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): show delivery and CI friction per author (#100840)

Julian Bez022da8034044
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index b0b07a0c1498..8b2a9bd697eb 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7372,6 +7372,18 @@ snapshots:
hash: v1.k794b7964.fadc2b2c0b5eedb49391586e0b3e5ea2aa845dd0b27c006cfad7389017158568.9Gke9ur_lx2xjtG29fVYUTYyUhDzjVg-dWWgpo5znTQ
scenes-app-discussions--threads--light:
hash: v1.k794b7964.28ac830bf83be5cbb6d7a397d67c9b9c61711904a822de38402b82220b0f7a49.7wENY7hvo1-qAJwq5fcsvKGJsfRAF_vDkpnM8iqFZcc
+ scenes-app-engineering-analytics-author--author--dark:
+ hash: v1.k794b7964.8520adcd3ce8680c16613e32f5d64566355a27bade6dfc442e19be47be8bfbb2._hZPqT7OcEhiSKDedzXlSpJpzb8jceYtcwwSyqB801A
+ scenes-app-engineering-analytics-author--author--light:
+ hash: v1.k794b7964.ad664cfe6903ddfe5bdc7bb15c1817088b89b858eb6e781d2eaa93bfcd6bd74d.KnT1_QSVMPtOR_dHTGSxaXVUDLtkjWcvqfWY_Dy3w3U
+ scenes-app-engineering-analytics-author--author-narrow--dark:
+ hash: v1.k794b7964.3bca0cb64645bdd887796aa0ccdc1e4f38ae3e91f6d536dd540b83fd72a3b91f.oXXTVcvEsGIrPvGCG0HR1FqpAwid9TXkQpa00ScMiYM
+ scenes-app-engineering-analytics-author--author-narrow--light:
+ hash: v1.k794b7964.29c171a5bdbe8125b19c449a55fef1ad52b249d6361d5785929473c53437208f.P_bjFcBIITGAsCj_c-Fo6jdxvgMJiKi1xqwS6x0X0uo
+ scenes-app-engineering-analytics-author--author-without-reviews-or-deploys--dark:
+ hash: v1.k794b7964.079499fddb5d88126b2fc93501d215aad1e361fd0622ec9e06aae82b0f81b1b3.X1gQOWOwe8W2YokDSb50W_fa0YC5LU0KyhI3S0wnsxs
+ scenes-app-engineering-analytics-author--author-without-reviews-or-deploys--light:
+ hash: v1.k794b7964.bea96d256929e856604648b09c72202d92938002ccd8042ceaa02a252172612d.x7UvuyHwU-uYlZiQXM5X2WYPiCte2j2OGUFfQeQ130A
scenes-app-engineering-analytics-delivery-pipeline--all-stages--dark:
hash: v1.k794b7964.e6fc5778d62714ed6fd4174b65c767a850d116b902223aa6f2086ce967edcaed.HoZOw65AQI9tW_L6CG_9JN6y7lmyhzy_Q1PQL__zCsk
scenes-app-engineering-analytics-delivery-pipeline--all-stages--light:
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index dbf16b613dff..227cbe2e8c8d 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -621,6 +621,8 @@ SPECTACULAR_SETTINGS = {
"EngineeringAnalyticsPRStateEnum": "products.engineering_analytics.backend.facade.contracts.PRState",
"QuarantineModeEnum": "products.engineering_analytics.backend.facade.contracts.QuarantineMode",
"CITestRunnerEnum": "products.engineering_analytics.backend.facade.contracts.CITestRunner",
+ "PRTimelineSegmentKindEnum": "products.engineering_analytics.backend.facade.contracts.PRTimelineSegmentKind",
+ "DeliveryScopeKindEnum": "products.engineering_analytics.backend.facade.contracts.DeliveryScopeKind",
"UserInterviewSearchDocumentTypeEnum": "products.user_interviews.backend.facade.enums.SEARCH_DOCUMENT_TYPES",
"DesktopAccessReasonEnum": "products.tasks.backend.facade.contracts.DESKTOP_ACCESS_REASON_SCHEMA_VALUES",
"LifecycleStatusEnum": "products.notebooks.backend.widget_models.WIDGET_LIFECYCLE_STATUS_CHOICES",
diff --git a/products/engineering_analytics/README.md b/products/engineering_analytics/README.md
index a02670a4c0d4..56f9fa80c68d 100644
--- a/products/engineering_analytics/README.md
+++ b/products/engineering_analytics/README.md
@@ -93,13 +93,13 @@ Shortening ready-for-review-to-merge is the headline metric this serves.
## The data boundary
-| Question | Substrate |
-| ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
-| CI and job durations, queue time, cost, failure logs, flaky and broken tests | Warehouse + Logs + Traces |
-| Open to merge time (coarse: `open_to_merge_seconds`) | PR snapshot |
-| Ready to merge time (`ready_to_merge_seconds`), draft/ready transitions | Warehouse `github_issue_events` (bounded window, grows forward) |
-| Approvals, review submissions | Warehouse `github_reviews` (synced; reads deferred until a wedge tool needs them) |
-| Deploys and DORA | Warehouse `github_deployments` + `github_deployment_statuses` |
+| Question | Substrate |
+| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
+| CI and job durations, queue time, cost, failure logs, flaky and broken tests | Warehouse + Logs + Traces |
+| Open to merge time (coarse: `open_to_merge_seconds`) | PR snapshot |
+| Ready to merge time (`ready_to_merge_seconds`), draft/ready transitions | Warehouse `github_issue_events` (bounded window, grows forward) |
+| Approvals, review submissions | Warehouse `github_reviews` (optional; the author page reads approvals) |
+| Deploys and DORA | Warehouse `github_deployments` + `github_deployment_statuses` |
The warehouse snapshots overwrite state on update, so transition timing is unrecoverable from them.
Immutable lifecycle events are the only thing the deferred events destination is for.
@@ -120,11 +120,11 @@ Change one only in a separate PR with a written reason. Engineering-level decisi
- Two first-class surfaces, one endpoint set: the in-app UI and MCP tools. Named typed endpoints run the curated read layer privately (no global HogQL views, core imports only the viewset); keep `mcp/tools.yaml` current whenever endpoints change.
- One sanctioned write: the test-health sidecar (quarantine, as an issue plus PR through the team's GitHub App). The write now lives behind the API and MCP tool only; the test-health UI became the Trunk quarantine debt scoreboard because Trunk's auto-quarantine outran the file-based flow as the thing teams need to see. No saved views or stateful filters; persisted surfaces are a separate decision.
- Data path: HogQL over the warehouse, plus reads from Logs and Traces. PR lifecycle event ingestion deferred. Product Postgres DB stays empty.
-- No author leaderboards or per-developer performance rankings, ever. The author page (own PRs plus own CI cost, reached only from PR-row author links) is allowed; ranking people against each other is not.
+- No author leaderboards or per-developer performance rankings, ever. The author page (one author's PRs, CI cost, delivery timing and lead time against the repository, reached only from PR-row author links) is allowed; ranking people against each other is not.
- Bots and drafts excluded by default in throughput / cycle-time reads; bot detection = `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`.
- Author identity = `Author{handle, display_name, avatar_url, is_bot}`. No PostHog-user mapping.
- Time to merge = `open_to_merge_seconds` = `merged_at - created_at`: coarse, and named so. `ready_to_merge_seconds` is the precise companion (last observed ready-for-review to merge, from `github_issue_events`); NULL means "not observed", never zero.
-- The GitHub `reviews` endpoint syncs, but review reads stay deferred until a wedge tool needs them.
+- The GitHub `reviews` endpoint syncs; the author page is its first reader (the approval split and the review states of a PR timeline).
## Glossary
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 0a049628d8fe..e9b428e55841 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -14,9 +14,8 @@ The goal is Signals for PostHog Desktop (README → "The goal"): Signal detectio
## 2. Non-goals
- Per-developer surveillance _rankings_, ever. They exist only to compare people.
- - No author leaderboards or cross-author rankings.
- - No per-developer performance/cycle-time scores: no author-scoped "median open→merge", no flaky-rate scoreboard.
- - The author-scoped _page_ is allowed: the author-filtered PR list plus that author's own CI **cost** (transparent spend, not a performance judgement), reachable only from the author links on PR rows.
+ - No author leaderboards or cross-author rankings: no read returns figures for more than one author, and no flaky-rate scoreboard.
+ - The author-scoped _page_ is allowed: one author's pull requests, CI cost, delivery timing and lead time, each figure next to the same figure over the whole repository. It answers "is my friction unusual here", never "who is slower", and it is reachable only from the author links on PR rows.
- Real-time alerting on individual PRs. That's notification surface, not analytics.
- Replacing GitHub's own UI. We surface signal, not the raw PR thread.
- Code-quality static analysis. Different product space.
@@ -154,7 +153,8 @@ Engineering-specific decisions. Product-level decisions live in README → Locke
- **CI Signals use immutable evidence.** Flaky checks require job rows from `github_workflow_jobs` showing a failed attempt followed by a successful later attempt for the same `(run_id, job)`. The run snapshot alone cannot prove this transition. Broken-default-branch detection reads GitHub's reported default branch from the PR snapshot's `base.repo`, the only full repository object in the tables this product reads (`query_default_branches` documents why the runs snapshot cannot answer it). A repo with no PR rows resolves nothing and is skipped: `repo_overview`'s master/main run-volume guess stays a display approximation, because a P1 needs GitHub's report, not inference. Detection gates on the canonical pass rate above. Duration comparisons require enough successful samples because the percentiles exclude failed and cancelled runs. All three conditions carry a week-stable `source_id`, and the coordinator records each emitted key in `SignalEmissionRecord` so an hourly sweep doesn't re-emit the same standing condition within its week. For broken-default-branch that means one signal per week per workflow, accepting that a distinct second breakage of the same workflow inside one week dedupes into the first rather than minting a signal (and a ledger row) per completed run.
- **HogQL only for analytics data.** No raw ClickHouse.
- **No product Postgres DB.** Analytics data lives in the warehouse / ClickHouse; any product-config model goes on the main DB as a team-scoped model (`TeamScopedRootMixin`), never a separate DB.
-- **No author leaderboards or per-developer performance rankings; the author page is allowed.** The surveillance risk is ranking people against each other, not an engineer viewing their own PRs and CI cost. The page is reachable only from PR-row author links; `author_workflow_costs` stays a UI-only read (MCP `enabled: false`).
+- **No author leaderboards or per-developer performance rankings; the author page is allowed.** The surveillance risk is ranking people against each other, not an engineer viewing their own friction. The delivery reads (`delivery_summary`, `pull_request_timelines`) take exactly one scope (one author, one GitHub team, or one pull request, defined once in `logic/delivery_scope.py`) and compare it with the repository, never with other authors or teams. A team scope matches authors through the `team_members` snapshot and matches nothing when it isn't synced. The author page is reachable only from PR-row author links; `author_workflow_costs` and the delivery reads stay UI-only (MCP `enabled: false`).
+- **A pull request timeline is replayed from immutable timestamps, defined once in `logic/pr_timeline.py`.** Run and job attempts, reviews and merge-queue gate runs become change points, and the state between two points follows one precedence: merge queue, out of the queue (open PRs, Trunk's current state), red checks, running checks, review state. A red stretch is labelled by what turned it green (a re-run of the same commit, the same job failing on the default branch within 12 hours, a later push), which is evidence about the cause, not proof of it. Every merge-queue state collapses into one span because the warehouse keeps no queue history. An author or team list reads CI from 30 days before the window at the earliest, so an older open pull request's timeline starts there; a single pull request is replayed whole.
- **Bot detection, defined once:** `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`. Hardcoded allowlist; per-team config deferred.
- **Bots and drafts excluded by default** in throughput / cycle-time reads; first-class in bot-impact analysis, so never strip them at the substrate.
- **Time to merge** = `open_to_merge_seconds` = `merged_at - created_at`, coarse (draft + ready combined). The precise companion is `ready_to_merge_seconds` = `merged_at` minus the last observed `ready_for_review` issue event (only the last draft/ready switch counts; a draft can't merge), falling back to `created_at` for a merged PR verifiably never drafted (no transition rows and its whole open-to-merge span inside the observed issue-event window, so the transitions can't merely be unsynced). NULL means "not observed", never zero: GitHub caps the issue-events history walk, so coverage grows forward from the first sync.
@@ -171,6 +171,7 @@ Warehouse tables (GitHub source):
- `github_workflow_runs`: CI runs. Webhook-only (the webhook is the source of truth; history is a deliberate one-off backfill). A settled run never changes, so durations and trends are precise; until settled, `status` / `conclusion` mutate (see the freshness caveat).
- `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.
Other products read as sources:
@@ -182,7 +183,7 @@ Other products read as sources:
- `github_deployments` + `github_deployment_statuses`: deploy requests and their status history (webhook-fed; statuses append one row per transition, with a bounded reconciliation fan-out for the `inactive` transitions GitHub never webhooks). The DORA substrate. Optional at the source, so reads must degrade gracefully when unsynced.
-Lifecycle data the snapshots can't hold and no synced endpoint records needs immutable timestamped events (GitHub webhooks → PostHog events, PR as group type). That is the only thing the deferred events destination is for. Reviews and approvals are not in that bucket: the GitHub `reviews` endpoint already syncs review submissions with their timestamps — only the reads stay deferred until a wedge tool needs them (README → Locked decisions). Deploys and DORA left the deferral the same way: `github_deployment_statuses` already holds the immutable transition history, so those reads run on the warehouse like everything else. See README → "The data boundary".
+Lifecycle data the snapshots can't hold and no synced endpoint records needs immutable timestamped events (GitHub webhooks → PostHog events, PR as group type). That is the only thing the deferred events destination is for. Reviews and approvals are not in that bucket: the GitHub `reviews` endpoint syncs review submissions with their timestamps, and the author page reads them. Deploys and DORA left the deferral the same way: `github_deployment_statuses` already holds the immutable transition history, so those reads run on the warehouse like everything else. See README → "The data boundary".
## 8. Reference reading
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index 72320796f56c..58d39f28085e 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,
+ DeliverySummary,
DoraOverview,
FlakyTestList,
GitHubSource,
@@ -41,6 +42,7 @@ from products.engineering_analytics.backend.facade.contracts import (
PRCostSummary,
PRLifecycle,
PullRequestList,
+ PullRequestTimelines,
QuarantineFile,
QuarantineRequest,
QuarantineRequestResult,
@@ -275,6 +277,51 @@ def list_author_workflow_costs(
)
+def get_delivery_summary(
+ *,
+ team: Team,
+ author: str | None = None,
+ github_team: str | 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,
+) -> DeliverySummary:
+ """Delivery figures for exactly one of ``author`` or ``github_team``, each against the repository."""
+ # Validate the scope before resolving the source, so a bad request reads as a bad scope.
+ scope = logic.DeliveryScope.from_params(author=author, github_team=github_team, pr_number=None, repo=None)
+ return logic.build_delivery_summary(
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
+ scope=scope,
+ date_from=date_from,
+ date_to=date_to,
+ )
+
+
+def get_pull_request_timelines(
+ *,
+ team: Team,
+ author: str | None = None,
+ github_team: str | None = None,
+ pr_number: int | None = None,
+ repo: str | None = None,
+ date_from: str | None = None,
+ date_to: str | None = None,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> PullRequestTimelines:
+ """Timelines for exactly one of ``author``, ``github_team``, or ``pr_number`` (which needs ``repo``)."""
+ # Validate the scope before resolving the source, so a bad request reads as a bad scope.
+ scope = logic.DeliveryScope.from_params(author=author, github_team=github_team, pr_number=pr_number, repo=repo)
+ return logic.build_pull_request_timelines(
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
+ scope=scope,
+ date_from=date_from,
+ date_to=date_to,
+ )
+
+
def list_workflow_jobs(
*,
team: Team,
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index f9740df2b212..fe995db0718c 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -1566,3 +1566,184 @@ class PathOwnership:
team_by_path: Mapping[str, str]
registry: Mapping[str, TeamEntry]
resolved: bool
+
+
+class DeliveryScopeKind(StrEnum):
+ """Which pull requests a delivery read covers. A scope is always exactly one author, one GitHub
+ team, or one pull request, so no delivery read puts people side by side (SPEC §2)."""
+
+ AUTHOR = "author"
+ GITHUB_TEAM = "github_team"
+ PULL_REQUEST = "pull_request"
+
+
+@dataclass(frozen=True)
+class ScopeRepoFigure:
+ """One figure measured twice over the same window: over the pull requests in scope, and over
+ every non-bot pull request in the repository (the scope included). None means the population
+ had nothing to measure, never zero."""
+
+ scope: float | None
+ repo: float | None
+
+
+@dataclass(frozen=True)
+class DurationDistribution:
+ """The box-plot summary of one per-PR duration, in seconds, over ``pr_count`` pull requests.
+ Every statistic is None when ``pr_count`` is 0."""
+
+ pr_count: int
+ min_seconds: float | None
+ p05_seconds: float | None
+ p25_seconds: float | None
+ p50_seconds: float | None
+ mean_seconds: float | None
+ p75_seconds: float | None
+ p95_seconds: float | None
+ max_seconds: float | None
+
+
+@dataclass(frozen=True)
+class ScopeRepoDistribution:
+ scope: DurationDistribution
+ repo: DurationDistribution
+
+
+@dataclass(frozen=True)
+class DeliveryLeadTime:
+ """Lead time to deploy for one scope against the repository, over the DORA deployed-PR
+ population (bots and drafts excluded, containment resolved through the deploy's head commit).
+
+ The distributions cover PRs whose first containing deploy succeeded in the window, so the
+ three stages compose. The coverage pair counts PRs merged in the window instead:
+ ``deployed_merged_pr_count`` of ``merged_pr_count`` reached a deploy. Deploy failure share and
+ recovery are per deploy and one deploy ships many PRs, so they are not attributable to an
+ author or a team and are not part of this type.
+ """
+
+ deploy_data_available: bool
+ # The environment names the lead time was scoped to (production by default).
+ environment_scope: str
+ merged_pr_count: int
+ deployed_merged_pr_count: int
+ open_to_deploy: ScopeRepoDistribution
+ open_to_merge: ScopeRepoDistribution
+ merge_to_deploy: ScopeRepoDistribution
+
+
+@dataclass(frozen=True)
+class DeliverySummary:
+ """Delivery and CI friction for one author's or one GitHub team's pull requests, each figure
+ against the repository.
+
+ Populations: PRs merged in the window, bots and drafts excluded, unless a field says otherwise.
+ Medians are per merged PR. The ``*_available`` flags say which optional source backs a figure;
+ a figure whose source is missing is None rather than a fake zero.
+ """
+
+ scope_kind: DeliveryScopeKind
+ # The author login or the GitHub team slug.
+ scope: str
+ # A team scope needs the membership table; without it the scope matches no pull requests.
+ has_membership_data: bool
+ # The optional sources behind the figures.
+ jobs_available: bool
+ review_data_available: bool
+ ready_data_available: bool
+ # Plain counts: no repo figure, because comparing volume ranks people.
+ opened_pr_count: int
+ merged_pr_count: int
+ open_pr_count: int
+ draft_pr_count: int
+ # CI spend. Cost includes merge-queue gate runs, which the PR's landing paid for.
+ cost_per_merged_pr_usd: ScopeRepoFigure
+ billable_minutes_per_merged_pr: ScopeRepoFigure
+ cost_per_push_usd: ScopeRepoFigure
+ total_cost_usd: float | None
+ total_billable_minutes: float | None
+ push_count: int
+ # Getting merged.
+ median_ready_to_merge_seconds: ScopeRepoFigure
+ p90_ready_to_merge_seconds: ScopeRepoFigure
+ median_ready_to_first_approval_seconds: ScopeRepoFigure
+ median_first_approval_to_merge_seconds: ScopeRepoFigure
+ before_first_approval_share: ScopeRepoFigure
+ pushes_after_approval_per_merged_pr: ScopeRepoFigure
+ merge_queue_attempts_per_merged_pr: ScopeRepoFigure
+ failed_merge_queue_share: ScopeRepoFigure
+ lead_time: DeliveryLeadTime
+
+
+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.
+ """
+
+ DRAFT = "draft"
+ WAITING_FOR_REVIEW = "waiting_for_review"
+ CHANGES_REQUESTED = "changes_requested"
+ APPROVED_NOT_ENQUEUED = "approved_not_enqueued"
+ # Review state without review data: the stretch is neither CI nor the queue, but who it waits on
+ # is unknown.
+ REVIEW_STATE_UNKNOWN = "review_state_unknown"
+ CI_RUNNING = "ci_running"
+ RED_PASSED_ON_RERUN = "red_passed_on_rerun"
+ RED_MASTER_BROKEN = "red_master_broken"
+ RED_FIXED_BY_PUSH = "red_fixed_by_push"
+ RED_NOT_PROVABLE = "red_not_provable"
+ MERGE_QUEUE = "merge_queue"
+ OUT_OF_MERGE_QUEUE = "out_of_merge_queue"
+
+
+@dataclass(frozen=True)
+class PRTimelineSegment:
+ kind: PRTimelineSegmentKind
+ started_at: datetime
+ ended_at: datetime
+
+
+@dataclass(frozen=True)
+class PRTimeline:
+ """One pull request's delivery timeline, from the moment it was ready for review (or opened,
+ for a draft) to its merge, its close, or now, as consecutive segments with no gaps."""
+
+ number: int
+ title: str
+ author: Author
+ repo: RepoRef
+ state: PRState
+ is_draft: bool
+ created_at: datetime
+ # Where the segments start: the last ready_for_review before the end, else created_at.
+ started_at: datetime
+ merged_at: datetime | None
+ # Distinct head commits that triggered CI, merge-queue gate runs excluded.
+ pushes: int
+ estimated_cost_usd: float | None
+ billable_minutes: float | None
+ segments: list[PRTimelineSegment]
+
+
+@dataclass(frozen=True)
+class PullRequestTimelines:
+ """The pull requests in one scope on a shared clock. An author or team scope lists every PR
+ still open plus every PR merged in the window (closed-unmerged PRs are not listed); a pull
+ request scope returns that one PR whatever its state. Capped at ``limit`` with ``truncated``."""
+
+ scope_kind: DeliveryScopeKind
+ # The author login, the GitHub team slug, or "owner/name#number".
+ scope: str
+ # A team scope needs the membership table; without it the scope matches no pull requests.
+ has_membership_data: bool
+ review_data_available: bool
+ jobs_available: bool
+ # True when the Trunk merge-queue table is synced, so an open PR out of the queue is visible.
+ merge_queue_state_available: bool
+ # The "now" every open PR's last segment ends at.
+ generated_at: datetime
+ items: list[PRTimeline]
+ truncated: bool
+ limit: int
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index b4e5952e89d5..7e6631f6415a 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -18,6 +18,11 @@ from products.engineering_analytics.backend.logic.ci_signals_config import (
get_ci_signals_config as get_ci_signals_config,
update_ci_signals_config as update_ci_signals_config,
)
+from products.engineering_analytics.backend.logic.delivery import (
+ build_delivery_summary as build_delivery_summary,
+ build_pull_request_timelines as build_pull_request_timelines,
+)
+from products.engineering_analytics.backend.logic.delivery_scope import DeliveryScope as DeliveryScope
from products.engineering_analytics.backend.logic.dora import (
build_dora_overview as build_dora_overview,
get_dora_environment_choices as get_dora_environment_choices,
diff --git a/products/engineering_analytics/backend/logic/delivery.py b/products/engineering_analytics/backend/logic/delivery.py
new file mode 100644
index 000000000000..de18428a0e8e
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/delivery.py
@@ -0,0 +1,45 @@
+"""Delivery orchestration: a scope's delivery summary and its pull request timelines.
+
+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.
+"""
+
+from products.engineering_analytics.backend.facade.contracts import (
+ DeliveryScopeKind,
+ DeliverySummary,
+ PullRequestTimelines,
+)
+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_summary import query_delivery_summary
+from products.engineering_analytics.backend.logic.queries.pull_request_timelines import query_pull_request_timelines
+
+
+def build_delivery_summary(
+ *,
+ curated: CuratedGitHubSource,
+ scope: DeliveryScope,
+ date_from: str | None = None,
+ date_to: str | None = None,
+) -> DeliverySummary:
+ if scope.kind == DeliveryScopeKind.PULL_REQUEST:
+ raise ValueError("the delivery summary takes an author or a github_team, not a single pull request")
+ parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)
+ return query_delivery_summary(curated=curated, scope=scope, date_from=parsed_from, date_to=parsed_to)
+
+
+def build_pull_request_timelines(
+ *,
+ curated: CuratedGitHubSource,
+ scope: DeliveryScope,
+ date_from: str | None = None,
+ date_to: str | None = None,
+) -> PullRequestTimelines:
+ # A single pull request is shown whatever its age, so neither end of the window applies to it.
+ single_pr = scope.kind == DeliveryScopeKind.PULL_REQUEST
+ window_from = None if single_pr else date_from
+ 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)
diff --git a/products/engineering_analytics/backend/logic/delivery_scope.py b/products/engineering_analytics/backend/logic/delivery_scope.py
new file mode 100644
index 000000000000..7f4cb69c58ec
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/delivery_scope.py
@@ -0,0 +1,83 @@
+"""Which pull requests a delivery read covers: one author's, one GitHub team's, or one pull request.
+
+Every delivery read (the summary figures and the pull request timelines) takes exactly one scope and
+compares it with the repository. A scope never holds more than one author or team, so no delivery read
+can put people side by side (SPEC §2). A team scope matches pull request authors through the
+``team_members`` snapshot, the same author→team rule the DORA team filter uses.
+"""
+
+from posthog.hogql import ast
+
+from posthog.dataclasses import frozen
+
+from products.engineering_analytics.backend.facade.contracts import DeliveryScopeKind
+from products.engineering_analytics.backend.logic._shared import _require_repo
+
+
+@frozen
+class DeliveryScope:
+ kind: DeliveryScopeKind
+ # Set for the AUTHOR kind only.
+ author: str | None = None
+ # Set for the GITHUB_TEAM kind only.
+ github_team: str | None = None
+ # Set for the PULL_REQUEST kind only.
+ pr_number: int | None = None
+ repo_owner: str | None = None
+ repo_name: str | None = None
+
+ @classmethod
+ def from_params(
+ cls, *, author: str | None, github_team: str | None, pr_number: int | None, repo: str | None
+ ) -> "DeliveryScope":
+ """Build a scope from caller input; raises ValueError unless exactly one scope is given."""
+ author = (author or "").strip() or None
+ github_team = (github_team or "").strip() or None
+ given = [value for value in (author, github_team, pr_number) if value is not None]
+ if len(given) != 1:
+ raise ValueError("pass exactly one of author, github_team or pr_number")
+ if author is not None:
+ return cls(kind=DeliveryScopeKind.AUTHOR, author=author)
+ if github_team is not None:
+ return cls(kind=DeliveryScopeKind.GITHUB_TEAM, github_team=github_team)
+ owner, name = _require_repo(repo)
+ return cls(kind=DeliveryScopeKind.PULL_REQUEST, pr_number=pr_number, repo_owner=owner, repo_name=name)
+
+ @property
+ def label(self) -> str:
+ """The scope as one string: the author login, the team slug, or 'owner/name#number'."""
+ if self.kind == DeliveryScopeKind.AUTHOR:
+ return self.author or ""
+ if self.kind == DeliveryScopeKind.GITHUB_TEAM:
+ return self.github_team or ""
+ return f"{self.repo_owner}/{self.repo_name}#{self.pr_number}"
+
+ def placeholders(self) -> dict[str, ast.Expr]:
+ """The HogQL placeholders ``pr_predicate`` reads."""
+ if self.kind == DeliveryScopeKind.AUTHOR:
+ return {"scope_author": ast.Constant(value=self.author)}
+ if self.kind == DeliveryScopeKind.GITHUB_TEAM:
+ return {"scope_team": ast.Constant(value=self.github_team)}
+ return {
+ "scope_pr_number": ast.Constant(value=self.pr_number),
+ "scope_repo_owner": ast.Constant(value=self.repo_owner),
+ "scope_repo_name": ast.Constant(value=self.repo_name),
+ }
+
+ def pr_predicate(self, *, members_source: str | None, prefix: str = "pr.") -> str:
+ """A SQL predicate over curated pull request columns (``prefix`` qualifies them) that is true for
+ the pull requests in scope. A team scope without membership data matches nothing, so a team
+ figure is never silently the whole repository."""
+ if self.kind == DeliveryScopeKind.AUTHOR:
+ return f"{prefix}author_handle = {{scope_author}}"
+ if self.kind == DeliveryScopeKind.GITHUB_TEAM:
+ if members_source is None:
+ return "0 = 1"
+ return (
+ f"{prefix}author_handle IN (SELECT member_handle FROM {members_source} AS scope_members "
+ "WHERE scope_members.team_slug = {scope_team})"
+ )
+ return (
+ f"{prefix}number = {{scope_pr_number}} AND {prefix}repo_owner = {{scope_repo_owner}} "
+ f"AND {prefix}repo_name = {{scope_repo_name}}"
+ )
diff --git a/products/engineering_analytics/backend/logic/pr_timeline.py b/products/engineering_analytics/backend/logic/pr_timeline.py
new file mode 100644
index 000000000000..c4d4253b2566
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/pr_timeline.py
@@ -0,0 +1,293 @@
+"""A pull request's delivery timeline: what it waited on at every moment from ready to merge.
+
+The warehouse holds immutable timestamps (run attempts, job attempts, reviews, merge-queue gate
+runs), not a state history, so the timeline is replayed from them. Every timestamp becomes a
+change point, the state is evaluated once per interval between two points, and equal neighbours
+merge into one segment. The evaluation is a fixed precedence, most blocking first:
+
+1. Merge queue: inside a gate attempt, or from the first gate attempt after the last push to the
+ merge. Every queue state (own test, a collateral restart, an ejection, a cancel gap) collapses
+ into this one span, because the warehouse keeps no queue transition history.
+2. Out of the merge queue: an open PR whose last gate attempt ended and whose current Trunk state
+ is failed or cancelled. Current state only, so this never appears on a merged PR.
+3. Red CI on the head commit, labelled by what turned it green (see ``_red_kind``).
+4. CI running on the head commit.
+5. Review state from each reviewer's latest verdict: changes requested with no push since while any
+ reviewer's latest verdict requests changes, approved when none does, else waiting for review.
+
+A commit's check state per workflow is its latest attempt: a re-run in flight reads as running,
+not red, the same way GitHub shows it.
+"""
+
+import bisect
+from collections import defaultdict
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from itertools import pairwise
+
+from posthog.dataclasses import frozen
+
+from products.engineering_analytics.backend.facade.contracts import PRTimelineSegment, PRTimelineSegmentKind
+from products.engineering_analytics.backend.logic.queries.master_failures import strip_shard_suffix
+from products.engineering_analytics.backend.logic.views.reviews import APPROVED_STATE, CHANGES_REQUESTED_STATE
+
+# A PR job failure counts as "master broken" when the same job failed on the default branch this
+# close to it. Wide enough for a master fix to take a few hours, narrow enough that an unrelated
+# failure of the same job days apart does not explain it.
+MASTER_FAILURE_PROXIMITY = timedelta(hours=12)
+
+
+@frozen
+class RunAttempt:
+ """One attempt of one workflow run on a PR commit, with merge-queue gate runs excluded."""
+
+ run_id: int
+ workflow_name: str
+ head_sha: str
+ attempt: int
+ # When the run was created, which is when its commit arrived. A queued run starts later.
+ pushed_at: datetime
+ started_at: datetime
+ # None while the attempt is still running.
+ completed_at: datetime | None
+ failed: bool
+ # Cancelled, neutral and action-required attempts are neither failed nor succeeded.
+ succeeded: bool
+ # Names of the jobs that failed in this attempt; empty when job data is not synced.
+ failed_jobs: tuple[str, ...]
+
+
+@frozen
+class GateAttempt:
+ """One merge-queue attempt for the PR: the gate branch's runs, bisection probes folded in."""
+
+ started_at: datetime
+ # None while any of the attempt's runs is still running.
+ completed_at: datetime | None
+
+
+@frozen
+class ReviewVerdict:
+ reviewer: str
+ state: str
+ submitted_at: datetime
+
+
+class MasterFailureIndex:
+ """Default-branch job failures, looked up by workflow and de-sharded job name."""
+
+ def __init__(self, failures: list[tuple[str, str, datetime]]) -> None:
+ self._completed: dict[tuple[str, str], list[datetime]] = defaultdict(list)
+ for workflow_name, job_name, completed_at in failures:
+ self._completed[(workflow_name, strip_shard_suffix(job_name))].append(completed_at)
+ for times in self._completed.values():
+ times.sort()
+
+ def explains(self, attempt: RunAttempt) -> bool:
+ """True when every failed job of the attempt also failed on the default branch close to it.
+ An attempt without job names (no job data) is never explained."""
+ if not attempt.failed_jobs or attempt.completed_at is None:
+ return False
+ return all(self._failed_near(attempt.workflow_name, job, attempt.completed_at) for job in attempt.failed_jobs)
+
+ def _failed_near(self, workflow_name: str, job_name: str, at: datetime) -> bool:
+ times = self._completed.get((workflow_name, strip_shard_suffix(job_name)), [])
+ index = bisect.bisect_left(times, at - MASTER_FAILURE_PROXIMITY)
+ return index < len(times) and times[index] <= at + MASTER_FAILURE_PROXIMITY
+
+
+@dataclass(frozen=True, kw_only=True)
+class PRTimelineInput:
+ started_at: datetime
+ # The merge, or now for an open PR.
+ ended_at: datetime
+ is_open: bool
+ is_merged: bool
+ is_draft: bool
+ attempts: list[RunAttempt]
+ gate_attempts: list[GateAttempt]
+ # None when the reviews table is not synced.
+ reviews: list[ReviewVerdict] | None
+ # Current Trunk state is failed or cancelled. Only meaningful for an open PR.
+ trunk_out_of_queue: bool
+
+
+@frozen
+class _QueueSpan:
+ started_at: datetime | None
+ ended_at: datetime | None
+
+
+@frozen
+class _Push:
+ head_sha: str
+ pushed_at: datetime
+ # Attempts per workflow, oldest first.
+ attempts_by_workflow: dict[str, list[RunAttempt]]
+
+
+class PRTimelineBuilder:
+ def __init__(self, pr: PRTimelineInput, master_failures: MasterFailureIndex) -> None:
+ self._pr = pr
+ self._master_failures = master_failures
+ self._pushes = self._group_pushes(pr.attempts)
+ self._push_times = [push.pushed_at for push in self._pushes]
+ self._verdicts = sorted(
+ (review for review in pr.reviews or [] if review.state in (APPROVED_STATE, CHANGES_REQUESTED_STATE)),
+ key=lambda review: review.submitted_at,
+ )
+ queue_span = self._queue_span()
+ self._queue_from, self._queue_until = queue_span.started_at, queue_span.ended_at
+
+ @staticmethod
+ def _group_pushes(attempts: list[RunAttempt]) -> list[_Push]:
+ by_sha: dict[str, list[RunAttempt]] = defaultdict(list)
+ for attempt in attempts:
+ by_sha[attempt.head_sha].append(attempt)
+ pushes = []
+ for head_sha, sha_attempts in by_sha.items():
+ by_workflow: dict[str, list[RunAttempt]] = defaultdict(list)
+ for attempt in sorted(sha_attempts, key=lambda a: (a.started_at, a.attempt)):
+ by_workflow[attempt.workflow_name].append(attempt)
+ pushed_at = min(attempt.pushed_at for attempt in sha_attempts)
+ pushes.append(_Push(head_sha=head_sha, pushed_at=pushed_at, attempts_by_workflow=dict(by_workflow)))
+ return sorted(pushes, key=lambda push: push.pushed_at)
+
+ def _queue_span(self) -> _QueueSpan:
+ """The continuous queue stretch: from the first gate attempt after the last push to the merge
+ (merged PR), or to the end of the last gate attempt (open or closed PR; the end while one still runs)."""
+ last_push_at = self._push_times[-1] if self._push_times else None
+ after_last_push = [
+ gate for gate in self._pr.gate_attempts if last_push_at is None or gate.started_at >= last_push_at
+ ]
+ if not after_last_push:
+ return _QueueSpan(started_at=None, ended_at=None)
+ queue_from = min(gate.started_at for gate in after_last_push)
+ if self._pr.is_merged or any(gate.completed_at is None for gate in after_last_push):
+ return _QueueSpan(started_at=queue_from, ended_at=self._pr.ended_at)
+ return _QueueSpan(
+ started_at=queue_from,
+ ended_at=max(gate.completed_at for gate in after_last_push if gate.completed_at is not None),
+ )
+
+ def build(self) -> list[PRTimelineSegment]:
+ start, end = self._pr.started_at, self._pr.ended_at
+ if end <= start:
+ return []
+ if self._pr.is_draft:
+ return [PRTimelineSegment(kind=PRTimelineSegmentKind.DRAFT, started_at=start, ended_at=end)]
+
+ points = sorted({start, end, *(point for point in self._change_points() if start < point < end)})
+ segments: list[PRTimelineSegment] = []
+ for left, right in pairwise(points):
+ kind = self._kind_at(left)
+ if segments and segments[-1].kind == kind:
+ segments[-1] = PRTimelineSegment(kind=kind, started_at=segments[-1].started_at, ended_at=right)
+ else:
+ segments.append(PRTimelineSegment(kind=kind, started_at=left, ended_at=right))
+ return segments
+
+ def _change_points(self) -> list[datetime]:
+ points: list[datetime] = [*self._push_times]
+ for attempt in self._pr.attempts:
+ points.append(attempt.started_at)
+ if attempt.completed_at is not None:
+ points.append(attempt.completed_at)
+ for gate in self._pr.gate_attempts:
+ points.append(gate.started_at)
+ if gate.completed_at is not None:
+ points.append(gate.completed_at)
+ points.extend(review.submitted_at for review in self._verdicts)
+ points.extend(point for point in (self._queue_from, self._queue_until) if point is not None)
+ return points
+
+ def _kind_at(self, at: datetime) -> PRTimelineSegmentKind:
+ if self._in_queue(at):
+ return PRTimelineSegmentKind.MERGE_QUEUE
+ if self._pr.is_open and self._pr.trunk_out_of_queue and self._queue_until and at >= self._queue_until:
+ return PRTimelineSegmentKind.OUT_OF_MERGE_QUEUE
+ push = self._head_at(at)
+ if push is not None:
+ failed, running = self._check_state(push, at)
+ if failed:
+ return self._red_kind(push, failed, at)
+ if running:
+ return PRTimelineSegmentKind.CI_RUNNING
+ return self._review_kind(push, at)
+
+ def _in_queue(self, at: datetime) -> bool:
+ if (
+ self._queue_from is not None
+ and self._queue_until is not None
+ and self._queue_from <= at < self._queue_until
+ ):
+ return True
+ return any(
+ gate.started_at <= at and (gate.completed_at is None or at < gate.completed_at)
+ for gate in self._pr.gate_attempts
+ )
+
+ def _head_at(self, at: datetime) -> _Push | None:
+ index = bisect.bisect_right(self._push_times, at)
+ return self._pushes[index - 1] if index else None
+
+ @staticmethod
+ def _check_state(push: _Push, at: datetime) -> tuple[list[RunAttempt], bool]:
+ """The head commit's failed latest attempts and whether any latest attempt still runs."""
+ failed: list[RunAttempt] = []
+ running = False
+ for attempts in push.attempts_by_workflow.values():
+ started = [attempt for attempt in attempts if attempt.started_at <= at]
+ if not started:
+ continue
+ latest = started[-1]
+ if latest.completed_at is None or latest.completed_at > at:
+ running = True
+ elif latest.failed:
+ failed.append(latest)
+ return failed, running
+
+ def _red_kind(self, push: _Push, failed: list[RunAttempt], at: datetime) -> PRTimelineSegmentKind:
+ """What turned the red checks green, in order of how much it clears the author:
+
+ - passed on a re-run: every failed workflow passed a later attempt on the same commit;
+ - master broken: every failed job failed on the default branch close to the failure;
+ - fixed by a push: a later commit arrived before the end;
+ - not provable: none of those, including a check that is still red now.
+
+ A mix of causes across workflows falls through to the weaker label on purpose.
+ """
+ if all(self._passed_later(push, attempt) for attempt in failed):
+ return PRTimelineSegmentKind.RED_PASSED_ON_RERUN
+ if all(self._master_failures.explains(attempt) for attempt in failed):
+ return PRTimelineSegmentKind.RED_MASTER_BROKEN
+ if bisect.bisect_right(self._push_times, at) < len(self._pushes):
+ return PRTimelineSegmentKind.RED_FIXED_BY_PUSH
+ return PRTimelineSegmentKind.RED_NOT_PROVABLE
+
+ @staticmethod
+ def _passed_later(push: _Push, failed: RunAttempt) -> bool:
+ assert failed.completed_at is not None
+ return any(
+ attempt.started_at >= failed.completed_at and attempt.completed_at is not None and attempt.succeeded
+ for attempt in push.attempts_by_workflow[failed.workflow_name]
+ )
+
+ def _review_kind(self, push: _Push | None, at: datetime) -> PRTimelineSegmentKind:
+ if self._pr.reviews is None:
+ return PRTimelineSegmentKind.REVIEW_STATE_UNKNOWN
+ # GitHub keeps a change request open until the same reviewer approves, so another reviewer's
+ # approval does not clear it. Only each reviewer's latest verdict counts.
+ latest_by_reviewer: dict[str, ReviewVerdict] = {}
+ for review in self._verdicts:
+ if review.submitted_at > at:
+ break
+ latest_by_reviewer[review.reviewer] = review
+ if not latest_by_reviewer:
+ return PRTimelineSegmentKind.WAITING_FOR_REVIEW
+ change_requests = [review for review in latest_by_reviewer.values() if review.state == CHANGES_REQUESTED_STATE]
+ if not change_requests:
+ return PRTimelineSegmentKind.APPROVED_NOT_ENQUEUED
+ if push is not None and push.pushed_at > max(review.submitted_at for review in change_requests):
+ return PRTimelineSegmentKind.WAITING_FOR_REVIEW
+ return PRTimelineSegmentKind.CHANGES_REQUESTED
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index 3b94046db6ba..f6ded46b1890 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -41,6 +41,7 @@ from products.engineering_analytics.backend.logic.views import (
issue_events,
job_costs,
pull_requests,
+ reviews,
team_members,
trunk_merge_queue,
trunk_quarantined_tests,
@@ -247,6 +248,13 @@ class CuratedGitHubSource:
return None
return f"({issue_events.build_query(self._tables.issue_events)})"
+ def reviews_source(self) -> str | None:
+ """Curated submitted-reviews ``SELECT`` subquery, or None when the optional reviews table
+ isn't synced."""
+ if not self._tables.reviews:
+ return None
+ return f"({reviews.build_query(self._tables.reviews)})"
+
def deploy_sources(self) -> "DeploySources | None":
"""The curated deploy ``SELECT`` subqueries, or None when the optional deploy pair isn't
fully synced. Gated on BOTH tables in one place: a deployment's outcome lives on its
diff --git a/products/engineering_analytics/backend/logic/queries/delivery_summary.py b/products/engineering_analytics/backend/logic/queries/delivery_summary.py
new file mode 100644
index 000000000000..ef996d37acdd
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/delivery_summary.py
@@ -0,0 +1,480 @@
+"""Curated query: delivery and CI friction for one scope (an author or a GitHub team) against the repository.
+
+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.
+"""
+
+import math
+import statistics
+from collections import defaultdict
+from collections.abc import Callable
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+
+from posthog.hogql import ast
+
+from products.engineering_analytics.backend.facade.contracts import (
+ DeliveryLeadTime,
+ DeliverySummary,
+ DurationDistribution,
+ ScopeRepoDistribution,
+ ScopeRepoFigure,
+)
+from products.engineering_analytics.backend.logic.cost import PRCostAggregate
+from products.engineering_analytics.backend.logic.delivery_scope import DeliveryScope
+from products.engineering_analytics.backend.logic.merge_queue import GATE_RUN_LOOKBACK, gate_attempt_expr
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._workflow_filters import (
+ DECISIVE_FAILURE_CONCLUSIONS_SQL,
+ 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.views.reviews import APPROVED_STATE
+
+# How far before the window a merged PR's CI is still counted. A PR merged in the window usually
+# ran its CI days before; older runs are left out so the runs and jobs scans stay bounded.
+CI_LOOKBACK = timedelta(days=30)
+
+_ROW_LIMIT = 100000
+
+_MERGED_SELECT = f"""
+ SELECT
+ pr.number,
+ (__SCOPE__) AS in_scope,
+ pr.created_at,
+ pr.merged_at,
+ __READY_TO_MERGE__ AS ready_to_merge_seconds
+ FROM __PR_SOURCE__ AS pr
+ __READY_JOIN__
+ WHERE pr.merged_at IS NOT NULL AND pr.merged_at >= {{date_from}} __DATE_TO__
+ AND NOT pr.is_bot AND NOT pr.is_draft
+ LIMIT {_ROW_LIMIT}
+"""
+
+# Open and draft counts are current state, so they ignore the window.
+_SCOPE_COUNTS_SELECT = """
+ SELECT
+ countIf(pr.created_at >= {date_from} __DATE_TO__) AS opened,
+ countIf(pr.state = 'open' AND NOT pr.is_draft) AS open_now,
+ countIf(pr.state = 'open' AND pr.is_draft) AS drafts
+ FROM __PR_SOURCE__ AS pr
+ WHERE NOT pr.is_bot AND (__SCOPE__)
+"""
+
+_APPROVALS_SELECT = f"""
+ SELECT pr_number, groupArray(submitted_at) AS approved_at
+ FROM __REVIEWS_SOURCE__ AS rv
+ WHERE state = '{APPROVED_STATE}' AND pr_number IN {{pr_numbers}}
+ GROUP BY pr_number
+ LIMIT {_ROW_LIMIT}
+"""
+
+# A push is a distinct head commit that triggered CI; gate runs are the queue's rebases, not pushes.
+# The run's creation time is when the commit arrived: a queued run starts later.
+_PUSHES_SELECT = f"""
+ SELECT pr_number, groupArray(pushed_at) AS pushed_at
+ FROM (
+ SELECT pr_number, head_sha, min(created_at) AS pushed_at
+ FROM __RUNS_SOURCE__ AS r
+ WHERE pr_number IN {{pr_numbers}} AND NOT is_merge_queue AND run_started_at >= {{run_from}}
+ GROUP BY pr_number, head_sha
+ )
+ GROUP BY pr_number
+ LIMIT {_ROW_LIMIT}
+"""
+
+_GATE_ATTEMPTS_SELECT = f"""
+ SELECT
+ r.pr_number AS pr_number,
+ __GATE_ATTEMPT__ AS attempt,
+ min(r.run_started_at) AS started_at,
+ max(r.status = 'completed' AND r.conclusion IN ({DECISIVE_FAILURE_CONCLUSIONS_SQL})) AS failed
+ FROM __RUNS_SOURCE__ AS r
+ WHERE r.is_merge_queue AND r.pr_number IN {{pr_numbers}} AND r.run_started_at >= {{gate_from}}
+ GROUP BY pr_number, attempt
+ LIMIT 1000000
+"""
+
+
+@dataclass(frozen=True, kw_only=True)
+class _GateAttempt:
+ started_at: datetime
+ failed: bool
+
+
+@dataclass(frozen=True, kw_only=True)
+class MergedPRFacts:
+ """The per-PR facts behind every scope and repo figure."""
+
+ number: int
+ in_scope: bool
+ created_at: datetime
+ merged_at: datetime
+ ready_to_merge_seconds: int | None
+ approved_at: list[datetime]
+ pushed_at: list[datetime]
+ gate_attempts: list[_GateAttempt]
+ cost: PRCostAggregate | None
+
+ @property
+ def ready_at(self) -> datetime | None:
+ if self.ready_to_merge_seconds is None:
+ return None
+ return self.merged_at - timedelta(seconds=self.ready_to_merge_seconds)
+
+ @property
+ def first_approval_at(self) -> datetime | None:
+ """The first approval after the PR went ready. An approval that landed while the PR was a
+ draft counts as approved at ready: nobody waited on a reviewer after that point."""
+ ready_at = self.ready_at
+ if ready_at is None or not self.approved_at:
+ return None
+ after_ready = [at for at in self.approved_at if ready_at <= at <= self.merged_at]
+ if after_ready:
+ return min(after_ready)
+ return ready_at if min(self.approved_at) < ready_at else None
+
+ @property
+ def pushes(self) -> int:
+ return sum(1 for at in self.pushed_at if at <= self.merged_at)
+
+ @property
+ def landing_gate_attempts(self) -> list[_GateAttempt]:
+ # Bisection probes after the merge are not attempts to land it.
+ return [gate for gate in self.gate_attempts if gate.started_at <= self.merged_at]
+
+
+def quantile(values: list[float], q: float) -> float | None:
+ """Linear-interpolation quantile (numpy's default), None over an empty list."""
+ if not values:
+ return None
+ ordered = sorted(values)
+ position = (len(ordered) - 1) * q
+ lower = math.floor(position)
+ upper = math.ceil(position)
+ return ordered[lower] + (ordered[upper] - ordered[lower]) * (position - lower)
+
+
+def duration_distribution(values: list[float]) -> DurationDistribution:
+ return DurationDistribution(
+ pr_count=len(values),
+ min_seconds=min(values) if values else None,
+ p05_seconds=quantile(values, 0.05),
+ p25_seconds=quantile(values, 0.25),
+ p50_seconds=quantile(values, 0.5),
+ mean_seconds=statistics.fmean(values) if values else None,
+ p75_seconds=quantile(values, 0.75),
+ p95_seconds=quantile(values, 0.95),
+ max_seconds=max(values) if values else None,
+ )
+
+
+def _median_cost(facts: list[MergedPRFacts]) -> float | None:
+ return quantile([f.cost.estimated_cost_usd for f in facts if f.cost and f.cost.estimated_cost_usd is not None], 0.5)
+
+
+def _median_billable_minutes(facts: list[MergedPRFacts]) -> float | None:
+ return quantile([f.cost.billable_seconds / 60 for f in facts if f.cost and f.cost.costed_jobs], 0.5)
+
+
+def _cost_per_push(facts: list[MergedPRFacts]) -> float | None:
+ costed = [f for f in facts if f.cost and f.cost.estimated_cost_usd is not None and f.pushes]
+ pushes = sum(f.pushes for f in costed)
+ if not pushes:
+ return None
+ return sum(f.cost.estimated_cost_usd for f in costed if f.cost and f.cost.estimated_cost_usd is not None) / pushes
+
+
+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]
+
+
+@dataclass(frozen=True, kw_only=True)
+class _ApprovalSplit:
+ before_seconds: float
+ after_seconds: float
+
+
+def _approval_splits(facts: list[MergedPRFacts]) -> list[_ApprovalSplit]:
+ splits = []
+ for fact in facts:
+ ready_at, approved_at = fact.ready_at, fact.first_approval_at
+ if ready_at is None or approved_at is None or fact.ready_to_merge_seconds is None:
+ continue
+ before = min(max((approved_at - ready_at).total_seconds(), 0.0), float(fact.ready_to_merge_seconds))
+ splits.append(_ApprovalSplit(before_seconds=before, after_seconds=fact.ready_to_merge_seconds - before))
+ return splits
+
+
+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 _pushes_after_approval(facts: list[MergedPRFacts]) -> float | None:
+ counts = []
+ for fact in facts:
+ approved_at = fact.first_approval_at
+ if approved_at is None:
+ continue
+ counts.append(sum(1 for at in fact.pushed_at if approved_at < at <= fact.merged_at))
+ return statistics.fmean(counts) if counts else None
+
+
+def _queue_attempts(facts: list[MergedPRFacts]) -> float | None:
+ counts = [len(f.landing_gate_attempts) for f in facts if f.landing_gate_attempts]
+ return statistics.fmean(counts) if counts else None
+
+
+def _failed_queue_share(facts: list[MergedPRFacts]) -> float | None:
+ queued = [f for f in facts if f.landing_gate_attempts]
+ if not queued:
+ return 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(lambda facts: quantile([split.before_seconds for split in _approval_splits(facts)], 0.5))
+
+ 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))
+
+ 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 _lead_time(
+ curated: CuratedGitHubSource,
+ *,
+ scope: DeliveryScope,
+ date_from: datetime,
+ date_to: datetime | None,
+ scope_merged_count: int,
+) -> DeliveryLeadTime:
+ deployed = query_deployed_prs(
+ curated=curated,
+ date_from=date_from,
+ date_to=date_to,
+ scope_predicate=scope.pr_predicate(members_source=curated.members_source(), prefix=""),
+ scope_placeholders=scope.placeholders(),
+ )
+ empty = duration_distribution([])
+ if deployed is None:
+ empty_pair = ScopeRepoDistribution(scope=empty, repo=empty)
+ return DeliveryLeadTime(
+ deploy_data_available=False,
+ environment_scope="",
+ merged_pr_count=scope_merged_count,
+ deployed_merged_pr_count=0,
+ open_to_deploy=empty_pair,
+ open_to_merge=empty_pair,
+ merge_to_deploy=empty_pair,
+ )
+
+ def in_window(at: datetime) -> bool:
+ return at >= date_from and (date_to is None or at <= date_to)
+
+ repo_rows = [row for row in deployed.rows if in_window(row.deployed_at)]
+ scope_rows = [row for row in repo_rows if row.in_scope]
+
+ def pair(stage: Callable[[DeployedPR], float]) -> ScopeRepoDistribution:
+ return ScopeRepoDistribution(
+ scope=duration_distribution([stage(row) for row in scope_rows]),
+ repo=duration_distribution([stage(row) for row in repo_rows]),
+ )
+
+ return DeliveryLeadTime(
+ deploy_data_available=True,
+ environment_scope=deployed.environment_scope,
+ merged_pr_count=scope_merged_count,
+ deployed_merged_pr_count=sum(1 for row in deployed.rows if row.in_scope and in_window(row.merged_at)),
+ 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()),
+ )
+
+
+def _query_merged_facts(
+ curated: CuratedGitHubSource, *, scope: DeliveryScope, date_from: datetime, date_to: datetime | None
+) -> list[MergedPRFacts]:
+ 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(members_source=curated.members_source()))
+ .replace("__READY_TO_MERGE__", ready.expr)
+ .replace("__READY_JOIN__", ready.join)
+ .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
+ )
+ 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})
+ if not pr_numbers:
+ return []
+
+ run_from = date_from - CI_LOOKBACK
+ numbers = 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 []}
+
+ runs_source = curated.run_source(started_floor=True)
+ pushes_response = curated.run(
+ _PUSHES_SELECT.replace("__RUNS_SOURCE__", runs_source),
+ query_type="engineering_analytics.delivery_summary_pushes",
+ placeholders={
+ "pr_numbers": numbers,
+ "run_from": ast.Constant(value=run_from),
+ "run_started_floor": run_started_floor_constant(run_from),
+ },
+ )
+ pushes = {int(number): [at for at in times if at is not None] for number, times in pushes_response.results or []}
+
+ gate_from = date_from - GATE_RUN_LOOKBACK
+ gates_response = curated.run(
+ _GATE_ATTEMPTS_SELECT.replace("__RUNS_SOURCE__", runs_source).replace(
+ "__GATE_ATTEMPT__", gate_attempt_expr("r.head_branch")
+ ),
+ query_type="engineering_analytics.delivery_summary_gate_attempts",
+ placeholders={
+ "pr_numbers": numbers,
+ "gate_from": ast.Constant(value=gate_from),
+ "run_started_floor": run_started_floor_constant(gate_from),
+ },
+ )
+ gates: dict[int, list[_GateAttempt]] = defaultdict(list)
+ for number, _attempt, started_at, failed in gates_response.results or []:
+ 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)
+
+ 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)),
+ )
+ for number, in_scope, created_at, merged_at, ready_seconds in rows
+ ]
+
+
+def query_delivery_summary(
+ *, curated: CuratedGitHubSource, scope: DeliveryScope, 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
+
+ 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(members_source=curated.members_source()))
+ .replace("__DATE_TO__", date_to_clause)
+ .replace("__PR_SOURCE__", curated.pr_source()),
+ query_type="engineering_analytics.delivery_summary_counts",
+ placeholders=placeholders,
+ )
+ opened, open_now, drafts = counts.results[0] if counts.results else (0, 0, 0)
+
+ jobs_available = curated.jobs_source() is not None
+ costed = [f.cost for f in scope_facts if f.cost and f.cost.estimated_cost_usd is not None]
+ return DeliverySummary(
+ scope_kind=scope.kind,
+ scope=scope.label,
+ has_membership_data=curated.members_source() is not None,
+ jobs_available=jobs_available,
+ review_data_available=curated.reviews_source() is not None,
+ ready_data_available=curated.ready_to_merge_sql().observable,
+ opened_pr_count=int(opened or 0),
+ 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(),
+ total_cost_usd=sum(cost.estimated_cost_usd for cost in costed if cost.estimated_cost_usd is not None)
+ if costed
+ else None,
+ total_billable_minutes=sum(f.cost.billable_seconds for f in scope_facts if f.cost) / 60
+ 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(),
+ 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/dora.py b/products/engineering_analytics/backend/logic/queries/dora.py
index 2fc67a294ae3..b3948d5d0d66 100644
--- a/products/engineering_analytics/backend/logic/queries/dora.py
+++ b/products/engineering_analytics/backend/logic/queries/dora.py
@@ -48,7 +48,7 @@ from products.engineering_analytics.backend.logic.queries._buckets import (
pick_granularity,
window_buckets,
)
-from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_float
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, DeploySources, opt_float
from products.engineering_analytics.backend.logic.queries._workflow_filters import (
run_started_floor_constant,
window_pair_predicates,
@@ -229,6 +229,7 @@ _DEPLOYED_PRS_CTE = """
deployed_prs AS (
SELECT
pr.number AS number,
+ pr.author_handle AS author_handle,
pr.created_at AS created_at,
pr.merged_at AS merged_at,
min(h.first_success_at) AS deployed_at
@@ -240,7 +241,7 @@ _DEPLOYED_PRS_CTE = """
AND NOT pr.is_draft
__TEAM_FILTER__
AND h.head_merged_at >= pr.merged_at
- GROUP BY pr.number, pr.created_at, pr.merged_at
+ GROUP BY pr.number, pr.author_handle, pr.created_at, pr.merged_at
)
"""
@@ -651,34 +652,26 @@ def _query_lead_time(scan: _DoraScan, *, github_team: str | None, members_source
)
-def query_dora_overview(
- *,
+@frozen
+class _ScopedScan:
+ scan: _DoraScan
+ environment_scope: _EnvironmentScope
+ # The picker's options: persistent environments deployed to in the scan window.
+ environments: list[str]
+
+
+def _scoped_scan(
curated: CuratedGitHubSource,
+ deploy_sources: DeploySources,
+ *,
date_from: datetime,
date_to: datetime | None,
- validated_environments: list[str] | None = None,
- github_team: str | None = None,
- granularity: Granularity | None = None,
-) -> DoraOverview:
- granularity = granularity or pick_granularity(date_from, date_to)
- deploy_sources = curated.deploy_sources()
- members_source = curated.members_source()
- has_membership_data = members_source is not None
- github_teams = _query_github_teams(curated, members_source)
-
- if deploy_sources is None:
- return _empty_overview(
- deploy_data_available=False,
- environment_scope=", ".join(validated_environments) if validated_environments else "persistent",
- environments=[],
- has_membership_data=has_membership_data,
- github_teams=github_teams,
- granularity=granularity,
- )
-
+ validated_environments: list[str] | None,
+ granularity: Granularity,
+) -> _ScopedScan:
+ """Resolve the environment scope and bind the deploys CTE and placeholders every deploy read shares."""
end = date_to or datetime.now(tz=date_from.tzinfo)
prev_from = date_from - (end - date_from)
- window_days = max((end - date_from).total_seconds() / 86400, 1 / 24)
placeholders: dict[str, ast.Expr] = {
"date_from": ast.Constant(value=date_from),
@@ -730,6 +723,45 @@ def query_dora_overview(
date_to=date_to,
granularity=granularity,
)
+ return _ScopedScan(scan=scan, environment_scope=env_scope, environments=environments)
+
+
+def query_dora_overview(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ date_to: datetime | None,
+ validated_environments: list[str] | None = None,
+ github_team: str | None = None,
+ granularity: Granularity | None = None,
+) -> DoraOverview:
+ granularity = granularity or pick_granularity(date_from, date_to)
+ deploy_sources = curated.deploy_sources()
+ members_source = curated.members_source()
+ has_membership_data = members_source is not None
+ github_teams = _query_github_teams(curated, members_source)
+
+ if deploy_sources is None:
+ return _empty_overview(
+ deploy_data_available=False,
+ environment_scope=", ".join(validated_environments) if validated_environments else "persistent",
+ environments=[],
+ has_membership_data=has_membership_data,
+ github_teams=github_teams,
+ granularity=granularity,
+ )
+
+ end = date_to or datetime.now(tz=date_from.tzinfo)
+ window_days = max((end - date_from).total_seconds() / 86400, 1 / 24)
+ scoped = _scoped_scan(
+ curated,
+ deploy_sources,
+ date_from=date_from,
+ date_to=date_to,
+ validated_environments=validated_environments,
+ granularity=granularity,
+ )
+ scan, env_scope, environments = scoped.scan, scoped.environment_scope, scoped.environments
outcomes = _query_deploy_outcomes(scan)
lead = _query_lead_time(scan, github_team=github_team, members_source=members_source)
@@ -767,6 +799,86 @@ def query_dora_overview(
)
+# Every deployed PR relevant to one window, one row each: deployed in the window (the distribution
+# population) or merged in it (the attribution-coverage population). The author page splits the
+# rows in Python, so the containment rule stays defined once, in the CTEs above.
+_DEPLOYED_PR_ROWS_SELECT = """
+ SELECT number, (__SCOPE__) AS in_scope, created_at, merged_at, deployed_at
+ FROM deployed_prs
+ WHERE (deployed_at >= {date_from} __DATE_TO_DEPLOYED__) OR (merged_at >= {date_from} __DATE_TO_MERGED__)
+ LIMIT 100000
+"""
+
+
+@frozen
+class DeployedPR:
+ number: int
+ # True when the caller's scope predicate matches the PR.
+ in_scope: bool
+ created_at: datetime
+ merged_at: datetime
+ # The first successful in-scope deployment that contains the merge.
+ deployed_at: datetime
+
+
+@frozen
+class DeployedPRs:
+ environment_scope: str
+ rows: list[DeployedPR]
+
+
+def query_deployed_prs(
+ *,
+ curated: CuratedGitHubSource,
+ date_from: datetime,
+ date_to: datetime | None,
+ scope_predicate: str,
+ scope_placeholders: dict[str, ast.Expr],
+) -> DeployedPRs | None:
+ """The deployed-PR population behind lead time, in the default (production) environment scope,
+ as rows. ``scope_predicate`` is a trusted SQL predicate over the unqualified ``deployed_prs``
+ columns that marks each row ``in_scope``; its placeholders ride in ``scope_placeholders``. None
+ when the deploy tables aren't synced."""
+ deploy_sources = curated.deploy_sources()
+ if deploy_sources is None:
+ return None
+ scoped = _scoped_scan(
+ curated,
+ deploy_sources,
+ date_from=date_from,
+ date_to=date_to,
+ validated_environments=None,
+ granularity=pick_granularity(date_from, date_to),
+ )
+ scan = scoped.scan
+ pr_source = curated.pr_source()
+ sql = f"WITH {scan.deploys_cte}, {_DEPLOY_HEADS_CTE}, {_DEPLOYED_PRS_CTE} " + (
+ _DEPLOYED_PR_ROWS_SELECT.replace("__DATE_TO_DEPLOYED__", scan.date_to_filter("deployed_at")).replace(
+ "__DATE_TO_MERGED__", scan.date_to_filter("merged_at")
+ )
+ )
+ sql = (
+ sql.replace("__PR_SOURCE__", pr_source)
+ .replace("__RUNS_SOURCE__", curated.run_source(started_floor=True))
+ .replace("__TEAM_FILTER__", "")
+ .replace("__SCOPE__", scope_predicate)
+ )
+ scan.placeholders.update(scope_placeholders)
+ response = scan.run(sql, query_type="engineering_analytics.deployed_pr_rows")
+ rows = [
+ DeployedPR(
+ number=int(number),
+ in_scope=bool(in_scope),
+ created_at=created_at,
+ merged_at=merged_at,
+ deployed_at=deployed_at,
+ )
+ for number, in_scope, created_at, merged_at, deployed_at in response.results or []
+ if created_at is not None and merged_at is not None and deployed_at is not None
+ ]
+ return DeployedPRs(environment_scope=scoped.environment_scope.scope, rows=rows)
+
+
def _lead_time_bucket(bucket: datetime, stats: tuple[Any, ...] | None, *, stage: int) -> LeadTimeBucket:
"""One stage's bucket off a series row: ``stats`` is (count, then a _STAGE_STAT_WIDTH-wide
slice per stage, in _LEAD_TIME_STAGES order); ``stage`` picks which slice."""
diff --git a/products/engineering_analytics/backend/logic/queries/pr_cost.py b/products/engineering_analytics/backend/logic/queries/pr_cost.py
index dc1ae3d3ecd9..2435dc4fe24f 100644
--- a/products/engineering_analytics/backend/logic/queries/pr_cost.py
+++ b/products/engineering_analytics/backend/logic/queries/pr_cost.py
@@ -238,6 +238,44 @@ def query_pr_list_costs(
}
+# 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).
diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py b/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py
new file mode 100644
index 000000000000..a3fca7a9b81f
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py
@@ -0,0 +1,506 @@
+"""Curated query: pull requests in one scope as delivery timelines.
+
+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.
+
+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.
+"""
+
+from collections import defaultdict
+from datetime import UTC, datetime, timedelta
+
+from posthog.hogql import ast
+
+from posthog.dataclasses import frozen
+
+from products.engineering_analytics.backend.facade.contracts import (
+ Author,
+ DeliveryScopeKind,
+ PRState,
+ PRTimeline,
+ PullRequestTimelines,
+ RepoRef,
+)
+from products.engineering_analytics.backend.logic.delivery_scope import DeliveryScope
+from products.engineering_analytics.backend.logic.merge_queue import gate_attempt_expr
+from products.engineering_analytics.backend.logic.pr_timeline import (
+ GateAttempt,
+ MasterFailureIndex,
+ PRTimelineBuilder,
+ PRTimelineInput,
+ ReviewVerdict,
+ RunAttempt,
+)
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._workflow_filters import (
+ DECISIVE_FAILURE_CONCLUSIONS,
+ DECISIVE_FAILURE_CONCLUSIONS_SQL,
+ run_started_floor_constant,
+ run_windowed_job_created_floor_constant,
+)
+from products.engineering_analytics.backend.logic.queries.delivery_summary import CI_LOOKBACK
+from products.engineering_analytics.backend.logic.queries.pr_cost import query_pr_costs_since
+from products.engineering_analytics.backend.logic.views import issue_events
+
+_LIMIT = 200
+
+# Trunk states that mean the entry left the queue without landing.
+_OUT_OF_QUEUE_STATES = frozenset({"failed", "cancelled"})
+
+# A list scope shows what is still open plus what merged in the window; closed-unmerged work is not
+# listed. A single pull request is shown whatever its state.
+_LIST_WINDOW = "(pr.state = 'open' OR (pr.merged_at >= {date_from} __DATE_TO__))"
+
+_PRS_SELECT = f"""
+ SELECT
+ pr.number, pr.title, pr.repo_owner, pr.repo_name, pr.state, pr.is_draft,
+ pr.created_at, pr.merged_at, pr.closed_at, pr.default_branch,
+ pr.author_handle, pr.author_avatar_url, pr.is_bot
+ FROM __PR_SOURCE__ AS pr
+ WHERE (__SCOPE__) AND __WINDOW__
+ ORDER BY pr.created_at DESC
+ LIMIT {_LIMIT + 1}
+"""
+
+_TRANSITIONS_SELECT = """
+ SELECT pr_number, event, created_at
+ FROM __EVENTS_SOURCE__ AS se
+ WHERE pr_number IN {pr_numbers}
+ ORDER BY created_at ASC, id ASC
+ LIMIT 100000
+"""
+
+_REVIEWS_SELECT = """
+ SELECT pr_number, reviewer_login, state, submitted_at
+ FROM __REVIEWS_SOURCE__ AS rv
+ WHERE pr_number IN {pr_numbers}
+ LIMIT 100000
+"""
+
+# A skipped run never executes, so it adds no red or running time. HogQL caps a result at 50k rows,
+# and skipped and merge-queue runs are a third of a busy team's runs, so both stay out of this list.
+_RUNS_SELECT = """
+ SELECT
+ id, pr_number, workflow_name, head_sha, status, conclusion, run_started_at, updated_at, run_attempt, created_at
+ FROM __RUNS_SOURCE__ AS r
+ WHERE pr_number IN {pr_numbers} AND run_started_at >= {run_from}
+ AND NOT is_merge_queue AND ifNull(conclusion, '') != 'skipped'
+ LIMIT 1000000
+"""
+
+# One row per merge-queue attempt: the queue runs several workflows for each attempt.
+_GATE_ATTEMPTS_SELECT = """
+ SELECT
+ pr_number,
+ min(run_started_at) AS started_at,
+ max(updated_at) AS completed_at,
+ countIf(status != 'completed' OR updated_at IS NULL) AS unfinished
+ FROM __RUNS_SOURCE__ AS r
+ WHERE pr_number IN {pr_numbers} AND run_started_at >= {run_from} AND is_merge_queue
+ GROUP BY pr_number, __GATE_ATTEMPT__
+ LIMIT 1000000
+"""
+
+# One row per run attempt. Re-run copies are GitHub's re-listing of jobs that never ran again, so
+# they would stretch an attempt back to the previous attempt's start.
+_JOB_ATTEMPTS_SELECT = f"""
+ SELECT
+ run_id,
+ run_attempt,
+ min(started_at) AS started_at,
+ max(completed_at) AS completed_at,
+ countIf(status != 'completed') AS unfinished,
+ groupArrayIf(name, conclusion IN ({DECISIVE_FAILURE_CONCLUSIONS_SQL})) AS failed_jobs,
+ countIf(conclusion NOT IN ('success', 'skipped')) AS unsuccessful
+ FROM __JOBS_SOURCE__ AS j
+ WHERE run_id IN {{run_ids}} AND NOT is_rerun_copy
+ GROUP BY run_id, run_attempt
+ LIMIT 1000000
+"""
+
+_MASTER_FAILURES_SELECT = f"""
+ SELECT j.workflow_name, j.name, j.completed_at
+ FROM __JOBS_SOURCE__ AS j
+ INNER JOIN __RUNS_SOURCE__ AS r ON r.id = j.run_id
+ WHERE r.head_branch = {{default_branch}}
+ AND NOT r.is_merge_queue
+ AND r.run_started_at >= {{run_from}}
+ AND j.conclusion IN ({DECISIVE_FAILURE_CONCLUSIONS_SQL})
+ AND j.completed_at IS NOT NULL
+ AND j.workflow_name IN {{workflow_names}}
+ LIMIT 200000
+"""
+
+_TRUNK_STATE_SELECT = """
+ SELECT pr_number, argMax(state, state_changed_at) AS state
+ FROM __TRUNK_SOURCE__ AS tq
+ WHERE pr_number IN {pr_numbers}
+ GROUP BY pr_number
+"""
+
+
+@frozen
+class _JobAttempt:
+ """One attempt of a run, rolled up from its jobs."""
+
+ attempt: int
+ started_at: datetime
+ # None while any job of the attempt is still running.
+ completed_at: datetime | None
+ failed_jobs: tuple[str, ...]
+ # Every job finished with success or skipped.
+ succeeded: bool
+
+
+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:
+ self._curated = curated
+ self._scope = scope
+ self._date_from = date_from
+ self._date_to = date_to
+ self._now = datetime.now(tz=UTC)
+
+ def _result(self, items: list[PRTimeline], *, truncated: bool) -> PullRequestTimelines:
+ return PullRequestTimelines(
+ scope_kind=self._scope.kind,
+ scope=self._scope.label,
+ has_membership_data=self._curated.members_source() is not None,
+ review_data_available=self._curated.reviews_source() is not None,
+ jobs_available=self._curated.jobs_source() is not None,
+ merge_queue_state_available=self._curated.trunk_merge_queue_source() is not None,
+ generated_at=self._now,
+ items=items,
+ truncated=truncated,
+ limit=_LIMIT,
+ )
+
+ def run(self) -> PullRequestTimelines:
+ prs = self._query_prs()
+ truncated = len(prs) > _LIMIT
+ prs = prs[:_LIMIT]
+ if not prs:
+ return self._result([], truncated=False)
+
+ pr_numbers = sorted({int(row[0]) for row in prs})
+ # A day of slack below the oldest listed PR keeps its first CI run inside the scan.
+ run_from = min(row[6] for row in prs) - timedelta(days=1)
+ if self._scope.kind != DeliveryScopeKind.PULL_REQUEST:
+ # An open PR is listed whatever its age, and one old PR would stretch every scan back months.
+ # A listed PR's CI is read from the same lookback the summary uses, and its timeline starts there.
+ run_from = max(run_from, self._date_from - CI_LOOKBACK)
+ ready_at = self._query_ready_at(pr_numbers)
+ reviews = self._query_reviews(pr_numbers)
+ attempts, gates = self._query_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)
+
+ items = []
+ for row in prs:
+ (
+ number,
+ title,
+ repo_owner,
+ repo_name,
+ state,
+ is_draft,
+ created_at,
+ merged_at,
+ closed_at,
+ _branch,
+ author_handle,
+ author_avatar_url,
+ is_bot,
+ ) = row
+ 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,
+ )
+ pr_attempts = [attempt for attempt in attempts.get(number, []) if attempt.started_at <= ended_at]
+ builder = PRTimelineBuilder(
+ PRTimelineInput(
+ started_at=started_at,
+ ended_at=ended_at,
+ is_open=is_open,
+ is_merged=merged_at is not None,
+ is_draft=bool(is_draft) and is_open,
+ attempts=pr_attempts,
+ gate_attempts=[gate for gate in gates.get(number, []) if gate.started_at <= ended_at],
+ reviews=reviews.get(number, []) if reviews is not None else None,
+ trunk_out_of_queue=number in out_of_queue,
+ ),
+ master_failures,
+ )
+ cost = costs.get(number)
+ items.append(
+ PRTimeline(
+ number=number,
+ title=title or "",
+ author=Author(
+ handle=author_handle or "",
+ display_name=author_handle or "",
+ avatar_url=author_avatar_url or "",
+ is_bot=bool(is_bot),
+ ),
+ repo=RepoRef(provider="github", owner=repo_owner, name=repo_name),
+ state=PRState(state),
+ is_draft=bool(is_draft),
+ created_at=created_at,
+ started_at=started_at,
+ merged_at=merged_at,
+ pushes=len({attempt.head_sha for attempt in pr_attempts}),
+ estimated_cost_usd=cost.estimated_cost_usd if cost else None,
+ billable_minutes=cost.billable_seconds / 60 if cost else None,
+ segments=builder.build(),
+ )
+ )
+ 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(members_source=self._curated.members_source()))
+ .replace("__WINDOW__", window)
+ .replace("__PR_SOURCE__", self._curated.pr_source())
+ .replace("__DATE_TO__", date_to_clause)
+ )
+ 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]) -> dict[int, list[datetime]]:
+ source = self._curated.issue_events_source()
+ if source is None:
+ return {}
+ response = self._curated.run(
+ _TRANSITIONS_SELECT.replace("__EVENTS_SOURCE__", source),
+ query_type="engineering_analytics.pull_request_timelines_transitions",
+ placeholders={"pr_numbers": ast.Constant(value=pr_numbers)},
+ )
+ 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
+
+ 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."""
+ source = self._curated.reviews_source()
+ if source is None:
+ return None
+ response = self._curated.run(
+ _REVIEWS_SELECT.replace("__REVIEWS_SOURCE__", source),
+ query_type="engineering_analytics.pull_request_timelines_reviews",
+ placeholders={"pr_numbers": ast.Constant(value=pr_numbers)},
+ )
+ reviews: dict[int, list[ReviewVerdict]] = defaultdict(list)
+ for number, reviewer, state, submitted_at in response.results or []:
+ 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] = {
+ "pr_numbers": ast.Constant(value=pr_numbers),
+ "run_from": ast.Constant(value=run_from),
+ "run_started_floor": run_started_floor_constant(run_from),
+ }
+ response = self._curated.run(
+ _RUNS_SELECT.replace("__RUNS_SOURCE__", runs_source),
+ query_type="engineering_analytics.pull_request_timelines_runs",
+ placeholders=placeholders,
+ )
+ 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
+ # describes it. Only re-runs (earlier attempts) and failures (failed job names) need the jobs.
+ job_attempts = self._query_job_attempts(
+ [int(row[0]) for row in runs if int(row[8] or 1) > 1 or row[5] in DECISIVE_FAILURE_CONCLUSIONS],
+ run_from,
+ )
+
+ attempts: dict[int, list[RunAttempt]] = defaultdict(list)
+ for (
+ run_id,
+ number,
+ workflow_name,
+ head_sha,
+ status,
+ conclusion,
+ started_at,
+ updated_at,
+ attempt,
+ created,
+ ) in runs:
+ run_attempts = job_attempts.get(int(run_id), [])
+ pushed_at = created or started_at
+ completed = status == "completed"
+ run_failed = completed and conclusion in DECISIVE_FAILURE_CONCLUSIONS
+ newest_attempt = int(attempt or 1)
+ for job_attempt in run_attempts:
+ # The run row decides its newest attempt's outcome: the jobs sync can still hold a queued
+ # job row, or miss the failing job's row, after the run itself completed.
+ is_newest = job_attempt.attempt == newest_attempt
+ failed = bool(job_attempt.failed_jobs) or (is_newest and run_failed)
+ completed_at = job_attempt.completed_at
+ succeeded = job_attempt.succeeded and not failed
+ if is_newest and completed:
+ completed_at = completed_at or updated_at
+ succeeded = conclusion == "success" and not failed
+ attempts[int(number)].append(
+ RunAttempt(
+ run_id=int(run_id),
+ workflow_name=workflow_name or "",
+ head_sha=head_sha or "",
+ attempt=job_attempt.attempt,
+ pushed_at=pushed_at,
+ started_at=job_attempt.started_at,
+ completed_at=completed_at,
+ failed=failed,
+ succeeded=succeeded,
+ failed_jobs=job_attempt.failed_jobs,
+ )
+ )
+ # The jobs sync can lag behind the run row, so the run's newest attempt comes from the run
+ # row whenever the jobs have not reported it yet.
+ if run_attempts and newest_attempt <= max(job_attempt.attempt for job_attempt in run_attempts):
+ continue
+ attempts[int(number)].append(
+ RunAttempt(
+ run_id=int(run_id),
+ workflow_name=workflow_name or "",
+ head_sha=head_sha or "",
+ attempt=newest_attempt,
+ pushed_at=pushed_at,
+ started_at=started_at,
+ completed_at=updated_at if completed else None,
+ failed=run_failed,
+ succeeded=completed and conclusion == "success",
+ failed_jobs=(),
+ )
+ )
+
+ gates_response = self._curated.run(
+ _GATE_ATTEMPTS_SELECT.replace("__RUNS_SOURCE__", runs_source).replace(
+ "__GATE_ATTEMPT__", gate_attempt_expr("r.head_branch")
+ ),
+ query_type="engineering_analytics.pull_request_timelines_gate_attempts",
+ placeholders=placeholders,
+ )
+ gates: dict[int, list[GateAttempt]] = defaultdict(list)
+ for number, started_at, completed_at, unfinished in gates_response.results or []:
+ if started_at is not None:
+ gates[int(number)].append(
+ GateAttempt(started_at=started_at, completed_at=None if unfinished else completed_at)
+ )
+ return attempts, 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)
+ if source is None or not run_ids:
+ return {}
+ response = self._curated.run(
+ _JOB_ATTEMPTS_SELECT.replace("__JOBS_SOURCE__", source),
+ query_type="engineering_analytics.pull_request_timelines_job_attempts",
+ placeholders={
+ "run_ids": ast.Constant(value=run_ids),
+ "job_created_floor": run_windowed_job_created_floor_constant(run_from),
+ },
+ )
+ by_run: dict[int, list[_JobAttempt]] = defaultdict(list)
+ for run_id, run_attempt, started_at, completed_at, unfinished, failed_jobs, unsuccessful in (
+ response.results or []
+ ):
+ if started_at is None:
+ continue
+ by_run[int(run_id)].append(
+ _JobAttempt(
+ attempt=int(run_attempt or 1),
+ started_at=started_at,
+ completed_at=None if unfinished else completed_at,
+ failed_jobs=tuple(failed_jobs or ()),
+ succeeded=not unfinished and not unsuccessful,
+ )
+ )
+ return by_run
+
+ def _query_master_failures(
+ self, attempts: dict[int, list[RunAttempt]], default_branch: str, run_from: datetime
+ ) -> MasterFailureIndex:
+ # Filtered by workflow, not by job name: the index compares job names without their shard
+ # suffix, and an exact-name filter would drop the other shards of the same job.
+ workflow_names = sorted(
+ {
+ attempt.workflow_name
+ for pr_attempts in attempts.values()
+ for attempt in pr_attempts
+ if attempt.failed_jobs
+ }
+ )
+ jobs_source = self._curated.jobs_source(created_floor=True)
+ if not workflow_names or not default_branch or jobs_source is None:
+ return MasterFailureIndex([])
+ response = self._curated.run(
+ _MASTER_FAILURES_SELECT.replace("__JOBS_SOURCE__", jobs_source).replace(
+ "__RUNS_SOURCE__", self._curated.run_source(started_floor=True)
+ ),
+ query_type="engineering_analytics.pull_request_timelines_master_failures",
+ placeholders={
+ "default_branch": ast.Constant(value=default_branch),
+ "workflow_names": ast.Constant(value=workflow_names),
+ "run_from": ast.Constant(value=run_from),
+ "run_started_floor": run_started_floor_constant(run_from),
+ "job_created_floor": run_windowed_job_created_floor_constant(run_from),
+ },
+ )
+ return MasterFailureIndex(
+ [(workflow or "", name or "", completed_at) for workflow, name, completed_at in response.results or []]
+ )
+
+ def _query_out_of_queue(self, pr_numbers: list[int]) -> set[int]:
+ source = self._curated.trunk_merge_queue_source()
+ if source is None:
+ return set()
+ response = self._curated.run(
+ _TRUNK_STATE_SELECT.replace("__TRUNK_SOURCE__", source),
+ query_type="engineering_analytics.pull_request_timelines_trunk_state",
+ placeholders={"pr_numbers": ast.Constant(value=pr_numbers)},
+ )
+ return {int(number) for number, state in response.results or [] if state in _OUT_OF_QUEUE_STATES}
+
+
+def query_pull_request_timelines(
+ *, curated: CuratedGitHubSource, scope: DeliveryScope, date_from: datetime, date_to: datetime | None
+) -> PullRequestTimelines:
+ return PullRequestTimelinesQuery(curated, scope=scope, date_from=date_from, date_to=date_to).run()
diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.py
index e788a81a9143..098fdc77261a 100644
--- a/products/engineering_analytics/backend/logic/sources.py
+++ b/products/engineering_analytics/backend/logic/sources.py
@@ -58,6 +58,9 @@ 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
+# at the source, so reads must degrade gracefully (no review data) exactly like issue_events.
+REVIEWS_SCHEMA = "reviews"
# 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.
@@ -70,6 +73,7 @@ _CURATED_ENDPOINTS = frozenset(
ISSUE_EVENTS_SCHEMA,
DEPLOYMENTS_SCHEMA,
DEPLOYMENT_STATUSES_SCHEMA,
+ REVIEWS_SCHEMA,
}
)
@@ -96,6 +100,8 @@ class GitHubTables:
# useful together, so consumers gate on both.
deployments: str | None = None
deployment_statuses: str | None = None
+ # Optional: present only once reviews are synced; None means "no review data".
+ reviews: str | None = None
# Used to scope cross-store reads such as CI traces to the selected source's repository.
repository: str = ""
@@ -167,6 +173,7 @@ def resolve_github_tables(
issue_events=tables.get(ISSUE_EVENTS_SCHEMA),
deployments=tables.get(DEPLOYMENTS_SCHEMA),
deployment_statuses=tables.get(DEPLOYMENT_STATUSES_SCHEMA),
+ reviews=tables.get(REVIEWS_SCHEMA),
repository=candidate.repository,
)
if source_id is not None:
diff --git a/products/engineering_analytics/backend/logic/views/reviews.py b/products/engineering_analytics/backend/logic/views/reviews.py
new file mode 100644
index 000000000000..251318742cb0
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/views/reviews.py
@@ -0,0 +1,30 @@
+"""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 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.
+"""
+
+APPROVED_STATE = "APPROVED"
+CHANGES_REQUESTED_STATE = "CHANGES_REQUESTED"
+
+
+def build_query(table_name: str) -> str:
+ # A row with no parsable submitted_at cannot be ordered against the PR's other events.
+ return f"""
+ SELECT id, pr_number, reviewer_login, state, submitted_at
+ FROM (
+ SELECT
+ id,
+ ifNull(pr_number, 0) AS pr_number,
+ ifNull(JSONExtractString(user, 'login'), '') AS reviewer_login,
+ upper(ifNull(state, '')) AS state,
+ parseDateTimeBestEffort(submitted_at) AS submitted_at
+ FROM {table_name}
+ )
+ WHERE submitted_at IS NOT NULL AND pr_number > 0
+ """
diff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.py
index 0e13f52fa293..97fe3e3fc145 100644
--- a/products/engineering_analytics/backend/logic/views/source_schema.py
+++ b/products/engineering_analytics/backend/logic/views/source_schema.py
@@ -98,6 +98,18 @@ ISSUE_EVENTS_COLUMNS: dict[str, dict[str, str]] = {
"created_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
}
+# Contract for the ``github_reviews`` warehouse source: one row per submitted review, fanned out
+# over pull requests with the parent's number injected as ``pr_number``. ``user`` is the reviewer
+# object verbatim as JSON. Same Nullable/string discipline as above.
+REVIEWS_COLUMNS: dict[str, dict[str, str]] = {
+ "id": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},
+ "pr_number": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},
+ "user": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
+ "state": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
+ "commit_id": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
+ "submitted_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
+}
+
# Contract for the ``github_team_members`` warehouse source (org team membership). Member rows
# are GitHub user objects with the parent team's identity injected by the source fan-out
# (``team_id`` / ``team_slug`` / ``team_name``); ``login`` + ``team_slug`` are the join keys the
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 078f7e8c4db5..f43fb7cf57fb 100644
--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
@@ -54,6 +54,7 @@ from products.engineering_analytics.backend.logic.sources import (
DEPLOYMENTS_SCHEMA,
ISSUE_EVENTS_SCHEMA,
PULL_REQUESTS_SCHEMA,
+ REVIEWS_SCHEMA,
TEAM_MEMBERS_SCHEMA,
TRUNK_QUARANTINED_TESTS_SCHEMA,
WORKFLOW_JOBS_SCHEMA,
@@ -65,6 +66,7 @@ from products.engineering_analytics.backend.logic.views.source_schema import (
DEPLOYMENTS_COLUMNS,
ISSUE_EVENTS_COLUMNS,
PULL_REQUESTS_COLUMNS,
+ REVIEWS_COLUMNS,
TEAM_MEMBERS_COLUMNS,
TRUNK_QUARANTINED_TESTS_COLUMNS,
WORKFLOW_JOBS_COLUMNS,
@@ -505,6 +507,54 @@ 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),),
+)
+_OPEN_REVIEW_PLANS: tuple[tuple[tuple[str, float], ...], ...] = (
+ (("CHANGES_REQUESTED", 0.6),),
+ (("COMMENTED", 0.5),),
+ (),
+)
+
+
+def _review_rows(prs: list[dict[str, Any]], anchor: datetime) -> list[dict[str, Any]]:
+ logins = sorted({(pr.get("user") or {}).get("login") or "" for pr in prs} - {""})
+ reviewers = [login for login in logins if not login.endswith("[bot]") and login not in KNOWN_BOT_HANDLES]
+ rows: list[dict[str, Any]] = []
+ for index, pr in enumerate(prs):
+ if not pr.get("created_at") or not reviewers:
+ continue
+ created = datetime.fromisoformat(pr["created_at"])
+ if pr.get("merged_at"):
+ end = datetime.fromisoformat(pr["merged_at"])
+ plan = _MERGED_REVIEW_PLANS[index % len(_MERGED_REVIEW_PLANS)]
+ elif pr.get("state") == "open" and not pr.get("draft"):
+ end = anchor
+ plan = _OPEN_REVIEW_PLANS[index % len(_OPEN_REVIEW_PLANS)]
+ else:
+ continue
+ author = (pr.get("user") or {}).get("login") or ""
+ reviewer = reviewers[index % len(reviewers)]
+ if reviewer == author:
+ reviewer = reviewers[(index + 1) % len(reviewers)]
+ for step, (state, fraction) in enumerate(plan):
+ rows.append(
+ {
+ "id": 6_000_000_000 + index * 10 + step,
+ "pr_number": pr["number"],
+ "user": json.dumps({"login": reviewer, "avatar_url": ""}),
+ "state": state,
+ "commit_id": "",
+ "submitted_at": (created + (end - created) * fraction).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ }
+ )
+ return rows
+
+
def _demo_multi_push(
prs: list[dict[str, Any]], runs: list[dict[str, Any]]
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
@@ -1178,6 +1228,7 @@ class Command(BaseCommand):
# Synthetic draft/ready transitions + merged events for ready_to_merge_seconds, windowed
# like a real capped issue-events sync (see _issue_event_rows).
issue_events = _issue_event_rows(prs, _fixture_anchor(prs, runs))
+ reviews = _review_rows(prs, _fixture_anchor(prs, runs))
deploy_rows = _deployment_rows(prs)
# Always normalize timestamps to a ClickHouse-friendly format; rebasing is optional.
@@ -1185,6 +1236,7 @@ class Command(BaseCommand):
prs = [self._shift_dates(pr, PR_DATE_FIELDS, shift) for pr in prs]
runs = [self._shift_dates(run, RUN_DATE_FIELDS, shift) for run in runs]
issue_events = [self._shift_dates(event, ("created_at",), shift) for event in issue_events]
+ reviews = [self._shift_dates(review, ("submitted_at",), shift) for review in reviews]
deployments = [self._shift_dates(row, ("created_at",), shift) for row in deploy_rows.deployments]
deployment_statuses = [self._shift_dates(row, ("created_at",), shift) for row in deploy_rows.statuses]
if shift:
@@ -1221,6 +1273,7 @@ class Command(BaseCommand):
self._upsert_schema_table(
team, source, credential, prefix, ISSUE_EVENTS_SCHEMA, ISSUE_EVENTS_COLUMNS, issue_events
)
+ self._upsert_schema_table(team, source, credential, prefix, REVIEWS_SCHEMA, REVIEWS_COLUMNS, reviews)
# A TrunkIo sibling source backs the Trunk quarantine debt scoreboard.
trunk_source = self._get_or_create_seed_source(
team,
diff --git a/products/engineering_analytics/backend/presentation/serializers/delivery.py b/products/engineering_analytics/backend/presentation/serializers/delivery.py
new file mode 100644
index 000000000000..6aab032e6249
--- /dev/null
+++ b/products/engineering_analytics/backend/presentation/serializers/delivery.py
@@ -0,0 +1,253 @@
+"""Payloads for the delivery reads: a scope's delivery summary and its pull request timelines."""
+
+from rest_framework_dataclasses.serializers import DataclassSerializer
+
+from products.engineering_analytics.backend.facade.contracts import (
+ DeliveryLeadTime,
+ DeliverySummary,
+ DurationDistribution,
+ PRTimeline,
+ PRTimelineSegment,
+ PullRequestTimelines,
+ ScopeRepoDistribution,
+ ScopeRepoFigure,
+)
+from products.engineering_analytics.backend.presentation.serializers._shared import RepoRefSerializer
+
+_SCOPE_KIND_HELP = (
+ "What the read covers: 'author' (one GitHub login), 'github_team' (the members of one GitHub team, "
+ "through the team membership table), or 'pull_request' (one pull request)."
+)
+
+
+class ScopeRepoFigureSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = ScopeRepoFigure
+ extra_kwargs = {
+ "scope": {
+ "help_text": "The figure over the pull requests in scope. Null when the scope has nothing to measure.",
+ "allow_null": True,
+ },
+ "repo": {
+ "help_text": "The same figure over every non-bot pull request in the repository, the scope "
+ "included. Null when the repository has nothing to measure.",
+ "allow_null": True,
+ },
+ }
+
+
+def _figure(help_text: str) -> ScopeRepoFigureSerializer:
+ return ScopeRepoFigureSerializer(help_text=help_text)
+
+
+class DurationDistributionSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = DurationDistribution
+ extra_kwargs = {
+ "pr_count": {"help_text": "Pull requests in the distribution. Every statistic is null when this is 0."},
+ "min_seconds": {"help_text": "Fastest duration, in seconds.", "allow_null": True},
+ "p05_seconds": {"help_text": "5th percentile, in seconds: the lower whisker.", "allow_null": True},
+ "p25_seconds": {"help_text": "25th percentile, in seconds: the box's lower edge.", "allow_null": True},
+ "p50_seconds": {"help_text": "Median, in seconds.", "allow_null": True},
+ "mean_seconds": {"help_text": "Mean, in seconds.", "allow_null": True},
+ "p75_seconds": {"help_text": "75th percentile, in seconds: the box's upper edge.", "allow_null": True},
+ "p95_seconds": {"help_text": "95th percentile, in seconds: the upper whisker.", "allow_null": True},
+ "max_seconds": {"help_text": "Slowest duration, in seconds.", "allow_null": True},
+ }
+
+
+class ScopeRepoDistributionSerializer(DataclassSerializer):
+ scope = DurationDistributionSerializer(help_text="The deployed pull requests in scope.")
+ repo = DurationDistributionSerializer(help_text="Every deployed pull request in the repository.")
+
+ class Meta:
+ dataclass = ScopeRepoDistribution
+
+
+class DeliveryLeadTimeSerializer(DataclassSerializer):
+ open_to_deploy = ScopeRepoDistributionSerializer(
+ help_text="Open to the first successful deploy containing the merge, over PRs deployed in the window."
+ )
+ open_to_merge = ScopeRepoDistributionSerializer(
+ help_text="Open to merge over the same deployed PRs, so it composes with merge_to_deploy. Includes draft time."
+ )
+ merge_to_deploy = ScopeRepoDistributionSerializer(help_text="Merge to deploy over the same deployed PRs.")
+
+ class Meta:
+ dataclass = DeliveryLeadTime
+ extra_kwargs = {
+ "deploy_data_available": {
+ "help_text": "False when the deployments and deployment statuses tables aren't synced. The "
+ "distributions are then empty."
+ },
+ "environment_scope": {
+ "help_text": "The deploy environments lead time was scoped to: production by default. Empty "
+ "when deploy data is not available."
+ },
+ "merged_pr_count": {"help_text": "PRs in scope merged in the window (bots and drafts excluded)."},
+ "deployed_merged_pr_count": {
+ "help_text": "Of merged_pr_count, the PRs a successful in-scope deploy contains. The rest are "
+ "still waiting for a deploy or fall outside the scan."
+ },
+ }
+
+
+class DeliverySummarySerializer(DataclassSerializer):
+ cost_per_merged_pr_usd = _figure(
+ "Median estimated CI cost per merged PR, in USD, over every run linked to the PR (merge-queue gate runs "
+ "included) that started up to 30 days before the window. Null when the jobs table isn't synced."
+ )
+ billable_minutes_per_merged_pr = _figure(
+ "Median billable runner minutes per merged PR, on the billed clock. Null when the jobs table isn't synced."
+ )
+ cost_per_push_usd = _figure(
+ "Total CI cost divided by total pushes over the merged PRs: the price of one iteration. A push is a "
+ "distinct head commit that triggered CI."
+ )
+ median_ready_to_merge_seconds = _figure(
+ "Median seconds from the last ready_for_review to merge. Null when issue events aren't synced."
+ )
+ p90_ready_to_merge_seconds = _figure("90th percentile of the ready-to-merge seconds.")
+ median_ready_to_first_approval_seconds = _figure(
+ "Median seconds from ready to the first approval. An approval given while the PR was a draft counts "
+ "as 0. PRs merged without an approval are left out. Null when reviews aren't synced."
+ )
+ median_first_approval_to_merge_seconds = _figure(
+ "Median seconds from the first approval to merge. This median and the one before it do not add up to "
+ "the ready-to-merge median."
+ )
+ before_first_approval_share = _figure(
+ "Share (0 to 1) of all ready-to-merge hours spent before the first approval, summed over the PRs, so "
+ "long PRs weigh more. The rest came after the approval."
+ )
+ pushes_after_approval_per_merged_pr = _figure(
+ "Mean pushes after the first approval per merged PR, over PRs with an approval."
+ )
+ merge_queue_attempts_per_merged_pr = _figure(
+ "Mean merge-queue gate attempts per merged PR that went through the queue. A bisection probe folds "
+ "into its attempt."
+ )
+ failed_merge_queue_share = _figure(
+ "Share (0 to 1) of queue-landed merged PRs with at least one failed gate attempt. A failure caused by "
+ "another PR ahead in the queue also counts, because the queue history is not in the warehouse."
+ )
+ lead_time = DeliveryLeadTimeSerializer(help_text="Lead time to deploy for the scope against the repository.")
+
+ class Meta:
+ dataclass = DeliverySummary
+ extra_kwargs = {
+ "scope_kind": {"help_text": _SCOPE_KIND_HELP},
+ "scope": {"help_text": "The GitHub login or GitHub team slug the summary is for."},
+ "has_membership_data": {
+ "help_text": "True when the team membership table is synced. A github_team scope without it "
+ "matches no pull requests, so every scope figure is empty rather than the whole repository."
+ },
+ "jobs_available": {"help_text": "True when the workflow jobs table is synced, which cost needs."},
+ "review_data_available": {
+ "help_text": "True when the reviews table is synced, which the approval split needs."
+ },
+ "ready_data_available": {
+ "help_text": "True when issue events are synced, which ready-to-merge time needs."
+ },
+ "opened_pr_count": {"help_text": "PRs in scope opened in the window, drafts included, bots excluded."},
+ "merged_pr_count": {
+ "help_text": "PRs in scope merged in the window (bots and drafts excluded): the population of every "
+ "per-merged-PR figure."
+ },
+ "open_pr_count": {"help_text": "PRs in scope that are open and not drafts right now. Ignores the window."},
+ "draft_pr_count": {"help_text": "PRs in scope that are open drafts right now. Ignores the window."},
+ "total_cost_usd": {
+ "help_text": "Estimated CI cost summed over the merged PRs in scope. Null when nothing was costable.",
+ "allow_null": True,
+ },
+ "total_billable_minutes": {
+ "help_text": "Billable minutes summed over the merged PRs in scope. Null when the jobs table isn't "
+ "synced.",
+ "allow_null": True,
+ },
+ "push_count": {"help_text": "Pushes summed over the merged PRs in scope."},
+ }
+
+
+class PRTimelineSegmentSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = PRTimelineSegment
+ extra_kwargs = {
+ "kind": {
+ "help_text": "What the PR waited on: draft; waiting_for_review (no approval yet, or re-review "
+ "after a push); changes_requested (no push since); approved_not_enqueued (approved, with no failing or running check); "
+ "review_state_unknown (reviews not synced); ci_running; red_passed_on_rerun (the failed "
+ "workflows passed a re-run of the same commit); red_master_broken (the failed jobs also failed "
+ "on the default branch within 12 hours); red_fixed_by_push (a later commit arrived); "
+ "red_not_provable; merge_queue (every queue state collapsed); out_of_merge_queue (open PR, "
+ "Trunk says failed or cancelled)."
+ },
+ "started_at": {"help_text": "Segment start."},
+ "ended_at": {"help_text": "Segment end: the next segment's start, the merge or close, or now."},
+ }
+
+
+class PRTimelineSerializer(DataclassSerializer):
+ repo = RepoRefSerializer(help_text="The repository the pull request belongs to.")
+ segments = PRTimelineSegmentSerializer(
+ many=True, help_text="Consecutive segments from started_at to the merge, the close, or now, with no gaps."
+ )
+
+ class Meta:
+ dataclass = PRTimeline
+ extra_kwargs = {
+ "number": {"help_text": "Pull request number."},
+ "title": {"help_text": "Pull request title."},
+ "author": {"help_text": "The pull request's author."},
+ "state": {
+ "help_text": "open, merged, or closed. Author and team scopes list open and merged PRs only; a "
+ "pull_request scope returns the PR whatever its state."
+ },
+ "is_draft": {"help_text": "True when the PR is a draft right now."},
+ "created_at": {"help_text": "When the PR was opened."},
+ "started_at": {
+ "help_text": "Where the timeline starts: the last ready_for_review before the end, else created_at. A PR listed for an author or a team starts no earlier than 30 days before the window, because older CI is not read."
+ },
+ "merged_at": {"help_text": "Merge time; null when not merged.", "allow_null": True},
+ "pushes": {"help_text": "Distinct head commits that triggered CI, merge-queue gate runs excluded."},
+ "estimated_cost_usd": {
+ "help_text": "Estimated CI cost over the PR's runs, in USD. Null when nothing was costable.",
+ "allow_null": True,
+ },
+ "billable_minutes": {
+ "help_text": "Billable minutes over the PR's runs. Null when the jobs table isn't synced.",
+ "allow_null": True,
+ },
+ }
+
+
+class PullRequestTimelinesSerializer(DataclassSerializer):
+ items = PRTimelineSerializer(
+ many=True,
+ help_text="The pull requests in scope, newest first: open PRs plus PRs merged in the window, or the one "
+ "pull request of a pull_request scope.",
+ )
+
+ class Meta:
+ dataclass = PullRequestTimelines
+ extra_kwargs = {
+ "scope_kind": {"help_text": _SCOPE_KIND_HELP},
+ "scope": {"help_text": "The GitHub login, GitHub team slug, or 'owner/name#number' the timelines are for."},
+ "has_membership_data": {
+ "help_text": "True when the team membership table is synced. A github_team scope without it lists "
+ "no pull requests."
+ },
+ "review_data_available": {
+ "help_text": "False when reviews aren't synced: review stretches read review_state_unknown."
+ },
+ "jobs_available": {
+ "help_text": "False when workflow jobs aren't synced: a check a re-run turned green is not "
+ "visible, and no red stretch reads red_master_broken."
+ },
+ "merge_queue_state_available": {
+ "help_text": "True when the Trunk merge-queue table is synced, so out_of_merge_queue can appear."
+ },
+ "generated_at": {"help_text": "The now every open PR's timeline ends at."},
+ "truncated": {"help_text": "True when more PRs matched than the limit."},
+ "limit": {"help_text": "The maximum number of PRs returned."},
+ }
diff --git a/products/engineering_analytics/backend/presentation/views/__init__.py b/products/engineering_analytics/backend/presentation/views/__init__.py
index 925e2c6e7b7c..87aa4cefb276 100644
--- a/products/engineering_analytics/backend/presentation/views/__init__.py
+++ b/products/engineering_analytics/backend/presentation/views/__init__.py
@@ -12,6 +12,7 @@ from products.engineering_analytics.backend.presentation.views._base import (
EngineeringAnalyticsViewSetBase,
)
from products.engineering_analytics.backend.presentation.views.ci_signals import CISignalsConfigMixin
+from products.engineering_analytics.backend.presentation.views.delivery import DeliveryActionsMixin
from products.engineering_analytics.backend.presentation.views.dora import DoraActionsMixin
from products.engineering_analytics.backend.presentation.views.pull_requests import PullRequestActionsMixin
from products.engineering_analytics.backend.presentation.views.sources import SourcesMixin
@@ -25,6 +26,7 @@ class EngineeringAnalyticsViewSet(
SourcesMixin,
CISignalsConfigMixin,
PullRequestActionsMixin,
+ DeliveryActionsMixin,
WorkflowActionsMixin,
SuiteHealthActionsMixin,
TeamActionsMixin,
@@ -39,6 +41,7 @@ class EngineeringAnalyticsViewSet(
*SourcesMixin.READ_ACTIONS,
*CISignalsConfigMixin.READ_ACTIONS,
*PullRequestActionsMixin.READ_ACTIONS,
+ *DeliveryActionsMixin.READ_ACTIONS,
*WorkflowActionsMixin.READ_ACTIONS,
*SuiteHealthActionsMixin.READ_ACTIONS,
*TeamActionsMixin.READ_ACTIONS,
diff --git a/products/engineering_analytics/backend/presentation/views/delivery.py b/products/engineering_analytics/backend/presentation/views/delivery.py
new file mode 100644
index 000000000000..02d187263fc3
--- /dev/null
+++ b/products/engineering_analytics/backend/presentation/views/delivery.py
@@ -0,0 +1,125 @@
+"""Delivery reads: a scope's delivery summary and its pull request timelines."""
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
+from rest_framework.decorators import action
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from products.engineering_analytics.backend.facade import api
+from products.engineering_analytics.backend.presentation.serializers.delivery import (
+ DeliverySummarySerializer,
+ PullRequestTimelinesSerializer,
+)
+from products.engineering_analytics.backend.presentation.views._base import (
+ _DATE_FROM,
+ _DATE_TO,
+ _SOURCE_ID,
+ EngineeringAnalyticsViewSetBase,
+ _bad_request,
+ _optional_int_param,
+)
+
+_AUTHOR = OpenApiParameter(
+ name="author",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="GitHub login: scope the read to this author's pull requests. Pass exactly one scope.",
+)
+
+_GITHUB_TEAM = OpenApiParameter(
+ name="github_team",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="GitHub team slug: scope the read to pull requests authored by the team's members, through the team "
+ "membership table. Pass exactly one scope.",
+)
+
+_PR_NUMBER = OpenApiParameter(
+ name="pr_number",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Pull request number: scope the read to this one pull request. Needs repo. Pass exactly one scope.",
+)
+
+_REPO = OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="'owner/name' repository. Required with pr_number; otherwise it picks the repository when the "
+ "selected source syncs several.",
+)
+
+
+class DeliveryActionsMixin(EngineeringAnalyticsViewSetBase):
+ READ_ACTIONS = ["delivery_summary", "pull_request_timelines"]
+
+ @extend_schema(
+ operation_id="engineering_analytics_delivery_summary",
+ parameters=[_AUTHOR, _GITHUB_TEAM, _DATE_FROM, _DATE_TO, _SOURCE_ID, _REPO],
+ responses={
+ 200: DeliverySummarySerializer,
+ 400: OpenApiResponse(description="Not exactly one of author or github_team, or invalid date or source_id."),
+ },
+ description=(
+ "Delivery and CI friction for one author or one GitHub team over a window (date_from default -30d), each "
+ "figure next to the same figure over the whole repository: CI spend per merged PR, ready to merged split "
+ "at the first approval, pushes after approval, merge-queue attempts, and lead time to deploy. Bots and "
+ "drafts are excluded. Figures whose optional source isn't synced are null and flagged."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def delivery_summary(self, request: Request, **kwargs) -> Response:
+ try:
+ summary = api.get_delivery_summary(
+ team=self.team,
+ author=request.query_params.get("author") or None,
+ github_team=request.query_params.get("github_team") or None,
+ 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 scope, date, or source_id")
+ return Response(DeliverySummarySerializer(instance=summary).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_pull_request_timelines",
+ parameters=[_AUTHOR, _GITHUB_TEAM, _PR_NUMBER, _REPO, _DATE_FROM, _DATE_TO, _SOURCE_ID],
+ responses={
+ 200: PullRequestTimelinesSerializer,
+ 400: OpenApiResponse(
+ description="Not exactly one of author, github_team or pr_number, pr_number without repo, or invalid "
+ "date or source_id."
+ ),
+ },
+ description=(
+ "Pull requests as timelines of what each waited on from ready for review to merge or now: review, CI, "
+ "red checks by what turned them green, and the merge queue. Scope to one author or one GitHub team (open "
+ "PRs plus PRs merged in the window, date_from default -30d), or to one pull request with pr_number and "
+ "repo."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def pull_request_timelines(self, request: Request, **kwargs) -> Response:
+ try:
+ timelines = api.get_pull_request_timelines(
+ team=self.team,
+ author=request.query_params.get("author") or None,
+ github_team=request.query_params.get("github_team") or None,
+ pr_number=_optional_int_param(request, "pr_number"),
+ repo=request.query_params.get("repo") or None,
+ 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,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid scope, date, or source_id")
+ return Response(PullRequestTimelinesSerializer(instance=timelines).data)
diff --git a/products/engineering_analytics/backend/tests/test_delivery.py b/products/engineering_analytics/backend/tests/test_delivery.py
new file mode 100644
index 000000000000..756ed7fdb891
--- /dev/null
+++ b/products/engineering_analytics/backend/tests/test_delivery.py
@@ -0,0 +1,468 @@
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import APIBaseTest
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework import status
+
+from products.engineering_analytics.backend.facade.contracts import (
+ DeliveryScopeKind,
+ PRTimelineSegmentKind as Kind,
+ ScopeRepoFigure,
+)
+from products.engineering_analytics.backend.logic.delivery_scope import DeliveryScope
+from products.engineering_analytics.backend.logic.pr_timeline import (
+ GateAttempt,
+ MasterFailureIndex,
+ PRTimelineBuilder,
+ PRTimelineInput,
+ ReviewVerdict,
+ RunAttempt,
+)
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries.delivery_summary import (
+ CI_LOOKBACK,
+ DeliverySummaryAggregator,
+ MergedPRFacts,
+ query_delivery_summary,
+)
+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 (
+ ISSUE_EVENTS_COLUMNS,
+ PULL_REQUESTS_COLUMNS,
+ REVIEWS_COLUMNS,
+ TEAM_MEMBERS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
+)
+from products.engineering_analytics.backend.tests._github_fixtures import _issue_event_row, _pr_row, _run_row
+from products.engineering_analytics.backend.tests._logic_helpers import (
+ _ago,
+ _ago_offset_with_duration,
+ _dt,
+ _WarehouseMixin,
+)
+
+T0 = datetime(2026, 9, 1, 8, tzinfo=UTC)
+
+
+def _at(hours: float) -> datetime:
+ return T0 + timedelta(hours=hours)
+
+
+def _attempt(
+ sha: str,
+ start: float,
+ end: float | None,
+ *,
+ failed: bool = False,
+ succeeded: bool | None = None,
+ attempt: int = 1,
+ jobs: tuple[str, ...] = (),
+) -> RunAttempt:
+ return RunAttempt(
+ run_id=hash(sha) % 1000,
+ workflow_name="CI",
+ head_sha=sha,
+ attempt=attempt,
+ pushed_at=_at(start),
+ started_at=_at(start),
+ completed_at=_at(end) if end is not None else None,
+ failed=failed,
+ succeeded=(end is not None and not failed) if succeeded is None else succeeded,
+ failed_jobs=jobs,
+ )
+
+
+def _pr(
+ end: float,
+ attempts: list[RunAttempt],
+ *,
+ reviews: list[ReviewVerdict] | None = None,
+ gates: list[GateAttempt] | None = None,
+ is_open: bool = False,
+ is_merged: bool | None = None,
+ is_draft: bool = False,
+ trunk_out: bool = False,
+) -> PRTimelineInput:
+ return PRTimelineInput(
+ started_at=_at(0),
+ ended_at=_at(end),
+ is_open=is_open,
+ is_merged=not is_open if is_merged is None else is_merged,
+ is_draft=is_draft,
+ attempts=attempts,
+ gate_attempts=gates or [],
+ reviews=reviews,
+ trunk_out_of_queue=trunk_out,
+ )
+
+
+class TestPRTimelineBuilder(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "rerun_turns_red_green",
+ _pr(
+ 6,
+ [_attempt("a", 0, 1, failed=True), _attempt("a", 3, 4, attempt=2)],
+ reviews=[ReviewVerdict(reviewer="ada", state="APPROVED", submitted_at=_at(5))],
+ ),
+ [],
+ [
+ (Kind.CI_RUNNING, 0, 1),
+ (Kind.RED_PASSED_ON_RERUN, 1, 3),
+ (Kind.CI_RUNNING, 3, 4),
+ (Kind.WAITING_FOR_REVIEW, 4, 5),
+ (Kind.APPROVED_NOT_ENQUEUED, 5, 6),
+ ],
+ ),
+ (
+ "cancelled_rerun_is_not_a_pass",
+ _pr(5, [_attempt("a", 0, 1, failed=True), _attempt("a", 3, 4, attempt=2, succeeded=False)]),
+ [],
+ [
+ (Kind.CI_RUNNING, 0, 1),
+ (Kind.RED_NOT_PROVABLE, 1, 3),
+ (Kind.CI_RUNNING, 3, 4),
+ (Kind.REVIEW_STATE_UNKNOWN, 4, 5),
+ ],
+ ),
+ (
+ "later_push_ends_red",
+ _pr(4, [_attempt("a", 0, 1, failed=True), _attempt("b", 2, 3)]),
+ [],
+ [
+ (Kind.CI_RUNNING, 0, 1),
+ (Kind.RED_FIXED_BY_PUSH, 1, 2),
+ (Kind.CI_RUNNING, 2, 3),
+ (Kind.REVIEW_STATE_UNKNOWN, 3, 4),
+ ],
+ ),
+ (
+ "same_job_failing_on_master",
+ _pr(3, [_attempt("a", 0, 1, failed=True, jobs=("Backend tests (1/3)",))]),
+ [("CI", "Backend tests (2/3)", _at(-2))],
+ [(Kind.CI_RUNNING, 0, 1), (Kind.RED_MASTER_BROKEN, 1, 3)],
+ ),
+ (
+ "master_failure_too_far_away",
+ _pr(3, [_attempt("a", 0, 1, failed=True, jobs=("Backend tests (1/3)",))]),
+ [("CI", "Backend tests (2/3)", _at(-20))],
+ [(Kind.CI_RUNNING, 0, 1), (Kind.RED_NOT_PROVABLE, 1, 3)],
+ ),
+ (
+ "changes_requested_then_rereview_then_queue",
+ _pr(
+ 9,
+ [_attempt("a", 0, 1), _attempt("b", 4, 5)],
+ reviews=[
+ ReviewVerdict(reviewer="ada", state="CHANGES_REQUESTED", submitted_at=_at(2)),
+ ReviewVerdict(reviewer="ada", state="COMMENTED", submitted_at=_at(3)),
+ ReviewVerdict(reviewer="ada", state="APPROVED", submitted_at=_at(6)),
+ ],
+ gates=[GateAttempt(started_at=_at(7), completed_at=_at(8))],
+ ),
+ [],
+ [
+ (Kind.CI_RUNNING, 0, 1),
+ (Kind.WAITING_FOR_REVIEW, 1, 2),
+ (Kind.CHANGES_REQUESTED, 2, 4),
+ (Kind.CI_RUNNING, 4, 5),
+ (Kind.WAITING_FOR_REVIEW, 5, 6),
+ (Kind.APPROVED_NOT_ENQUEUED, 6, 7),
+ (Kind.MERGE_QUEUE, 7, 9),
+ ],
+ ),
+ (
+ "approval_from_another_reviewer_keeps_change_request_open",
+ _pr(
+ 4,
+ [_attempt("a", 0, 1)],
+ reviews=[
+ ReviewVerdict(reviewer="ada", state="CHANGES_REQUESTED", submitted_at=_at(2)),
+ ReviewVerdict(reviewer="bo", state="APPROVED", submitted_at=_at(3)),
+ ],
+ ),
+ [],
+ [(Kind.CI_RUNNING, 0, 1), (Kind.WAITING_FOR_REVIEW, 1, 2), (Kind.CHANGES_REQUESTED, 2, 4)],
+ ),
+ (
+ "open_pr_out_of_the_queue",
+ _pr(
+ 10,
+ [_attempt("a", 0, 1)],
+ reviews=[ReviewVerdict(reviewer="ada", state="APPROVED", submitted_at=_at(1))],
+ gates=[GateAttempt(started_at=_at(2), completed_at=_at(3))],
+ is_open=True,
+ trunk_out=True,
+ ),
+ [],
+ [
+ (Kind.CI_RUNNING, 0, 1),
+ (Kind.APPROVED_NOT_ENQUEUED, 1, 2),
+ (Kind.MERGE_QUEUE, 2, 3),
+ (Kind.OUT_OF_MERGE_QUEUE, 3, 10),
+ ],
+ ),
+ (
+ "closed_pr_queue_stops_at_the_gate_end",
+ _pr(
+ 10,
+ [_attempt("a", 0, 1)],
+ reviews=[ReviewVerdict(reviewer="ada", state="APPROVED", submitted_at=_at(1))],
+ gates=[GateAttempt(started_at=_at(2), completed_at=_at(3))],
+ is_merged=False,
+ ),
+ [],
+ [
+ (Kind.CI_RUNNING, 0, 1),
+ (Kind.APPROVED_NOT_ENQUEUED, 1, 2),
+ (Kind.MERGE_QUEUE, 2, 3),
+ (Kind.APPROVED_NOT_ENQUEUED, 3, 10),
+ ],
+ ),
+ (
+ "open_pr_still_red",
+ _pr(5, [_attempt("a", 0, 1, failed=True)], reviews=[], is_open=True),
+ [],
+ [(Kind.CI_RUNNING, 0, 1), (Kind.RED_NOT_PROVABLE, 1, 5)],
+ ),
+ (
+ "open_draft",
+ _pr(10, [_attempt("a", 0, 1, failed=True)], is_open=True, is_draft=True),
+ [],
+ [(Kind.DRAFT, 0, 10)],
+ ),
+ ]
+ )
+ def test_segments(
+ self,
+ _name: str,
+ pr: PRTimelineInput,
+ master_failures: list[tuple[str, str, datetime]],
+ expected: list[tuple[Kind, float, float]],
+ ) -> None:
+ segments = PRTimelineBuilder(pr, MasterFailureIndex(master_failures)).build()
+ assert [(s.kind, s.started_at, s.ended_at) for s in segments] == [
+ (kind, _at(start), _at(end)) for kind, start, end in expected
+ ]
+
+
+class TestDeliveryScope(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("nothing", {}),
+ ("two_people_at_once", {"author": "alice", "github_team": "team-replay"}),
+ ("blank_author", {"author": " "}),
+ ("pr_without_repo", {"pr_number": 21}),
+ ]
+ )
+ def test_rejects_anything_but_one_scope(self, _name: str, params: dict) -> None:
+ with self.assertRaises(ValueError):
+ DeliveryScope.from_params(
+ author=params.get("author"),
+ github_team=params.get("github_team"),
+ pr_number=params.get("pr_number"),
+ repo=params.get("repo"),
+ )
+
+
+def _facts(
+ number: int, *, in_scope: bool, ready_hours: float, approved_after_hours: float | None, pushes_after: list[float]
+) -> MergedPRFacts:
+ merged_at = _at(100)
+ ready_at = merged_at - timedelta(hours=ready_hours)
+ return MergedPRFacts(
+ number=number,
+ in_scope=in_scope,
+ created_at=ready_at - timedelta(hours=1),
+ merged_at=merged_at,
+ ready_to_merge_seconds=int(ready_hours * 3600),
+ approved_at=[ready_at + timedelta(hours=approved_after_hours)] if approved_after_hours is not None else [],
+ pushed_at=[ready_at + timedelta(hours=h) for h in pushes_after],
+ gate_attempts=[],
+ cost=None,
+ )
+
+
+class TestDeliverySummaryAggregator(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=[]),
+ ]
+ )
+
+ 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)
+
+
+def _review_row(review_id: int, pr_number: int, state: str, submitted_at: str) -> dict:
+ return {
+ "id": review_id,
+ "pr_number": pr_number,
+ "user": '{"login": "reviewer"}',
+ "state": state,
+ "commit_id": "",
+ "submitted_at": submitted_at,
+ }
+
+
+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}
+
+
+_ALICE = DeliveryScope.from_params(author="alice", github_team=None, pr_number=None, repo=None)
+_ALICES_TEAM = DeliveryScope.from_params(author=None, github_team="team-replay", pr_number=None, repo=None)
+
+
+class TestDeliveryReadsOnWarehouse(_WarehouseMixin):
+ def _seed(self) -> None:
+ self._create_table(
+ "github_pull_requests",
+ PULL_REQUESTS_COLUMNS,
+ [
+ _pr_row(21, "alice", "closed", 0, _ago(3), merged_at=_ago(1)),
+ _pr_row(22, "bob", "closed", 0, _ago(4), merged_at=_ago(1)),
+ _pr_row(23, "alice", "open", 0, _ago(2)),
+ _pr_row(24, "alice", "open", 1, _ago(1)),
+ _pr_row(26, "alice", "open", 0, _ago(60)),
+ # A bot's one-hour merge would drag the repo median down if bots counted.
+ _pr_row(
+ 25,
+ "dependabot[bot]",
+ "closed",
+ 0,
+ _ago_offset_with_duration(2, 0, 0)[0],
+ merged_at=_ago_offset_with_duration(2, 3600, 0)[0],
+ ),
+ ],
+ )
+ self._create_table(
+ "github_issue_events",
+ ISSUE_EVENTS_COLUMNS,
+ [
+ # The outer events bound the observed range, so PR 22's never-drafted life sits inside it.
+ _issue_event_row(1, "labeled", 22, _ago(10)),
+ _issue_event_row(2, "ready_for_review", 21, _ago(2)),
+ _issue_event_row(3, "labeled", 22, _ago(0)),
+ ],
+ )
+ self._create_table(
+ "github_reviews",
+ 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,
+ [_member_row(1, "alice", "team-replay"), _member_row(2, "bob", "team-ingestion")],
+ )
+ red_start, red_end = _ago_offset_with_duration(2, 0, 3600)
+ fix_start, fix_end = _ago_offset_with_duration(2, 8 * 3600, 3600)
+ gate_start, gate_end = _ago_offset_with_duration(2, 20 * 3600, 3600)
+ self._create_table(
+ "github_workflow_runs",
+ WORKFLOW_RUNS_COLUMNS,
+ [
+ _run_row(3001, "CI", "sha21a", "completed", "failure", red_start, red_end, pr_number=21),
+ _run_row(3002, "CI", "sha21b", "completed", "success", fix_start, fix_end, pr_number=21),
+ _run_row(
+ 3003,
+ "CI",
+ "sha21queue",
+ "completed",
+ "success",
+ gate_start,
+ gate_end,
+ pr_number=9001,
+ head_branch="trunk-merge/pr-21/cabec75e-5181-4429-aea5-0501a52d0688",
+ actor="trunk-io[bot]",
+ ),
+ _run_row(3004, "CI", "sha22", "completed", "success", _ago(2), _ago(2), pr_number=22),
+ ],
+ )
+
+ @parameterized.expand([("author", _ALICE), ("github_team", _ALICES_TEAM)])
+ def test_summary_compares_scope_with_repo_and_flags_missing_sources(self, _name: str, scope: DeliveryScope) -> None:
+ self._seed()
+ curated = CuratedGitHubSource.for_team(self.team)
+
+ summary = query_delivery_summary(
+ curated=curated, scope=scope, date_from=datetime.now(tz=UTC) - timedelta(days=7), date_to=None
+ )
+
+ assert (summary.opened_pr_count, summary.merged_pr_count, summary.open_pr_count, summary.draft_pr_count) == (
+ 3,
+ 1,
+ 2,
+ 1,
+ )
+ assert (summary.jobs_available, summary.review_data_available, summary.ready_data_available) == (
+ False,
+ True,
+ True,
+ )
+ assert summary.median_ready_to_merge_seconds.scope == 86400
+ assert summary.median_ready_to_merge_seconds.repo == (86400 + 3 * 86400) / 2
+ assert summary.pushes_after_approval_per_merged_pr.scope == 1
+ assert summary.merge_queue_attempts_per_merged_pr.scope == 1
+ assert summary.push_count == 2
+ assert summary.cost_per_merged_pr_usd.scope is None
+ assert summary.lead_time.deploy_data_available is False
+
+ @parameterized.expand(
+ [
+ ("author", _ALICE, {21, 23, 24, 26}),
+ ("github_team", _ALICES_TEAM, {21, 23, 24, 26}),
+ (
+ "one_pull_request",
+ DeliveryScope(
+ kind=DeliveryScopeKind.PULL_REQUEST, pr_number=21, repo_owner="PostHog", repo_name="posthog"
+ ),
+ {21},
+ ),
+ ]
+ )
+ def test_timelines_replay_each_pr_in_scope(self, _name: str, scope: DeliveryScope, expected: set[int]) -> None:
+ self._seed()
+ curated = CuratedGitHubSource.for_team(self.team)
+ date_from = datetime.now(tz=UTC) - timedelta(days=7)
+
+ 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]
+ merged = next(item for item in timelines.items if item.number == 21)
+ assert merged.author.handle == "alice"
+ assert merged.pushes == 2
+ 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
+
+
+class TestDeliveryEndpoints(APIBaseTest):
+ @parameterized.expand([("delivery_summary",), ("pull_request_timelines",)])
+ def test_requires_exactly_one_scope(self, action: 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"]
diff --git a/products/engineering_analytics/frontend/AGENTS.md b/products/engineering_analytics/frontend/AGENTS.md
index 85607340f5b7..a09a0c4ca880 100644
--- a/products/engineering_analytics/frontend/AGENTS.md
+++ b/products/engineering_analytics/frontend/AGENTS.md
@@ -8,9 +8,10 @@ UI grammar for every scene in this product. `frontend/src/AGENTS.md` and the rep
- Current-state content (a backlog, a "now" signal list) sits outside the panel and must not refetch when a picker changes. If a section does not move with the picker, it does not belong inside the border, and the reverse.
- Navigation (repo chip and crumbs via `ScopeBar`, `showDate={false}` when the page has its own picker) sits above the panel; it scopes identity, not time.
-## One comparison vocabulary
+## One comparison vocabulary per question
- Window-vs-window comparison renders as `WindowComparisonCard` ("This window / Previous window" bars plus a `DeltaBadge`). Nothing else: no invented forms (a muted "was N" companion value was tried and removed), no `MetricTile` delta pills for windowed metrics.
+- Scope-vs-repository comparison (an author or a team against the repository) renders as `ScopeComparisonCard` ("This author / Repo" bars on one scale). The question there is "is this friction unusual here", which a previous window can't answer. It never compares authors or teams with each other.
- Table cells hold plain current values via `CountCell` (`components/CountCell.tsx`). Comparison never lives in a table cell.
## Information altitude
diff --git a/products/engineering_analytics/frontend/components/ComparisonBarRow.tsx b/products/engineering_analytics/frontend/components/ComparisonBarRow.tsx
new file mode 100644
index 000000000000..34abbdcfb048
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/ComparisonBarRow.tsx
@@ -0,0 +1,61 @@
+// Every comparison card draws its bars with this row, so a comparison reads the same on every page.
+
+import { ReactNode } from 'react'
+
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { cn } from 'lib/utils/css-classes'
+
+export interface ComparisonBarMarker {
+ fraction: number
+ tooltip?: string
+}
+
+function fillClassName(muted: boolean, hasSegments: boolean): string {
+ if (hasSegments) {
+ return muted ? 'opacity-50' : ''
+ }
+ return muted ? 'bg-[var(--muted)]' : 'bg-[var(--data-color-1)]'
+}
+
+export function ComparisonBarRow({
+ label,
+ value,
+ fraction,
+ muted = false,
+ marker,
+ children,
+}: {
+ label: string
+ value: string
+ /** Bar length as a share of the track, 0–1. */
+ fraction: number
+ /** The baseline row (previous window, repo), drawn quieter than the row it is compared with. */
+ muted?: boolean
+ marker?: ComparisonBarMarker | null
+ /** Segments that fill the bar instead of one color, e.g. a pass/fail or before/after split. */
+ children?: ReactNode
+}): JSX.Element {
+ return (
+ <div className="flex items-center gap-2">
+ <span className="w-24 shrink-0 truncate text-[11px] text-tertiary">{label}</span>
+ <div className="relative h-2.5 flex-1">
+ <div
+ className={cn('h-full overflow-hidden rounded-sm', fillClassName(muted, children != null))}
+ style={{ width: `${Math.max(fraction * 100, 2)}%` }}
+ >
+ {children}
+ </div>
+ {marker && (
+ <Tooltip title={marker.tooltip}>
+ <div
+ className="absolute -top-0.5 h-3.5 w-0.5 -translate-x-1/2 rounded-sm bg-[var(--text-3000)]"
+ style={{ left: `${marker.fraction * 100}%` }}
+ />
+ </Tooltip>
+ )}
+ </div>
+ <span className="w-14 shrink-0 text-right text-xs font-medium tabular-nums">{value}</span>
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/LeadTimeComparisonCard.tsx b/products/engineering_analytics/frontend/components/LeadTimeComparisonCard.tsx
new file mode 100644
index 000000000000..6522af80b088
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/LeadTimeComparisonCard.tsx
@@ -0,0 +1,127 @@
+// Lead time to deploy for one scope (an author or a team) against the repository: one scope-vs-repo box
+// plot per stage. No DORA band edge here: a band on one person's or one team's lead time reads as a grade.
+
+import { LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
+
+import { pluralize } from 'lib/utils/strings'
+
+import type { DeliveryLeadTimeApi, DurationDistributionApi } from '../generated/api.schemas'
+import { compactAgeLabel } from '../lib/format'
+import { BoxPlotBucket, LeadTimeBoxPlot } from './LeadTimeBoxPlot'
+
+function toBucket(label: string, distribution: DurationDistributionApi): BoxPlotBucket {
+ return {
+ label,
+ count: distribution.pr_count,
+ minSeconds: distribution.min_seconds,
+ p05Seconds: distribution.p05_seconds,
+ p25Seconds: distribution.p25_seconds,
+ p50Seconds: distribution.p50_seconds,
+ meanSeconds: distribution.mean_seconds,
+ p75Seconds: distribution.p75_seconds,
+ p95Seconds: distribution.p95_seconds,
+ maxSeconds: distribution.max_seconds,
+ }
+}
+
+export function LeadTimeComparisonCard({
+ leadTime,
+ scopeLabel,
+ loading,
+}: {
+ leadTime: DeliveryLeadTimeApi | null | undefined
+ /** The box label for the scope, e.g. "This author" or "This team". */
+ scopeLabel: string
+ loading: boolean
+}): JSX.Element {
+ const stages = leadTime
+ ? [
+ { key: 'open_to_deploy', title: 'Open to deploy', pair: leadTime.open_to_deploy },
+ { key: 'open_to_merge', title: 'Open to merge', pair: leadTime.open_to_merge },
+ { key: 'merge_to_deploy', title: 'Merge to deploy', pair: leadTime.merge_to_deploy },
+ ]
+ : []
+ const headline = leadTime?.open_to_deploy.scope
+
+ return (
+ <LemonCard
+ hoverEffect={false}
+ className="flex flex-col p-4"
+ data-attr="engineering-analytics-delivery-lead-time"
+ >
+ <h3 className="mb-1 text-xs font-semibold text-secondary">
+ <Tooltip
+ title={
+ <div className="flex flex-col gap-1">
+ <div>
+ Merged pull requests (bots and drafts excluded), each matched once to the first
+ successful deploy that contains its merge, in the environments named under the headline.
+ Open to merge includes draft time. The three stages use the same pull requests. For each
+ one, open to merge and merge to deploy add up to open to deploy, but their medians do
+ not.
+ </div>
+ <div>
+ Box: the middle half of the pull requests. Line: median. Dot: mean. Whiskers: 5th to
+ 95th percentile.
+ </div>
+ <div>
+ Deploy failure share and recovery are not shown: one deploy ships many pull requests, so
+ neither belongs to one author or team. Health shows both for the repo.
+ </div>
+ </div>
+ }
+ >
+ <span className="cursor-default">Lead time to deploy</span>
+ </Tooltip>
+ </h3>
+ {loading ? (
+ <LemonSkeleton className="h-56 w-full" />
+ ) : !leadTime?.deploy_data_available ? (
+ <div className="flex h-20 items-center text-xs text-secondary">
+ Lead time appears once the deployments and deployment statuses tables on this GitHub source are
+ synced.
+ </div>
+ ) : !headline || headline.pr_count === 0 ? (
+ <div className="flex h-20 items-center text-xs text-secondary">
+ None of these pull requests reached a deploy in the window.
+ </div>
+ ) : (
+ <>
+ <div className="flex flex-wrap items-baseline gap-2">
+ <span className="text-2xl font-semibold leading-none tabular-nums">
+ {compactAgeLabel(headline.p50_seconds)}
+ </span>
+ <span className="text-xs tabular-nums text-tertiary">
+ open to deploy, median · repo {compactAgeLabel(leadTime.open_to_deploy.repo.p50_seconds)}
+ </span>
+ </div>
+ <div className="mb-3 mt-1 text-[11px] tabular-nums text-tertiary">
+ {leadTime.deployed_merged_pr_count} of{' '}
+ {pluralize(leadTime.merged_pr_count, 'merged pull request')} matched to a deploy in{' '}
+ {leadTime.environment_scope}
+ </div>
+ <div className="@container">
+ <div className="grid grid-cols-1 gap-4 @min-[40rem]:grid-cols-3">
+ {stages.map((stage) => (
+ <div key={stage.key} className="min-w-0">
+ <div className="text-[11px] font-semibold text-secondary">{stage.title}</div>
+ <LeadTimeBoxPlot
+ seriesKey={stage.key}
+ seriesLabel={stage.title}
+ buckets={[
+ toBucket(scopeLabel, stage.pair.scope),
+ toBucket('Repo', stage.pair.repo),
+ ]}
+ formatSeconds={compactAgeLabel}
+ excludeOutliers
+ dataAttr={`engineering-analytics-delivery-${stage.key}`}
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+ </LemonCard>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/PullRequestCountsCard.tsx b/products/engineering_analytics/frontend/components/PullRequestCountsCard.tsx
new file mode 100644
index 000000000000..cf0a117ff39d
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/PullRequestCountsCard.tsx
@@ -0,0 +1,57 @@
+// Plain pull request counts for a delivery scope. No repo figure on purpose: comparing how much an author
+// or a team ships ranks people, and these counts are only the denominators for the cards next to it.
+
+import { LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
+
+import type { DeliverySummaryApi } from '../generated/api.schemas'
+
+export function PullRequestCountsCard({
+ summary,
+ loading,
+}: {
+ summary: DeliverySummaryApi | null
+ loading: boolean
+}): JSX.Element {
+ const lines: [string, string][] = summary
+ ? [
+ ['Opened', String(summary.opened_pr_count)],
+ [
+ 'Deployed',
+ summary.lead_time.deploy_data_available ? String(summary.lead_time.deployed_merged_pr_count) : '—',
+ ],
+ ]
+ : []
+
+ return (
+ <LemonCard hoverEffect={false} className="flex flex-col p-4">
+ <h3 className="mb-1 text-xs font-semibold text-secondary">
+ <Tooltip title="Counts only, with no repo figure: how many pull requests someone ships is not friction, and comparing it would rank people. Merged and deployed count bots and drafts out.">
+ <span className="cursor-default">Pull requests in the window</span>
+ </Tooltip>
+ </h3>
+ {loading || !summary ? (
+ <LemonSkeleton className="h-20 w-full" />
+ ) : (
+ <>
+ <div className="mb-2 flex items-baseline gap-2">
+ <span className="text-2xl font-semibold leading-none tabular-nums">
+ {summary.merged_pr_count}
+ </span>
+ <span className="text-xs text-tertiary">merged</span>
+ </div>
+ <div className="flex flex-col">
+ {lines.map(([label, value]) => (
+ <div
+ key={label}
+ className="flex justify-between gap-2 border-t border-primary py-0.5 text-xs text-secondary"
+ >
+ <span>{label}</span>
+ <span className="font-semibold tabular-nums text-primary">{value}</span>
+ </div>
+ ))}
+ </div>
+ </>
+ )}
+ </LemonCard>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/PullRequestDayView.tsx b/products/engineering_analytics/frontend/components/PullRequestDayView.tsx
new file mode 100644
index 000000000000..8d67eaf94a1e
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/PullRequestDayView.tsx
@@ -0,0 +1,195 @@
+// Pull requests on a shared clock: each row starts at 06:00 on the day the pull request went ready (or
+// Monday 06:00 of that week), so nights and weekends line up across rows and a long wait reads as the
+// days it spanned. Groups put the work that needs attention first.
+
+import { LemonCard, LemonSegmentedButton, LemonSkeleton, Link, Tooltip } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { pluralize } from 'lib/utils/strings'
+import { urls } from 'scenes/urls'
+
+import type { PullRequestTimelinesApi } from '../generated/api.schemas'
+import { compactAgeLabel, compactUsd } from '../lib/format'
+import {
+ DAY_START_HOUR,
+ DayViewAlignment,
+ DayViewGroup,
+ DayViewRow,
+ SEGMENT_KIND_STYLES,
+ segmentBackground,
+} from '../lib/pullRequestDayView'
+import { withCurrentScope } from '../lib/scope'
+import { PullRequestTimelineLegend } from './PullRequestTimelineLegend'
+import { PullRequestTimelineTrack } from './PullRequestTimelineTrack'
+
+const WEEKDAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
+const ROW_GRID =
+ 'grid grid-cols-[minmax(6rem,11rem)_minmax(0,1fr)_3rem] items-center gap-2 @min-[48rem]:grid-cols-[minmax(9rem,16rem)_minmax(0,1fr)_3rem_11rem]'
+
+function DayViewRowItem({
+ row,
+ alignment,
+ days,
+ generatedAt,
+ sourceId,
+ showAuthor,
+}: {
+ row: DayViewRow
+ alignment: DayViewAlignment
+ days: number
+ generatedAt: string
+ sourceId: string | null
+ showAuthor: boolean
+}): JSX.Element {
+ const { pr } = row
+ const highlight = SEGMENT_KIND_STYLES[row.highlightKind]
+ const hover = [
+ pr.title,
+ showAuthor ? `by ${pr.author.handle}` : null,
+ `timeline from ${dayjs(pr.started_at).format('ddd D MMM HH:mm')}`,
+ pluralize(pr.pushes, 'push', 'pushes'),
+ pr.estimated_cost_usd != null ? `CI cost ${compactUsd(pr.estimated_cost_usd)}` : null,
+ ]
+ .filter(Boolean)
+ .join(' · ')
+ return (
+ <div className={`${ROW_GRID} py-0.5 text-xs`}>
+ <Tooltip title={hover}>
+ <Link
+ to={withCurrentScope(
+ urls.engineeringAnalyticsPullRequest(pr.repo.owner, pr.repo.name, pr.number),
+ sourceId
+ )}
+ className="flex min-w-0 items-baseline gap-1.5"
+ >
+ <span className="shrink-0 tabular-nums">#{pr.number}</span>
+ <span className="truncate text-[11px] text-secondary">{pr.title}</span>
+ </Link>
+ </Tooltip>
+ <PullRequestTimelineTrack pr={pr} alignment={alignment} days={days} generatedAt={generatedAt} />
+ <span className="text-right text-[11px] tabular-nums text-tertiary">
+ {row.isOpen && <span className="mr-1 inline-block size-1.5 rounded-full bg-success align-middle" />}
+ {compactAgeLabel(row.lengthSeconds)}
+ </span>
+ <span className="hidden min-w-0 items-center gap-1 truncate text-[11px] text-secondary @min-[48rem]:flex">
+ <span className="size-2 shrink-0 rounded-sm" style={segmentBackground(row.highlightKind)} />
+ <span className="truncate">
+ {row.isOpen ? 'now: ' : 'most: '}
+ <span className="font-semibold text-primary">{highlight.short}</span>{' '}
+ {compactAgeLabel(row.highlightSeconds)}
+ </span>
+ </span>
+ </div>
+ )
+}
+
+export function PullRequestDayView({
+ timelines,
+ groups,
+ days,
+ alignment,
+ onAlignmentChange,
+ loading,
+ sourceId,
+ showAuthor = false,
+}: {
+ timelines: PullRequestTimelinesApi | null
+ groups: DayViewGroup[]
+ days: number
+ alignment: DayViewAlignment
+ onAlignmentChange: (alignment: DayViewAlignment) => void
+ loading: boolean
+ sourceId: string | null
+ /** Name each pull request's author on hover, for scopes that list several authors (a team). */
+ showAuthor?: boolean
+}): JSX.Element {
+ const step = days > 7 ? 2 : 1
+ const ticks = Array.from({ length: Math.ceil(days / step) }).map((_, index) => index * step)
+ const alignmentNote =
+ alignment === 'weeks'
+ ? `Rows start at Monday ${DAY_START_HOUR}:00 of the week each timeline starts, so weekdays line up.`
+ : `Rows start at ${DAY_START_HOUR}:00 on the day each timeline starts, so nights and weekends line up.`
+
+ return (
+ <LemonCard hoverEffect={false} className="@container p-4" data-attr="engineering-analytics-day-view">
+ <div className="mb-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
+ <PullRequestTimelineLegend />
+ <div className="flex items-center gap-2">
+ <Tooltip
+ title={`${alignmentNote} Shaded: nights 22:00 to 06:00 and weekends, in your time zone. The axis stretches to fit 90% of the pull requests; longer bars end in ›.`}
+ >
+ <span className="cursor-default text-[11px] text-tertiary">
+ axis fits {pluralize(days, 'day')}
+ </span>
+ </Tooltip>
+ <LemonSegmentedButton
+ size="xsmall"
+ value={alignment}
+ onChange={onAlignmentChange}
+ options={[
+ { value: 'days', label: 'Days' },
+ { value: 'weeks', label: 'Weeks' },
+ ]}
+ data-attr="engineering-analytics-day-view-alignment"
+ />
+ </div>
+ </div>
+ {loading && !timelines ? (
+ <div className="flex flex-col gap-2">
+ {Array.from({ length: 6 }).map((_, index) => (
+ <LemonSkeleton key={index} className="h-3.5 w-full" />
+ ))}
+ </div>
+ ) : groups.length === 0 ? (
+ <div className="py-6 text-center text-xs text-secondary">
+ {timelines?.scope_kind === 'github_team' && !timelines.has_membership_data
+ ? 'Team pull requests appear once the team members table on this GitHub source is synced.'
+ : 'No open pull requests, and nothing merged in the window.'}
+ </div>
+ ) : (
+ <>
+ <div className={`${ROW_GRID} mb-1 text-[10px] text-tertiary`}>
+ <span />
+ <div className="relative h-3.5 overflow-hidden">
+ {ticks.map((day) => (
+ <span
+ key={day}
+ className="absolute whitespace-nowrap pl-0.5"
+ style={{ left: `${(100 * day) / days}%` }}
+ >
+ {alignment === 'weeks' ? WEEKDAYS[day % 7] : `Day ${day + 1}`}
+ </span>
+ ))}
+ </div>
+ </div>
+ {groups.map((group, index) => (
+ <div key={group.key}>
+ <div
+ className={`mb-1 flex items-center gap-2 text-[11px] font-semibold text-secondary ${index > 0 ? 'mt-2 border-t border-primary pt-2' : ''}`}
+ >
+ {group.label}
+ <span className="font-normal text-tertiary">{group.rows.length}</span>
+ </div>
+ {group.rows.map((row) => (
+ <DayViewRowItem
+ key={`${row.pr.repo.owner}/${row.pr.repo.name}#${row.pr.number}`}
+ row={row}
+ alignment={alignment}
+ days={days}
+ generatedAt={timelines?.generated_at ?? ''}
+ sourceId={sourceId}
+ showAuthor={showAuthor}
+ />
+ ))}
+ </div>
+ ))}
+ {timelines?.truncated && (
+ <div className="mt-2 text-[11px] text-tertiary">
+ Showing the newest {timelines.limit} pull requests. Narrow the window to see the rest.
+ </div>
+ )}
+ </>
+ )}
+ </LemonCard>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/PullRequestTimelineLegend.tsx b/products/engineering_analytics/frontend/components/PullRequestTimelineLegend.tsx
new file mode 100644
index 000000000000..2778bc0a7541
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/PullRequestTimelineLegend.tsx
@@ -0,0 +1,21 @@
+// The legend for pull request timeline tracks, grouped by who can move a pull request out of each state.
+
+import { SEGMENT_KIND_STYLES, SEGMENT_LEGEND_GROUPS, segmentBackground } from '../lib/pullRequestDayView'
+
+export function PullRequestTimelineLegend(): JSX.Element {
+ return (
+ <div className="flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-secondary">
+ {SEGMENT_LEGEND_GROUPS.map((group) => (
+ <span key={group.label} className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span className="text-tertiary">{group.label}</span>
+ {group.kinds.map((kind) => (
+ <span key={kind} className="flex items-center gap-1">
+ <span className="h-2.5 w-3 rounded-sm" style={segmentBackground(kind)} />
+ {SEGMENT_KIND_STYLES[kind].short}
+ </span>
+ ))}
+ </span>
+ ))}
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/PullRequestTimelineTrack.tsx b/products/engineering_analytics/frontend/components/PullRequestTimelineTrack.tsx
new file mode 100644
index 000000000000..d1a4db13d2d7
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/PullRequestTimelineTrack.tsx
@@ -0,0 +1,107 @@
+// One pull request's timeline as a track on a shared clock. The day view stacks one per row, and a
+// single pull request page can draw one on its own with the same axis rules.
+
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+
+import type { PRTimelineApi } from '../generated/api.schemas'
+import { compactAgeLabel } from '../lib/format'
+import {
+ DayViewAlignment,
+ NIGHT_START_OFFSET_HOURS,
+ SEGMENT_KIND_STYLES,
+ hoursFromOrigin,
+ rowOrigin,
+ segmentBackground,
+} from '../lib/pullRequestDayView'
+
+export function PullRequestTimelineTrack({
+ pr,
+ alignment,
+ days,
+ generatedAt,
+}: {
+ pr: PRTimelineApi
+ alignment: DayViewAlignment
+ /** Days the axis spans (see axisDays); a longer timeline ends in a clip marker. */
+ days: number
+ /** The "now" an open pull request's last segment ends at. */
+ generatedAt: string
+}): JSX.Element {
+ const origin = rowOrigin(pr.started_at, alignment)
+ const hours = days * 24
+ const pct = (value: number): string => `${(100 * value) / hours}%`
+ const segments = pr.segments
+ const isOpen = pr.state === 'open'
+ const end = segments.length ? hoursFromOrigin(origin, segments[segments.length - 1].ended_at) : 0
+
+ return (
+ <div className="relative h-3.5 overflow-hidden rounded-sm">
+ {Array.from({ length: days }).map((_, day) => {
+ const weekday = origin.add(day, 'day').day()
+ return (
+ <div key={day}>
+ {(weekday === 0 || weekday === 6) && (
+ <div
+ className="absolute inset-y-0 bg-fill-secondary"
+ style={{ left: pct(day * 24), width: pct(24) }}
+ />
+ )}
+ <div
+ className="absolute inset-y-0 bg-fill-tertiary"
+ style={{
+ left: pct(day * 24 + NIGHT_START_OFFSET_HOURS),
+ width: pct(24 - NIGHT_START_OFFSET_HOURS),
+ }}
+ />
+ {day > 0 && (
+ <div
+ className="absolute inset-y-0 w-px bg-border-primary"
+ style={{ left: pct(day * 24) }}
+ />
+ )}
+ </div>
+ )
+ })}
+ {segments.map((segment, index) => {
+ const start = hoursFromOrigin(origin, segment.started_at)
+ if (start >= hours) {
+ return null
+ }
+ const segmentEnd = Math.min(hoursFromOrigin(origin, segment.ended_at), hours)
+ const live = isOpen && index === segments.length - 1
+ const duration = dayjs(segment.ended_at).diff(dayjs(segment.started_at), 'second')
+ const style = SEGMENT_KIND_STYLES[segment.kind]
+ return (
+ <Tooltip
+ key={segment.started_at}
+ title={`${style.label} · ${compactAgeLabel(duration)}${live ? ' so far' : ''} · from ${dayjs(segment.started_at).format('ddd D MMM HH:mm')}`}
+ >
+ <div
+ className="absolute inset-y-px min-w-0.5 rounded-sm"
+ style={{
+ left: pct(start),
+ width: pct(Math.max(segmentEnd - start, 0.05)),
+ ...segmentBackground(segment.kind),
+ }}
+ />
+ </Tooltip>
+ )
+ })}
+ {isOpen && segments.length > 0 && end <= hours && (
+ <Tooltip title={`Now, ${dayjs(generatedAt).format('ddd HH:mm')}`}>
+ <div
+ className="absolute -inset-y-px w-[3px] -translate-x-px rounded-sm bg-[var(--text-3000)]"
+ style={{ left: pct(end) }}
+ />
+ </Tooltip>
+ )}
+ {end > hours && (
+ <span className="absolute inset-y-0 right-0 flex w-3.5 items-center justify-center bg-surface-primary text-[11px] font-bold">
+ ›
+ </span>
+ )}
+ </div>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/ReadyToMergeCard.tsx b/products/engineering_analytics/frontend/components/ReadyToMergeCard.tsx
new file mode 100644
index 000000000000..c01742f1a7ce
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/ReadyToMergeCard.tsx
@@ -0,0 +1,178 @@
+// Ready for review to merged, split at the first approval. Medians of the two legs do not add up to
+// the median of the whole, so the bar length is the whole median and the split is the share of summed
+// hours on each side of the approval. The leg medians sit under the bars as separate numbers.
+
+import { LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
+
+import type { DeliverySummaryApi } from '../generated/api.schemas'
+import { compactAgeLabel, percent } from '../lib/format'
+import { ComparisonBarRow } from './ComparisonBarRow'
+
+const BEFORE_APPROVAL_COLOR = 'var(--data-color-3)'
+const AFTER_APPROVAL_COLOR = 'var(--data-color-1)'
+
+function ApprovalSplit({ beforeShare }: { beforeShare: number | null }): JSX.Element {
+ if (beforeShare == null) {
+ return <div className="h-full bg-[var(--muted)]" />
+ }
+ return (
+ <div className="flex h-full gap-px">
+ <Tooltip title={`Before the first approval: ${percent(beforeShare)} of the hours`}>
+ <div
+ className="h-full"
+ style={{ flex: `${beforeShare} 1 0`, backgroundColor: BEFORE_APPROVAL_COLOR }}
+ />
+ </Tooltip>
+ <Tooltip title={`After the first approval: ${percent(1 - beforeShare)} of the hours`}>
+ <div
+ className="h-full"
+ style={{ flex: `${1 - beforeShare} 1 0`, backgroundColor: AFTER_APPROVAL_COLOR }}
+ />
+ </Tooltip>
+ </div>
+ )
+}
+
+function SplitRow({
+ label,
+ value,
+ p90,
+ beforeShare,
+ max,
+ isScope,
+}: {
+ label: string
+ value: number
+ p90: number | null
+ beforeShare: number | null
+ max: number
+ isScope: boolean
+}): JSX.Element {
+ return (
+ <ComparisonBarRow
+ label={label}
+ value={compactAgeLabel(value)}
+ fraction={value / max}
+ muted={!isScope}
+ marker={p90 != null ? { fraction: p90 / max, tooltip: `90th percentile ${compactAgeLabel(p90)}` } : null}
+ >
+ <ApprovalSplit beforeShare={beforeShare} />
+ </ComparisonBarRow>
+ )
+}
+
+function LegRow({
+ color,
+ label,
+ scope,
+ repo,
+}: {
+ color: string
+ label: string
+ scope: number | null
+ repo: number | null
+}): JSX.Element {
+ return (
+ <div className="grid grid-cols-[minmax(0,1fr)_auto_5rem] items-baseline gap-2 border-t border-primary py-1 text-xs text-secondary">
+ <span className="flex min-w-0 items-center gap-1.5">
+ <span className="size-2 shrink-0 rounded-sm" style={{ backgroundColor: color }} />
+ <span className="truncate">{label}</span>
+ </span>
+ <span className="font-semibold tabular-nums text-primary">{compactAgeLabel(scope)}</span>
+ <span className="text-right tabular-nums text-tertiary">repo {compactAgeLabel(repo)}</span>
+ </div>
+ )
+}
+
+export function ReadyToMergeCard({
+ summary,
+ scopeLabel,
+ loading,
+}: {
+ summary: DeliverySummaryApi | null
+ /** The row label for the scope's bar, e.g. "This author" or "This team". */
+ scopeLabel: string
+ loading: boolean
+}): JSX.Element {
+ const median = summary?.median_ready_to_merge_seconds
+ const p90 = summary?.p90_ready_to_merge_seconds
+ const share = summary?.before_first_approval_share
+ const reviewsSynced = !!summary?.review_data_available
+ const max = Math.max(...[median?.scope, median?.repo, p90?.scope, p90?.repo].map((value) => value ?? 0))
+
+ return (
+ <LemonCard
+ hoverEffect={false}
+ className="flex h-full flex-col p-4"
+ data-attr="engineering-analytics-delivery-ready"
+ >
+ <h3 className="mb-1 text-xs font-semibold text-secondary">
+ <Tooltip title="Median calendar time from the last ready for review to the merge, over pull requests merged in the window. The bar length is that median. Its split is the share of all those hours spent before and after the first approval, so long pull requests weigh more. The two medians below are separate medians and do not add up to the total.">
+ <span className="cursor-default">Ready for review to merged</span>
+ </Tooltip>
+ </h3>
+ {loading ? (
+ <LemonSkeleton className="h-24 w-full" />
+ ) : median?.scope != null ? (
+ <>
+ <div className="mb-3 flex flex-wrap items-baseline gap-2">
+ <span className="text-2xl font-semibold leading-none tabular-nums">
+ {compactAgeLabel(median.scope)}
+ </span>
+ {median.repo != null && (
+ <span className="text-xs tabular-nums text-tertiary">
+ repo {compactAgeLabel(median.repo)}
+ </span>
+ )}
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <SplitRow
+ label={scopeLabel}
+ value={median.scope}
+ p90={p90?.scope ?? null}
+ beforeShare={reviewsSynced ? (share?.scope ?? null) : null}
+ max={max}
+ isScope
+ />
+ {median.repo != null && (
+ <SplitRow
+ label="Repo"
+ value={median.repo}
+ p90={p90?.repo ?? null}
+ beforeShare={reviewsSynced ? (share?.repo ?? null) : null}
+ max={max}
+ isScope={false}
+ />
+ )}
+ </div>
+ {reviewsSynced ? (
+ <div className="mt-3 flex flex-col">
+ <LegRow
+ color={BEFORE_APPROVAL_COLOR}
+ label="Ready to first approval, median"
+ scope={summary?.median_ready_to_first_approval_seconds.scope ?? null}
+ repo={summary?.median_ready_to_first_approval_seconds.repo ?? null}
+ />
+ <LegRow
+ color={AFTER_APPROVAL_COLOR}
+ label="First approval to merged, median"
+ scope={summary?.median_first_approval_to_merge_seconds.scope ?? null}
+ repo={summary?.median_first_approval_to_merge_seconds.repo ?? null}
+ />
+ </div>
+ ) : (
+ <div className="mt-2 text-[11px] text-tertiary">
+ Sync the reviews table on this GitHub source to split the wait at the first approval.
+ </div>
+ )}
+ </>
+ ) : (
+ <div className="flex h-20 items-center text-xs text-secondary">
+ {summary && !summary.ready_data_available
+ ? 'Ready time appears once the issue events table on this GitHub source is synced.'
+ : 'No merged pull requests with a known ready time in the window.'}
+ </div>
+ )}
+ </LemonCard>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/RedTimeByCauseCard.tsx b/products/engineering_analytics/frontend/components/RedTimeByCauseCard.tsx
new file mode 100644
index 000000000000..b0c4da54c39c
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/RedTimeByCauseCard.tsx
@@ -0,0 +1,102 @@
+// Red check time on the listed merged pull requests, split by what turned the check green. No repo
+// figure: the cause comes from replaying each pull request's timeline, which is too heavy to run over
+// the whole repository per request.
+
+import { LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
+
+import { pluralize } from 'lib/utils/strings'
+
+import { compactAgeLabel } from '../lib/format'
+import { RedTimeByCause, SEGMENT_KIND_STYLES, segmentBackground } from '../lib/pullRequestDayView'
+
+export function RedTimeByCauseCard({
+ redTime,
+ loading,
+ jobsAvailable,
+}: {
+ redTime: RedTimeByCause
+ loading: boolean
+ jobsAvailable: boolean
+}): JSX.Element {
+ const total = redTime.totalSecondsPerMergedPr
+
+ return (
+ <LemonCard
+ hoverEffect={false}
+ className="flex flex-col p-4"
+ data-attr="engineering-analytics-delivery-red-time"
+ >
+ <h3 className="mb-1 text-xs font-semibold text-secondary">
+ <Tooltip
+ title={
+ <div className="flex flex-col gap-1">
+ <div>
+ Time a merged pull request's latest commit had a failed check, per merged pull request,
+ split by what turned it green.
+ </div>
+ <div>
+ Flake: the failed workflow passed a re-run of the same commit. Master broken: the failed
+ jobs also failed on the default branch within 12 hours. Fixed by a push: a later commit
+ arrived. Not provable: none of those.
+ </div>
+ <div>
+ There is no repo figure: the cause comes from replaying each pull request, which only
+ runs for the pull requests listed here.
+ </div>
+ {!jobsAvailable && (
+ <div>
+ The workflow jobs table isn't synced, so flakes and master breakage can't be seen.
+ </div>
+ )}
+ </div>
+ }
+ >
+ <span className="cursor-default">Red checks, by what turned them green</span>
+ </Tooltip>
+ </h3>
+ {loading ? (
+ <LemonSkeleton className="h-16 w-full" />
+ ) : redTime.mergedCount === 0 ? (
+ <div className="flex h-16 items-center text-xs text-secondary">
+ No merged pull requests in the window.
+ </div>
+ ) : (
+ <>
+ <div className="mb-3 flex flex-wrap items-baseline gap-2">
+ <span className="text-2xl font-semibold leading-none tabular-nums">
+ {total > 0 ? compactAgeLabel(total) : '0m'}
+ </span>
+ <span className="text-xs tabular-nums text-tertiary">
+ red per merged pull request, over {pluralize(redTime.mergedCount, 'merged pull request')}
+ </span>
+ </div>
+ {total > 0 && (
+ <div className="flex h-2.5 gap-px overflow-hidden rounded-sm">
+ {redTime.secondsPerMergedPr
+ .filter((entry) => entry.seconds > 0)
+ .map((entry) => (
+ <Tooltip
+ key={entry.kind}
+ title={`${SEGMENT_KIND_STYLES[entry.kind].label}: ${compactAgeLabel(entry.seconds)} per merged pull request`}
+ >
+ <div
+ className="h-full"
+ style={{ flex: `${entry.seconds} 1 0`, ...segmentBackground(entry.kind) }}
+ />
+ </Tooltip>
+ ))}
+ </div>
+ )}
+ <div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-secondary">
+ {redTime.secondsPerMergedPr.map((entry) => (
+ <span key={entry.kind} className="flex items-center gap-1 tabular-nums">
+ <span className="size-2.5 rounded-sm" style={segmentBackground(entry.kind)} />
+ {SEGMENT_KIND_STYLES[entry.kind].short} {compactAgeLabel(entry.seconds || null)}
+ </span>
+ ))}
+ </div>
+ </>
+ )}
+ </LemonCard>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/ScopeComparisonCard.tsx b/products/engineering_analytics/frontend/components/ScopeComparisonCard.tsx
new file mode 100644
index 000000000000..8fd2c5da4e46
--- /dev/null
+++ b/products/engineering_analytics/frontend/components/ScopeComparisonCard.tsx
@@ -0,0 +1,127 @@
+// A scope-against-repo card: one author's or one team's figure next to the same figure over the whole
+// repository. The question is "is this unusual here", so the graphic is two labeled bars on a shared
+// zero-based scale. Window-over-window comparisons use WindowComparisonCard instead.
+
+import { ReactNode } from 'react'
+
+import { LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
+
+import type { ScopeRepoFigureApi } from '../generated/api.schemas'
+import { ComparisonBarRow } from './ComparisonBarRow'
+
+function ComparisonRow({
+ label,
+ value,
+ max,
+ formatValue,
+ isScope,
+ marker,
+ markerLabel,
+}: {
+ label: string
+ value: number
+ max: number
+ formatValue: (value: number) => string
+ isScope: boolean
+ marker?: number | null
+ markerLabel?: string
+}): JSX.Element {
+ return (
+ <ComparisonBarRow
+ label={label}
+ value={formatValue(value)}
+ fraction={max > 0 ? value / max : 0}
+ muted={!isScope}
+ marker={
+ marker != null && max > 0
+ ? { fraction: marker / max, tooltip: `${markerLabel} ${formatValue(marker)}` }
+ : null
+ }
+ />
+ )
+}
+
+export function ScopeComparisonCard({
+ title,
+ tooltip,
+ scopeLabel,
+ figure,
+ formatValue,
+ marker,
+ markerLabel,
+ caption,
+ loading = false,
+ emptyText,
+ dataAttr,
+}: {
+ title: string
+ /** Definition or methodology, shown on title hover. */
+ tooltip?: ReactNode
+ /** The row label for the scope's bar, e.g. "This author" or "This team". */
+ scopeLabel: string
+ figure: ScopeRepoFigureApi | null | undefined
+ formatValue: (value: number) => string
+ /** A companion figure (e.g. p90) pinned as a tick on each bar, on the same scale. */
+ marker?: ScopeRepoFigureApi | null
+ markerLabel?: string
+ /** The totals behind the figure, under the bars. */
+ caption?: ReactNode
+ loading?: boolean
+ emptyText: string
+ dataAttr?: string
+}): JSX.Element {
+ const scope = figure?.scope
+ const repo = figure?.repo
+ const max = Math.max(...[scope, repo, marker?.scope, marker?.repo].map((value) => value ?? 0))
+
+ return (
+ <LemonCard hoverEffect={false} className="flex flex-col p-4" data-attr={dataAttr}>
+ <h3 className="mb-1 text-xs font-semibold text-secondary">
+ {tooltip ? (
+ <Tooltip title={tooltip}>
+ <span className="cursor-default">{title}</span>
+ </Tooltip>
+ ) : (
+ title
+ )}
+ </h3>
+ {loading ? (
+ <LemonSkeleton className="h-20 w-full" />
+ ) : scope != null ? (
+ <>
+ <div className="mb-3 flex flex-wrap items-baseline gap-2">
+ <span className="text-2xl font-semibold leading-none tabular-nums">{formatValue(scope)}</span>
+ {repo != null && (
+ <span className="text-xs tabular-nums text-tertiary">repo {formatValue(repo)}</span>
+ )}
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <ComparisonRow
+ label={scopeLabel}
+ value={scope}
+ max={max}
+ formatValue={formatValue}
+ isScope
+ marker={marker?.scope}
+ markerLabel={markerLabel}
+ />
+ {repo != null && (
+ <ComparisonRow
+ label="Repo"
+ value={repo}
+ max={max}
+ formatValue={formatValue}
+ isScope={false}
+ marker={marker?.repo}
+ markerLabel={markerLabel}
+ />
+ )}
+ </div>
+ {caption && <div className="mt-2 text-[11px] tabular-nums text-tertiary">{caption}</div>}
+ </>
+ ) : (
+ <div className="flex h-20 items-center text-xs text-secondary">{emptyText}</div>
+ )}
+ </LemonCard>
+ )
+}
diff --git a/products/engineering_analytics/frontend/components/WindowComparisonCard.tsx b/products/engineering_analytics/frontend/components/WindowComparisonCard.tsx
index a54416fb68f0..7a3eb2728ccb 100644
--- a/products/engineering_analytics/frontend/components/WindowComparisonCard.tsx
+++ b/products/engineering_analytics/frontend/components/WindowComparisonCard.tsx
@@ -12,6 +12,7 @@ import { LemonCard, LemonSkeleton, Tooltip } from '@posthog/lemon-ui'
import { cn } from 'lib/utils/css-classes'
import { percent } from '../lib/format'
+import { ComparisonBarRow } from './ComparisonBarRow'
import { DeltaBadge, percentChange, pointChange, type TileBenchmark } from './MetricTile'
const BENCHMARK_EDGE_CLASS: Record<TileBenchmark['band'], string> = {
@@ -21,39 +22,10 @@ const BENCHMARK_EDGE_CLASS: Record<TileBenchmark['band'], string> = {
low: 'border-l-danger',
}
-function MagnitudeBar({
- fraction,
- current,
- markerFraction,
- markerTooltip,
-}: {
- fraction: number
- current: boolean
- markerFraction?: number | null
- markerTooltip?: string
-}): JSX.Element {
- return (
- <div className="relative h-2.5 flex-1 rounded-sm">
- <div
- className={`h-full rounded-sm ${current ? 'bg-[var(--data-color-1)]' : 'bg-[var(--muted)]'}`}
- style={{ width: `${Math.max(fraction * 100, 2)}%` }}
- />
- {markerFraction != null && (
- <Tooltip title={markerTooltip}>
- <div
- className="absolute -top-0.5 h-3.5 w-0.5 -translate-x-1/2 rounded-sm bg-[var(--text-3000)]"
- style={{ left: `${markerFraction * 100}%` }}
- />
- </Tooltip>
- )}
- </div>
- )
-}
-
-function SplitBar({ rate }: { rate: number }): JSX.Element {
+function PassFailSplit({ rate }: { rate: number }): JSX.Element {
return (
<Tooltip title={`${percent(rate, 1)} passed, ${percent(1 - rate, 1)} failed`}>
- <div className="flex h-2.5 flex-1 overflow-hidden rounded-sm">
+ <div className="flex h-full">
<div className="h-full bg-success" style={{ width: `${rate * 100}%` }} />
<div className="h-full flex-1 bg-danger" />
</div>
@@ -81,21 +53,28 @@ function ComparisonRow({
marker?: number | null
markerLabel?: string
}): JSX.Element {
+ if (share) {
+ return (
+ <ComparisonBarRow label={label} value={formatValue(value)} fraction={1}>
+ <PassFailSplit rate={value} />
+ </ComparisonBarRow>
+ )
+ }
return (
- <div className="flex items-center gap-2">
- <span className="w-24 shrink-0 text-[11px] text-tertiary">{label}</span>
- {share ? (
- <SplitBar rate={value} />
- ) : (
- <MagnitudeBar
- fraction={max > 0 ? value / max : 0}
- current={current}
- markerFraction={marker != null && max > 0 ? marker / max : null}
- markerTooltip={marker != null && markerLabel ? `${markerLabel} ${formatValue(marker)}` : undefined}
- />
- )}
- <span className="w-12 shrink-0 text-right text-xs font-medium tabular-nums">{formatValue(value)}</span>
- </div>
+ <ComparisonBarRow
+ label={label}
+ value={formatValue(value)}
+ fraction={max > 0 ? value / max : 0}
+ muted={!current}
+ marker={
+ marker != null && max > 0
+ ? {
+ fraction: marker / max,
+ tooltip: markerLabel ? `${markerLabel} ${formatValue(marker)}` : undefined,
+ }
+ : null
+ }
+ />
)
}
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index 221a89d3412a..a12f29dc7baa 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -201,6 +201,164 @@ export interface CurrentBranchHealthApi {
failing_workflow_names: string[]
}
+export interface ScopeRepoFigureApi {
+ /**
+ * The figure over the pull requests in scope. Null when the scope has nothing to measure.
+ * @nullable
+ */
+ scope: number | null
+ /**
+ * The same figure over every non-bot pull request in the repository, the scope included. Null when the repository has nothing to measure.
+ * @nullable
+ */
+ repo: number | null
+}
+
+export interface DurationDistributionApi {
+ /** Pull requests in the distribution. Every statistic is null when this is 0. */
+ pr_count: number
+ /**
+ * Fastest duration, in seconds.
+ * @nullable
+ */
+ min_seconds: number | null
+ /**
+ * 5th percentile, in seconds: the lower whisker.
+ * @nullable
+ */
+ p05_seconds: number | null
+ /**
+ * 25th percentile, in seconds: the box's lower edge.
+ * @nullable
+ */
+ p25_seconds: number | null
+ /**
+ * Median, in seconds.
+ * @nullable
+ */
+ p50_seconds: number | null
+ /**
+ * Mean, in seconds.
+ * @nullable
+ */
+ mean_seconds: number | null
+ /**
+ * 75th percentile, in seconds: the box's upper edge.
+ * @nullable
+ */
+ p75_seconds: number | null
+ /**
+ * 95th percentile, in seconds: the upper whisker.
+ * @nullable
+ */
+ p95_seconds: number | null
+ /**
+ * Slowest duration, in seconds.
+ * @nullable
+ */
+ max_seconds: number | null
+}
+
+export interface ScopeRepoDistributionApi {
+ /** The deployed pull requests in scope. */
+ scope: DurationDistributionApi
+ /** Every deployed pull request in the repository. */
+ repo: DurationDistributionApi
+}
+
+export interface DeliveryLeadTimeApi {
+ /** Open to the first successful deploy containing the merge, over PRs deployed in the window. */
+ open_to_deploy: ScopeRepoDistributionApi
+ /** Open to merge over the same deployed PRs, so it composes with merge_to_deploy. Includes draft time. */
+ open_to_merge: ScopeRepoDistributionApi
+ /** Merge to deploy over the same deployed PRs. */
+ merge_to_deploy: ScopeRepoDistributionApi
+ /** False when the deployments and deployment statuses tables aren't synced. The distributions are then empty. */
+ deploy_data_available: boolean
+ /** The deploy environments lead time was scoped to: production by default. Empty when deploy data is not available. */
+ environment_scope: string
+ /** PRs in scope merged in the window (bots and drafts excluded). */
+ merged_pr_count: number
+ /** Of merged_pr_count, the PRs a successful in-scope deploy contains. The rest are still waiting for a deploy or fall outside the scan. */
+ deployed_merged_pr_count: number
+}
+
+/**
+ * * `author` - AUTHOR
+ * * `github_team` - GITHUB_TEAM
+ * * `pull_request` - PULL_REQUEST
+ */
+export type DeliveryScopeKindEnumApi = (typeof DeliveryScopeKindEnumApi)[keyof typeof DeliveryScopeKindEnumApi]
+
+export const DeliveryScopeKindEnumApi = {
+ Author: 'author',
+ GithubTeam: 'github_team',
+ PullRequest: 'pull_request',
+} as const
+
+export interface DeliverySummaryApi {
+ /** Median estimated CI cost per merged PR, in USD, over every run linked to the PR (merge-queue gate runs included) that started up to 30 days before the window. Null when the jobs table isn't synced. */
+ cost_per_merged_pr_usd: ScopeRepoFigureApi
+ /** Median billable runner minutes per merged PR, on the billed clock. Null when the jobs table isn't synced. */
+ billable_minutes_per_merged_pr: ScopeRepoFigureApi
+ /** Total CI cost divided by total pushes over the merged PRs: the price of one iteration. A push is a distinct head commit that triggered CI. */
+ cost_per_push_usd: ScopeRepoFigureApi
+ /** Median seconds from the last ready_for_review to merge. Null when issue events aren't synced. */
+ median_ready_to_merge_seconds: ScopeRepoFigureApi
+ /** 90th percentile of the ready-to-merge seconds. */
+ p90_ready_to_merge_seconds: ScopeRepoFigureApi
+ /** Median seconds from ready to the first approval. An approval given while the PR was a draft counts as 0. PRs merged without an approval are left out. Null when reviews aren't synced. */
+ median_ready_to_first_approval_seconds: ScopeRepoFigureApi
+ /** Median seconds from the first approval to merge. This median and the one before it do not add up to the ready-to-merge median. */
+ median_first_approval_to_merge_seconds: ScopeRepoFigureApi
+ /** Share (0 to 1) of all ready-to-merge hours spent before the first approval, summed over the PRs, so long PRs weigh more. The rest came after the approval. */
+ before_first_approval_share: ScopeRepoFigureApi
+ /** Mean pushes after the first approval per merged PR, over PRs with an approval. */
+ pushes_after_approval_per_merged_pr: ScopeRepoFigureApi
+ /** Mean merge-queue gate attempts per merged PR that went through the queue. A bisection probe folds into its attempt. */
+ merge_queue_attempts_per_merged_pr: ScopeRepoFigureApi
+ /** Share (0 to 1) of queue-landed merged PRs with at least one failed gate attempt. A failure caused by another PR ahead in the queue also counts, because the queue history is not in the warehouse. */
+ failed_merge_queue_share: ScopeRepoFigureApi
+ /** Lead time to deploy for the scope against the repository. */
+ lead_time: DeliveryLeadTimeApi
+ /** What the read covers: 'author' (one GitHub login), 'github_team' (the members of one GitHub team, through the team membership table), or 'pull_request' (one pull request).
+ *
+ * * `author` - AUTHOR
+ * * `github_team` - GITHUB_TEAM
+ * * `pull_request` - PULL_REQUEST */
+ scope_kind: DeliveryScopeKindEnumApi
+ /** The GitHub login or GitHub team slug the summary is for. */
+ scope: string
+ /** True when the team membership table is synced. A github_team scope without it matches no pull requests, so every scope figure is empty rather than the whole repository. */
+ has_membership_data: boolean
+ /** True when the workflow jobs table is synced, which cost needs. */
+ jobs_available: boolean
+ /** True when the reviews table is synced, which the approval split needs. */
+ review_data_available: boolean
+ /** True when issue events are synced, which ready-to-merge time needs. */
+ ready_data_available: boolean
+ /** PRs in scope opened in the window, drafts included, bots excluded. */
+ opened_pr_count: number
+ /** PRs in scope merged in the window (bots and drafts excluded): the population of every per-merged-PR figure. */
+ merged_pr_count: number
+ /** PRs in scope that are open and not drafts right now. Ignores the window. */
+ open_pr_count: number
+ /** PRs in scope that are open drafts right now. Ignores the window. */
+ draft_pr_count: number
+ /**
+ * Estimated CI cost summed over the merged PRs in scope. Null when nothing was costable.
+ * @nullable
+ */
+ total_cost_usd: number | null
+ /**
+ * Billable minutes summed over the merged PRs in scope. Null when the jobs table isn't synced.
+ * @nullable
+ */
+ total_billable_minutes: number | null
+ /** Pushes summed over the merged PRs in scope. */
+ push_count: number
+}
+
export interface DeploymentFrequencyBucketApi {
/** Bucket start, aligned to series_granularity (top of hour, midnight, or Monday). */
bucket_start: string
@@ -706,6 +864,129 @@ export interface WorkflowRunDetailApi {
commit_pr_number: number | null
}
+/**
+ * * `draft` - DRAFT
+ * * `waiting_for_review` - WAITING_FOR_REVIEW
+ * * `changes_requested` - CHANGES_REQUESTED
+ * * `approved_not_enqueued` - APPROVED_NOT_ENQUEUED
+ * * `review_state_unknown` - REVIEW_STATE_UNKNOWN
+ * * `ci_running` - CI_RUNNING
+ * * `red_passed_on_rerun` - RED_PASSED_ON_RERUN
+ * * `red_master_broken` - RED_MASTER_BROKEN
+ * * `red_fixed_by_push` - RED_FIXED_BY_PUSH
+ * * `red_not_provable` - RED_NOT_PROVABLE
+ * * `merge_queue` - MERGE_QUEUE
+ * * `out_of_merge_queue` - OUT_OF_MERGE_QUEUE
+ */
+export type PRTimelineSegmentKindEnumApi =
+ (typeof PRTimelineSegmentKindEnumApi)[keyof typeof PRTimelineSegmentKindEnumApi]
+
+export const PRTimelineSegmentKindEnumApi = {
+ Draft: 'draft',
+ WaitingForReview: 'waiting_for_review',
+ ChangesRequested: 'changes_requested',
+ ApprovedNotEnqueued: 'approved_not_enqueued',
+ ReviewStateUnknown: 'review_state_unknown',
+ CiRunning: 'ci_running',
+ RedPassedOnRerun: 'red_passed_on_rerun',
+ RedMasterBroken: 'red_master_broken',
+ RedFixedByPush: 'red_fixed_by_push',
+ RedNotProvable: 'red_not_provable',
+ MergeQueue: 'merge_queue',
+ OutOfMergeQueue: 'out_of_merge_queue',
+} as const
+
+export interface PRTimelineSegmentApi {
+ /** What the PR waited on: draft; waiting_for_review (no approval yet, or re-review after a push); changes_requested (no push since); approved_not_enqueued (approved, with no failing or running check); review_state_unknown (reviews not synced); ci_running; red_passed_on_rerun (the failed workflows passed a re-run of the same commit); red_master_broken (the failed jobs also failed on the default branch within 12 hours); red_fixed_by_push (a later commit arrived); red_not_provable; merge_queue (every queue state collapsed); out_of_merge_queue (open PR, Trunk says failed or cancelled).
+ *
+ * * `draft` - DRAFT
+ * * `waiting_for_review` - WAITING_FOR_REVIEW
+ * * `changes_requested` - CHANGES_REQUESTED
+ * * `approved_not_enqueued` - APPROVED_NOT_ENQUEUED
+ * * `review_state_unknown` - REVIEW_STATE_UNKNOWN
+ * * `ci_running` - CI_RUNNING
+ * * `red_passed_on_rerun` - RED_PASSED_ON_RERUN
+ * * `red_master_broken` - RED_MASTER_BROKEN
+ * * `red_fixed_by_push` - RED_FIXED_BY_PUSH
+ * * `red_not_provable` - RED_NOT_PROVABLE
+ * * `merge_queue` - MERGE_QUEUE
+ * * `out_of_merge_queue` - OUT_OF_MERGE_QUEUE */
+ kind: PRTimelineSegmentKindEnumApi
+ /** Segment start. */
+ started_at: string
+ /** Segment end: the next segment's start, the merge or close, or now. */
+ ended_at: string
+}
+
+export interface PRTimelineApi {
+ /** The repository the pull request belongs to. */
+ repo: RepoRefApi
+ /** Consecutive segments from started_at to the merge, the close, or now, with no gaps. */
+ segments: PRTimelineSegmentApi[]
+ /** Pull request number. */
+ number: number
+ /** Pull request title. */
+ title: string
+ /** The pull request's author. */
+ author: AuthorApi
+ /** open, merged, or closed. Author and team scopes list open and merged PRs only; a pull_request scope returns the PR whatever its state.
+ *
+ * * `open` - OPEN
+ * * `closed` - CLOSED
+ * * `merged` - MERGED */
+ state: EngineeringAnalyticsPRStateEnumApi
+ /** True when the PR is a draft right now. */
+ is_draft: boolean
+ /** When the PR was opened. */
+ created_at: string
+ /** Where the timeline starts: the last ready_for_review before the end, else created_at. A PR listed for an author or a team starts no earlier than 30 days before the window, because older CI is not read. */
+ started_at: string
+ /**
+ * Merge time; null when not merged.
+ * @nullable
+ */
+ merged_at: string | null
+ /** Distinct head commits that triggered CI, merge-queue gate runs excluded. */
+ pushes: number
+ /**
+ * Estimated CI cost over the PR's runs, in USD. Null when nothing was costable.
+ * @nullable
+ */
+ estimated_cost_usd: number | null
+ /**
+ * Billable minutes over the PR's runs. Null when the jobs table isn't synced.
+ * @nullable
+ */
+ billable_minutes: number | null
+}
+
+export interface PullRequestTimelinesApi {
+ /** The pull requests in scope, newest first: open PRs plus PRs merged in the window, or the one pull request of a pull_request scope. */
+ items: PRTimelineApi[]
+ /** What the read covers: 'author' (one GitHub login), 'github_team' (the members of one GitHub team, through the team membership table), or 'pull_request' (one pull request).
+ *
+ * * `author` - AUTHOR
+ * * `github_team` - GITHUB_TEAM
+ * * `pull_request` - PULL_REQUEST */
+ scope_kind: DeliveryScopeKindEnumApi
+ /** The GitHub login, GitHub team slug, or 'owner/name#number' the timelines are for. */
+ scope: string
+ /** True when the team membership table is synced. A github_team scope without it lists no pull requests. */
+ has_membership_data: boolean
+ /** False when reviews aren't synced: review stretches read review_state_unknown. */
+ review_data_available: boolean
+ /** False when workflow jobs aren't synced: a check a re-run turned green is not visible, and no red stretch reads red_master_broken. */
+ jobs_available: boolean
+ /** True when the Trunk merge-queue table is synced, so out_of_merge_queue can appear. */
+ merge_queue_state_available: boolean
+ /** The now every open PR's timeline ends at. */
+ generated_at: string
+ /** True when more PRs matched than the limit. */
+ truncated: boolean
+ /** The maximum number of PRs returned. */
+ limit: number
+}
+
export interface CIStatusRollupApi {
/** Distinct workflows run on the PR's head SHA. */
runs: number
@@ -1735,6 +2016,33 @@ export type EngineeringAnalyticsCurrentBranchHealthParams = {
source_id?: string
}
+export type EngineeringAnalyticsDeliverySummaryParams = {
+ /**
+ * GitHub login: scope the read to this author's pull requests. Pass exactly one scope.
+ */
+ 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
+ /**
+ * GitHub team slug: scope the read to pull requests authored by the team's members, through the team membership table. Pass exactly one scope.
+ */
+ github_team?: string
+ /**
+ * '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 EngineeringAnalyticsDoraParams = {
/**
* Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
@@ -1923,6 +2231,37 @@ export type EngineeringAnalyticsPrRunsParams = {
source_id?: string
}
+export type EngineeringAnalyticsPullRequestTimelinesParams = {
+ /**
+ * GitHub login: scope the read to this author's pull requests. Pass exactly one scope.
+ */
+ 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
+ /**
+ * GitHub team slug: scope the read to pull requests authored by the team's members, through the team membership table. Pass exactly one scope.
+ */
+ github_team?: string
+ /**
+ * Pull request number: scope the read to this one pull request. Needs repo. Pass exactly one scope.
+ */
+ 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 EngineeringAnalyticsPullRequestsParams = {
/**
* Optional GitHub login to scope the list to one author's pull requests.
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index 2115b6f9b9ed..91bf9808ec52 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -16,12 +16,14 @@ import type {
CISignalsConfigApi,
CISignalsConfigUpdateApi,
CurrentBranchHealthApi,
+ DeliverySummaryApi,
DoraOverviewApi,
EngineeringAnalyticsAuthorWorkflowCostsParams,
EngineeringAnalyticsBrokenTestsParams,
EngineeringAnalyticsCiCardsParams,
EngineeringAnalyticsCiFailureLogsParams,
EngineeringAnalyticsCurrentBranchHealthParams,
+ EngineeringAnalyticsDeliverySummaryParams,
EngineeringAnalyticsDoraParams,
EngineeringAnalyticsFlakyTestsParams,
EngineeringAnalyticsJobAggregatesParams,
@@ -29,6 +31,7 @@ import type {
EngineeringAnalyticsPrCostParams,
EngineeringAnalyticsPrLifecycleParams,
EngineeringAnalyticsPrRunsParams,
+ EngineeringAnalyticsPullRequestTimelinesParams,
EngineeringAnalyticsPullRequestsParams,
EngineeringAnalyticsQuarantineParams,
EngineeringAnalyticsRepoOverviewParams,
@@ -51,6 +54,7 @@ import type {
PRCostSummaryApi,
PRLifecycleApi,
PullRequestListApi,
+ PullRequestTimelinesApi,
QuarantineFileApi,
QuarantineRequestApi,
QuarantineRequestResultApi,
@@ -268,6 +272,39 @@ export const engineeringAnalyticsCurrentBranchHealth = async (
})
}
+export const getEngineeringAnalyticsDeliverySummaryUrl = (
+ projectId: string,
+ params?: EngineeringAnalyticsDeliverySummaryParams
+) => {
+ 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_summary/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/delivery_summary/`
+}
+
+/**
+ * Delivery and CI friction for one author or one GitHub team over a window (date_from default -30d), each figure next to the same figure over the whole repository: CI spend per merged PR, ready to merged split at the first approval, pushes after approval, merge-queue attempts, and lead time to deploy. Bots and drafts are excluded. Figures whose optional source isn't synced are null and flagged.
+ */
+export const engineeringAnalyticsDeliverySummary = async (
+ projectId: string,
+ params?: EngineeringAnalyticsDeliverySummaryParams,
+ options?: RequestInit
+): Promise<DeliverySummaryApi> => {
+ return apiMutator<DeliverySummaryApi>(getEngineeringAnalyticsDeliverySummaryUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEngineeringAnalyticsDoraUrl = (projectId: string, params?: EngineeringAnalyticsDoraParams) => {
const normalizedParams = new URLSearchParams()
@@ -499,6 +536,39 @@ export const engineeringAnalyticsPrRuns = async (
})
}
+export const getEngineeringAnalyticsPullRequestTimelinesUrl = (
+ projectId: string,
+ params?: EngineeringAnalyticsPullRequestTimelinesParams
+) => {
+ 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/pull_request_timelines/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/pull_request_timelines/`
+}
+
+/**
+ * Pull requests as timelines of what each waited on from ready for review to merge or now: review, CI, red checks by what turned them green, and the merge queue. Scope to one author or one GitHub team (open PRs plus PRs merged in the window, date_from default -30d), or to one pull request with pr_number and repo.
+ */
+export const engineeringAnalyticsPullRequestTimelines = async (
+ projectId: string,
+ params?: EngineeringAnalyticsPullRequestTimelinesParams,
+ options?: RequestInit
+): Promise<PullRequestTimelinesApi> => {
+ return apiMutator<PullRequestTimelinesApi>(getEngineeringAnalyticsPullRequestTimelinesUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEngineeringAnalyticsPullRequestsUrl = (
projectId: string,
params?: EngineeringAnalyticsPullRequestsParams
diff --git a/products/engineering_analytics/frontend/lib/deliveryScope.ts b/products/engineering_analytics/frontend/lib/deliveryScope.ts
new file mode 100644
index 000000000000..6e097ddba097
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/deliveryScope.ts
@@ -0,0 +1,39 @@
+// Which pull requests a delivery surface covers: one author's, one GitHub team's, or one pull request.
+// Mirrors the backend's DeliveryScope, so a page picks its scope once and every delivery logic and
+// request below it agrees on it.
+
+export type DeliveryScope =
+ | { kind: 'author'; author: string }
+ | { kind: 'github_team'; githubTeam: string }
+ | { kind: 'pull_request'; prNumber: number; repo: string }
+
+export interface DeliveryScopeParams {
+ author?: string
+ github_team?: string
+ pr_number?: number
+ repo?: string
+}
+
+/** The query params the delivery endpoints read the scope from. */
+export function deliveryScopeParams(scope: DeliveryScope): DeliveryScopeParams {
+ switch (scope.kind) {
+ case 'author':
+ return { author: scope.author }
+ case 'github_team':
+ return { github_team: scope.githubTeam }
+ case 'pull_request':
+ return { pr_number: scope.prNumber, repo: scope.repo }
+ }
+}
+
+/** A stable key for logics keyed by scope. */
+export function deliveryScopeKey(scope: DeliveryScope): string {
+ switch (scope.kind) {
+ case 'author':
+ return `author:${scope.author}`
+ case 'github_team':
+ return `team:${scope.githubTeam}`
+ case 'pull_request':
+ return `pr:${scope.repo}#${scope.prNumber}`
+ }
+}
diff --git a/products/engineering_analytics/frontend/lib/pullRequestDayView.test.ts b/products/engineering_analytics/frontend/lib/pullRequestDayView.test.ts
new file mode 100644
index 000000000000..6399af48669f
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/pullRequestDayView.test.ts
@@ -0,0 +1,102 @@
+import { PRTimelineApi, PRTimelineSegmentKindEnumApi as Kind } from '../generated/api.schemas'
+import { axisDays, groupTimelines, redTimeByCause } from './pullRequestDayView'
+
+const HOUR = 3600 * 1000
+const T0 = Date.parse('2026-07-01T10:00:00Z')
+
+function at(hours: number): string {
+ return new Date(T0 + hours * HOUR).toISOString()
+}
+
+function pr(
+ number: number,
+ segments: [Kind, number, number][],
+ options: { merged?: boolean; draft?: boolean } = {}
+): PRTimelineApi {
+ const last = segments[segments.length - 1]
+ return {
+ number,
+ title: `PR ${number}`,
+ author: { handle: 'alice', display_name: 'alice', avatar_url: '', is_bot: false },
+ repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },
+ state: options.merged ? 'merged' : 'open',
+ is_draft: !!options.draft,
+ created_at: at(segments[0][1]),
+ started_at: at(segments[0][1]),
+ merged_at: options.merged ? at(last[2]) : null,
+ pushes: 1,
+ estimated_cost_usd: null,
+ billable_minutes: null,
+ segments: segments.map(([kind, start, end]) => ({ kind, started_at: at(start), ended_at: at(end) })),
+ }
+}
+
+describe('pullRequestDayView', () => {
+ it('orders groups by what the author can act on first', () => {
+ const groups = groupTimelines([
+ pr(1, [
+ [Kind.CiRunning, 0, 1],
+ [Kind.MergeQueue, 1, 5],
+ ]),
+ pr(2, [
+ [Kind.WaitingForReview, 0, 2],
+ [Kind.OutOfMergeQueue, 2, 3],
+ ]),
+ pr(3, [[Kind.WaitingForReview, 0, 60]], { merged: true }),
+ pr(4, [
+ [Kind.CiRunning, 0, 1],
+ [Kind.ApprovedNotEnqueued, 1, 30],
+ ]),
+ pr(
+ 5,
+ [
+ [Kind.WaitingForReview, 0, 2],
+ [Kind.RedFixedByPush, 2, 3],
+ ],
+ { merged: true }
+ ),
+ pr(6, [[Kind.Draft, 0, 8]], { draft: true }),
+ ])
+
+ expect(groups.map((group) => [group.label, group.rows.map((row) => row.pr.number)])).toEqual([
+ ["Open, the author's move", [4, 2]],
+ ['Open, waiting on others', [1]],
+ ['Merged, took over 2 days', [3]],
+ ['Merged, under a day', [5]],
+ ['Open, still draft', [6]],
+ ])
+ // A merged row explains itself by the state that took longest, not the last one.
+ expect(groups[3].rows[0].highlightKind).toBe(Kind.WaitingForReview)
+ })
+
+ it.each([
+ ['one outlier does not stretch the axis', 'days', [5, 6, 7, 8, 9, 10, 11, 12, 13, 1000], [1, 2]],
+ ['weeks round up to a whole week', 'weeks', [5, 20, 30], [7, 7]],
+ ['long waits cap at two weeks', 'days', [400, 500, 600], [14, 14]],
+ ] as const)('%s', (_name, alignment, lengths, [atLeast, atMost]) => {
+ const items = lengths.map((length, index) => pr(index, [[Kind.CiRunning, 0, length]], { merged: true }))
+ const days = axisDays(items, alignment)
+ // The row origin follows the runner's time zone, so the fitted day count can shift by one.
+ expect(days).toBeGreaterThanOrEqual(atLeast)
+ expect(days).toBeLessThanOrEqual(atMost)
+ })
+
+ it('averages red time by cause over merged pull requests only', () => {
+ const red = redTimeByCause([
+ pr(
+ 1,
+ [
+ [Kind.CiRunning, 0, 1],
+ [Kind.RedPassedOnRerun, 1, 3],
+ ],
+ { merged: true }
+ ),
+ pr(2, [[Kind.WaitingForReview, 0, 4]], { merged: true }),
+ pr(3, [[Kind.RedNotProvable, 0, 50]]),
+ ])
+
+ expect(red.mergedCount).toBe(2)
+ expect(red.totalSecondsPerMergedPr).toBe(3600)
+ expect(red.secondsPerMergedPr.find((entry) => entry.kind === Kind.RedPassedOnRerun)?.seconds).toBe(3600)
+ })
+})
diff --git a/products/engineering_analytics/frontend/lib/pullRequestDayView.ts b/products/engineering_analytics/frontend/lib/pullRequestDayView.ts
new file mode 100644
index 000000000000..fed70905ebee
--- /dev/null
+++ b/products/engineering_analytics/frontend/lib/pullRequestDayView.ts
@@ -0,0 +1,303 @@
+// The author page's day view: every pull request on a shared clock, grouped by what is most useful
+// to look at first. Pure functions, so the grouping and the axis fit are testable without a render.
+
+import type { CSSProperties } from 'react'
+
+import { Dayjs, dayjs } from 'lib/dayjs'
+
+import { PRTimelineApi, PRTimelineSegmentKindEnumApi as Kind } from '../generated/api.schemas'
+
+export type DayViewAlignment = 'days' | 'weeks'
+
+/** The longest axis the day view draws; longer bars end in a clip marker. */
+export const MAX_AXIS_DAYS = 14
+/** Rows start at this local hour, so a working day reads left to right without a split night. */
+export const DAY_START_HOUR = 6
+/** Night band, in hours after the row origin: 22:00 to 06:00. */
+export const NIGHT_START_OFFSET_HOURS = 16
+
+const HOUR_SECONDS = 3600
+const DAY_HOURS = 24
+
+export interface SegmentKindStyle {
+ label: string
+ short: string
+ color: string
+ pattern?: 'stripes' | 'dots' | 'dashes'
+}
+
+export const SEGMENT_KIND_STYLES: Record<Kind, SegmentKindStyle> = {
+ [Kind.WaitingForReview]: {
+ label: 'Waiting for approval',
+ short: 'review wait',
+ color: 'var(--data-color-3)',
+ },
+ [Kind.ChangesRequested]: {
+ label: 'Changes requested, no push yet',
+ short: 'changes requested',
+ color: 'var(--data-color-1)',
+ },
+ [Kind.ApprovedNotEnqueued]: {
+ label: 'Approved, nothing failing or running, not in the merge queue',
+ short: 'approved, not enqueued',
+ color: 'var(--data-color-1)',
+ pattern: 'stripes',
+ },
+ [Kind.RedFixedByPush]: {
+ label: 'Red until the next push',
+ short: 'red, fixed by a push',
+ color: 'var(--data-color-1)',
+ pattern: 'dots',
+ },
+ [Kind.CiRunning]: { label: 'CI running', short: 'CI running', color: 'var(--data-color-12)' },
+ [Kind.MergeQueue]: {
+ label: 'In the merge queue, restarts included',
+ short: 'merge queue',
+ color: 'var(--data-color-10)',
+ },
+ [Kind.OutOfMergeQueue]: {
+ label: 'Out of the merge queue, not added back',
+ short: 'out of the queue',
+ color: 'var(--data-color-10)',
+ pattern: 'stripes',
+ },
+ [Kind.RedPassedOnRerun]: {
+ label: 'Red, passed on a re-run of the same commit',
+ short: 'red, flake',
+ color: 'var(--data-color-13)',
+ },
+ [Kind.RedMasterBroken]: {
+ label: 'Red, the same job was failing on the default branch',
+ short: 'red, master broken',
+ color: 'var(--data-color-2)',
+ },
+ [Kind.RedNotProvable]: {
+ label: 'Red, cause not provable',
+ short: 'red, cause unknown',
+ color: 'var(--muted)',
+ pattern: 'dots',
+ },
+ [Kind.ReviewStateUnknown]: {
+ label: 'Review state unknown, reviews are not synced',
+ short: 'review state unknown',
+ color: 'var(--muted)',
+ pattern: 'stripes',
+ },
+ [Kind.Draft]: {
+ label: 'Draft, not ready for review yet',
+ short: 'draft',
+ color: 'var(--muted)',
+ pattern: 'dashes',
+ },
+}
+
+/** The fill for a segment kind. Patterns separate kinds that share a color, so the author's own states
+ * and the grey "unknown" states stay apart without extra hues. */
+export function segmentBackground(kind: Kind): CSSProperties {
+ const { color, pattern } = SEGMENT_KIND_STYLES[kind]
+ switch (pattern) {
+ case 'stripes':
+ return {
+ backgroundColor: color,
+ backgroundImage: 'repeating-linear-gradient(135deg, rgb(255 255 255 / 45%) 0 2px, transparent 2px 5px)',
+ }
+ case 'dots':
+ return {
+ backgroundColor: color,
+ backgroundImage: 'radial-gradient(rgb(0 0 0 / 35%) 1px, transparent 1.2px)',
+ backgroundSize: '4px 4px',
+ }
+ case 'dashes':
+ return { backgroundImage: `repeating-linear-gradient(90deg, ${color} 0 4px, transparent 4px 7px)` }
+ default:
+ return { backgroundColor: color }
+ }
+}
+
+/** Legend order: who can move the pull request out of each state. */
+export const SEGMENT_LEGEND_GROUPS: { label: string; kinds: Kind[] }[] = [
+ { label: 'Reviewers', kinds: [Kind.WaitingForReview] },
+ { label: 'Author', kinds: [Kind.ChangesRequested, Kind.ApprovedNotEnqueued, Kind.RedFixedByPush] },
+ {
+ label: 'CI and merge queue',
+ kinds: [Kind.CiRunning, Kind.MergeQueue, Kind.OutOfMergeQueue, Kind.RedPassedOnRerun, Kind.RedMasterBroken],
+ },
+ { label: 'Other', kinds: [Kind.RedNotProvable, Kind.ReviewStateUnknown, Kind.Draft] },
+]
+
+/** Current states an open pull request's author can clear without waiting on anyone else. */
+const AUTHOR_CAN_CLEAR: ReadonlySet<Kind> = new Set([
+ Kind.OutOfMergeQueue,
+ Kind.ApprovedNotEnqueued,
+ Kind.ChangesRequested,
+ Kind.RedFixedByPush,
+ Kind.RedPassedOnRerun,
+ Kind.RedNotProvable,
+])
+
+// Without synced reviews nobody is known to be blocking the PR, so it gets its own group.
+const UNKNOWN_OWNER: ReadonlySet<Kind> = new Set([Kind.ReviewStateUnknown])
+
+export const RED_KINDS: Kind[] = [Kind.RedFixedByPush, Kind.RedPassedOnRerun, Kind.RedMasterBroken, Kind.RedNotProvable]
+
+export interface DayViewRow {
+ pr: PRTimelineApi
+ isOpen: boolean
+ /** Ready to merged, or ready to now for an open pull request. */
+ lengthSeconds: number
+ /** The last segment for an open pull request, the longest state for a merged one. */
+ highlightKind: Kind
+ highlightSeconds: number
+}
+
+export interface DayViewGroup {
+ key: string
+ label: string
+ rows: DayViewRow[]
+}
+
+function secondsBetween(start: string, end: string): number {
+ return dayjs(end).diff(dayjs(start), 'second')
+}
+
+function toRow(pr: PRTimelineApi): DayViewRow | null {
+ const segments = pr.segments
+ if (segments.length === 0) {
+ return null
+ }
+ const isOpen = pr.state === 'open'
+ const last = segments[segments.length - 1]
+ let highlightKind = last.kind
+ let highlightSeconds = secondsBetween(last.started_at, last.ended_at)
+ if (!isOpen) {
+ const totals = new Map<Kind, number>()
+ for (const segment of segments) {
+ totals.set(
+ segment.kind,
+ (totals.get(segment.kind) ?? 0) + secondsBetween(segment.started_at, segment.ended_at)
+ )
+ }
+ ;[highlightKind, highlightSeconds] = [...totals.entries()].reduce((best, entry) =>
+ entry[1] > best[1] ? entry : best
+ )
+ }
+ return {
+ pr,
+ isOpen,
+ lengthSeconds: secondsBetween(segments[0].started_at, last.ended_at),
+ highlightKind,
+ highlightSeconds,
+ }
+}
+
+const byHighlightDesc = (a: DayViewRow, b: DayViewRow): number => b.highlightSeconds - a.highlightSeconds
+const byLengthDesc = (a: DayViewRow, b: DayViewRow): number => b.lengthSeconds - a.lengthSeconds
+
+/** Most useful first: open work the author can move now, open work waiting on others, merged work
+ * from the longest wait down, then drafts. Empty groups are dropped; nothing else is hidden. */
+export function groupTimelines(items: PRTimelineApi[]): DayViewGroup[] {
+ const rows = items.map(toRow).filter((row): row is DayViewRow => row !== null)
+ const openReady = rows.filter((row) => row.isOpen && !row.pr.is_draft)
+ const merged = rows.filter((row) => row.pr.merged_at != null)
+ const day = DAY_HOURS * HOUR_SECONDS
+ const groups: DayViewGroup[] = [
+ {
+ key: 'open-author',
+ label: "Open, the author's move",
+ rows: openReady.filter((row) => AUTHOR_CAN_CLEAR.has(row.highlightKind)).sort(byHighlightDesc),
+ },
+ {
+ key: 'open-others',
+ label: 'Open, waiting on others',
+ rows: openReady
+ .filter((row) => !AUTHOR_CAN_CLEAR.has(row.highlightKind) && !UNKNOWN_OWNER.has(row.highlightKind))
+ .sort(byHighlightDesc),
+ },
+ {
+ key: 'open-unknown',
+ label: 'Open, review state unknown',
+ rows: openReady.filter((row) => UNKNOWN_OWNER.has(row.highlightKind)).sort(byHighlightDesc),
+ },
+ {
+ key: 'merged-long',
+ label: 'Merged, took over 2 days',
+ rows: merged.filter((row) => row.lengthSeconds > 2 * day).sort(byLengthDesc),
+ },
+ {
+ key: 'merged-medium',
+ label: 'Merged, 1 to 2 days',
+ rows: merged.filter((row) => row.lengthSeconds > day && row.lengthSeconds <= 2 * day).sort(byLengthDesc),
+ },
+ {
+ key: 'merged-short',
+ label: 'Merged, under a day',
+ rows: merged.filter((row) => row.lengthSeconds <= day).sort(byLengthDesc),
+ },
+ {
+ key: 'drafts',
+ label: 'Open, still draft',
+ rows: rows.filter((row) => row.isOpen && row.pr.is_draft).sort(byLengthDesc),
+ },
+ ]
+ return groups.filter((group) => group.rows.length > 0)
+}
+
+/** Where a row's clock starts: 06:00 local on the day it went ready (the day before when it went
+ * ready in the small hours), or Monday 06:00 of that week so weekdays line up across rows. */
+export function rowOrigin(startedAt: string, alignment: DayViewAlignment): Dayjs {
+ const shifted = dayjs(startedAt).subtract(DAY_START_HOUR, 'hour')
+ const dayStart = shifted.startOf('day')
+ const origin = alignment === 'weeks' ? dayStart.subtract((dayStart.day() + 6) % 7, 'day') : dayStart
+ return origin.add(DAY_START_HOUR, 'hour')
+}
+
+export function hoursFromOrigin(origin: Dayjs, at: string): number {
+ return dayjs(at).diff(origin, 'second') / HOUR_SECONDS
+}
+
+/** Days the axis spans: it fits 90% of the rows' ends, so the bulk fills the width. Capped at
+ * MAX_AXIS_DAYS; the weeks alignment rounds up to whole weeks. */
+export function axisDays(items: PRTimelineApi[], alignment: DayViewAlignment): number {
+ const ends = items
+ .filter((pr) => pr.segments.length > 0)
+ .map((pr) => hoursFromOrigin(rowOrigin(pr.started_at, alignment), pr.segments[pr.segments.length - 1].ended_at))
+ .sort((a, b) => a - b)
+ if (ends.length === 0) {
+ return 1
+ }
+ const p90 = ends[Math.floor(0.9 * (ends.length - 1))]
+ const days = Math.min(MAX_AXIS_DAYS, Math.max(1, Math.ceil(p90 / DAY_HOURS)))
+ return alignment === 'weeks' ? Math.min(MAX_AXIS_DAYS, Math.ceil(days / 7) * 7) : days
+}
+
+export interface RedTimeByCause {
+ mergedCount: number
+ /** Red seconds per merged pull request, per cause, in RED_KINDS order. */
+ secondsPerMergedPr: { kind: Kind; seconds: number }[]
+ totalSecondsPerMergedPr: number
+}
+
+/** Red time on the merged pull requests, split by what turned the check green. */
+export function redTimeByCause(items: PRTimelineApi[]): RedTimeByCause {
+ const merged = items.filter((pr) => pr.merged_at != null)
+ const totals = new Map<Kind, number>(RED_KINDS.map((kind) => [kind, 0]))
+ for (const pr of merged) {
+ for (const segment of pr.segments) {
+ if (totals.has(segment.kind)) {
+ totals.set(
+ segment.kind,
+ (totals.get(segment.kind) ?? 0) + secondsBetween(segment.started_at, segment.ended_at)
+ )
+ }
+ }
+ }
+ const perPr = RED_KINDS.map((kind) => ({
+ kind,
+ seconds: merged.length ? (totals.get(kind) ?? 0) / merged.length : 0,
+ }))
+ return {
+ mergedCount: merged.length,
+ secondsPerMergedPr: perPr,
+ totalSecondsPerMergedPr: perPr.reduce((sum, entry) => sum + entry.seconds, 0),
+ }
+}
diff --git a/products/engineering_analytics/frontend/scenes/DeliverySections.tsx b/products/engineering_analytics/frontend/scenes/DeliverySections.tsx
new file mode 100644
index 000000000000..402635edb248
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/DeliverySections.tsx
@@ -0,0 +1,178 @@
+// The delivery sections for one scope, meant to sit inside a page's ScopePanel: CI spend, getting merged,
+// lead time to deploy, and the pull requests day view, each figure against the repository. The author
+// page renders them for one author; a team page renders the same sections for one GitHub team.
+
+import { useActions, useValues } from 'kea'
+
+import { pluralize } from 'lib/utils/strings'
+
+import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'
+import { LeadTimeComparisonCard } from '../components/LeadTimeComparisonCard'
+import { PullRequestCountsCard } from '../components/PullRequestCountsCard'
+import { PullRequestDayView } from '../components/PullRequestDayView'
+import { ReadyToMergeCard } from '../components/ReadyToMergeCard'
+import { RedTimeByCauseCard } from '../components/RedTimeByCauseCard'
+import { ScopeComparisonCard } from '../components/ScopeComparisonCard'
+import { Section } from '../components/Section'
+import { DeliveryScope } from '../lib/deliveryScope'
+import { compactMinutes, compactUsd, percent } from '../lib/format'
+import { deliverySummaryLogic } from './deliverySummaryLogic'
+import { pullRequestTimelinesLogic } from './pullRequestTimelinesLogic'
+
+const formatRatio = (value: number): string => value.toFixed(1)
+
+export function DeliverySections({
+ scope,
+ scopeLabel,
+ sourceId,
+}: {
+ /** An author or a GitHub team; the summary endpoint rejects a single pull request. */
+ scope: DeliveryScope
+ /** The row label for the scope's bars, e.g. "This author" or "This team". */
+ scopeLabel: string
+ sourceId: string | null
+}): JSX.Element {
+ const summaryLogic = deliverySummaryLogic({ scope, sourceId })
+ const timelinesLogic = pullRequestTimelinesLogic({ scope, sourceId })
+ const { summary, summaryLoading, summaryFailed } = useValues(summaryLogic)
+ const { loadSummary } = useActions(summaryLogic)
+ const { timelines, timelinesLoading, timelinesFailed, dayViewAlignment, dayViewGroups, dayViewAxisDays, redTime } =
+ useValues(timelinesLogic)
+ const { loadTimelines, setDayViewAlignment } = useActions(timelinesLogic)
+
+ if (summaryFailed || timelinesFailed) {
+ return (
+ <CIAnalyticsLoadError
+ onRetry={() => {
+ loadSummary()
+ loadTimelines()
+ }}
+ />
+ )
+ }
+
+ const summaryPending = summaryLoading && !summary
+ const noMembers = summary?.scope_kind === 'github_team' && !summary.has_membership_data
+ const noMerges = noMembers
+ ? 'Team figures appear once the team members table on this GitHub source is synced.'
+ : 'Nothing merged in the window.'
+ const costEmpty =
+ summary && !summary.jobs_available
+ ? 'Cost appears once the workflow jobs table on this GitHub source is synced.'
+ : noMerges
+ const reviewsEmpty =
+ summary && !summary.review_data_available
+ ? 'Sync the reviews table on this GitHub source to see pushes after the first approval.'
+ : 'No approved pull requests merged in the window.'
+
+ return (
+ <>
+ <Section id="delivery-spend" title="CI spend">
+ <div className="@container">
+ <div className="grid grid-cols-1 gap-2 @min-[36rem]:grid-cols-2 @min-[64rem]:grid-cols-4">
+ <PullRequestCountsCard summary={summary} loading={summaryPending} />
+ <ScopeComparisonCard
+ title="CI cost per merged PR"
+ tooltip="Median estimated CI cost of a merged pull request: every run linked to it, merge queue runs included, from up to 30 days before the window. Repo: the same median over every pull request merged in the repository, bots excluded."
+ scopeLabel={scopeLabel}
+ figure={summary?.cost_per_merged_pr_usd}
+ formatValue={compactUsd}
+ caption={
+ summary?.total_cost_usd != null
+ ? `${compactUsd(summary.total_cost_usd)} in total`
+ : undefined
+ }
+ loading={summaryPending}
+ emptyText={costEmpty}
+ />
+ <ScopeComparisonCard
+ title="Billable minutes per merged PR"
+ tooltip="Median billed runner minutes of a merged pull request, on the billed clock (machine boot left out). Re-run copies that never ran again are not counted."
+ scopeLabel={scopeLabel}
+ figure={summary?.billable_minutes_per_merged_pr}
+ formatValue={compactMinutes}
+ caption={
+ summary?.total_billable_minutes != null
+ ? `${compactMinutes(summary.total_billable_minutes)} billable in total`
+ : undefined
+ }
+ loading={summaryPending}
+ emptyText={costEmpty}
+ />
+ <ScopeComparisonCard
+ title="Cost per push"
+ tooltip="CI cost divided by pushes. A push is a new commit and the CI it started: the price of one iteration, so a high figure points at heavy workflows rather than many pushes."
+ scopeLabel={scopeLabel}
+ figure={summary?.cost_per_push_usd}
+ formatValue={compactUsd}
+ caption={summary ? pluralize(summary.push_count, 'push', 'pushes') : undefined}
+ loading={summaryPending}
+ emptyText={costEmpty}
+ />
+ </div>
+ </div>
+ </Section>
+
+ <Section id="delivery-merge" title="Getting merged">
+ <div className="@container">
+ <div className="grid grid-cols-1 gap-2 @min-[36rem]:grid-cols-2 @min-[64rem]:grid-cols-4">
+ <div className="@min-[36rem]:col-span-2">
+ <ReadyToMergeCard summary={summary} scopeLabel={scopeLabel} loading={summaryPending} />
+ </div>
+ <ScopeComparisonCard
+ title="Pushes after approval"
+ tooltip="Average new commits pushed after the first approval, per merged pull request that had an approval."
+ scopeLabel={scopeLabel}
+ figure={summary?.pushes_after_approval_per_merged_pr}
+ formatValue={formatRatio}
+ loading={summaryPending}
+ emptyText={reviewsEmpty}
+ />
+ <ScopeComparisonCard
+ title="Merge queue attempts"
+ tooltip="Average merge queue attempts per merged pull request that went through the queue. 1.0 means every pull request landed on its first try. A failed attempt also counts when another pull request ahead in the queue broke it: the queue's history isn't in the warehouse, so the two can't be told apart."
+ scopeLabel={scopeLabel}
+ figure={summary?.merge_queue_attempts_per_merged_pr}
+ formatValue={formatRatio}
+ caption={
+ summary?.failed_merge_queue_share.scope != null
+ ? `${percent(summary.failed_merge_queue_share.scope)} had a failed attempt · repo ${percent(summary.failed_merge_queue_share.repo)}`
+ : undefined
+ }
+ loading={summaryPending}
+ emptyText="No merged pull requests went through the merge queue in the window."
+ />
+ </div>
+ </div>
+ </Section>
+
+ <Section id="delivery-lead-time" title="Lead time to deploy">
+ <LeadTimeComparisonCard
+ leadTime={summary?.lead_time}
+ scopeLabel={scopeLabel}
+ loading={summaryPending}
+ />
+ </Section>
+
+ <Section id="delivery-pull-requests" title="Pull requests">
+ <div className="flex flex-col gap-2">
+ <RedTimeByCauseCard
+ redTime={redTime}
+ loading={timelinesLoading && !timelines}
+ jobsAvailable={!!timelines?.jobs_available}
+ />
+ <PullRequestDayView
+ timelines={timelines}
+ groups={dayViewGroups}
+ days={dayViewAxisDays}
+ alignment={dayViewAlignment}
+ onAlignmentChange={setDayViewAlignment}
+ loading={timelinesLoading}
+ sourceId={sourceId}
+ showAuthor={scope.kind === 'github_team'}
+ />
+ </div>
+ </Section>
+ </>
+ )
+}
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.stories.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.stories.tsx
new file mode 100644
index 000000000000..25ac8e754954
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.stories.tsx
@@ -0,0 +1,261 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { App } from 'scenes/App'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import type {
+ DeliverySummaryApi,
+ DurationDistributionApi,
+ PRTimelineApi,
+ PullRequestTimelinesApi,
+ WorkflowCostApi,
+} from '../generated/api.schemas'
+
+const HOUR = 3600
+
+function distribution(p50Hours: number, count: number): DurationDistributionApi {
+ return {
+ pr_count: count,
+ min_seconds: 0.2 * p50Hours * HOUR,
+ p05_seconds: 0.3 * p50Hours * HOUR,
+ p25_seconds: 0.6 * p50Hours * HOUR,
+ p50_seconds: p50Hours * HOUR,
+ mean_seconds: 1.8 * p50Hours * HOUR,
+ p75_seconds: 2.2 * p50Hours * HOUR,
+ p95_seconds: 6 * p50Hours * HOUR,
+ max_seconds: 9 * p50Hours * HOUR,
+ }
+}
+
+const SUMMARY: DeliverySummaryApi = {
+ scope_kind: 'author',
+ scope: 'jane-dev',
+ has_membership_data: false,
+ jobs_available: true,
+ review_data_available: true,
+ ready_data_available: true,
+ opened_pr_count: 24,
+ merged_pr_count: 21,
+ open_pr_count: 3,
+ draft_pr_count: 1,
+ cost_per_merged_pr_usd: { scope: 9.4, repo: 6.1 },
+ billable_minutes_per_merged_pr: { scope: 118, repo: 84 },
+ cost_per_push_usd: { scope: 1.35, repo: 1.2 },
+ total_cost_usd: 231.8,
+ total_billable_minutes: 2940,
+ push_count: 172,
+ median_ready_to_merge_seconds: { scope: 18 * HOUR, repo: 9 * HOUR },
+ p90_ready_to_merge_seconds: { scope: 4.1 * 24 * HOUR, repo: 3.2 * 24 * HOUR },
+ median_ready_to_first_approval_seconds: { scope: 2.1 * HOUR, repo: 2.6 * HOUR },
+ median_first_approval_to_merge_seconds: { scope: 11 * HOUR, repo: 3.4 * HOUR },
+ before_first_approval_share: { scope: 0.38, repo: 0.52 },
+ pushes_after_approval_per_merged_pr: { scope: 1.6, repo: 0.9 },
+ merge_queue_attempts_per_merged_pr: { scope: 1.4, repo: 1.3 },
+ failed_merge_queue_share: { scope: 0.24, repo: 0.21 },
+ lead_time: {
+ deploy_data_available: true,
+ environment_scope: 'prod-us, prod-eu',
+ merged_pr_count: 21,
+ deployed_merged_pr_count: 19,
+ open_to_deploy: { scope: distribution(21, 19), repo: distribution(12, 640) },
+ open_to_merge: { scope: distribution(20, 19), repo: distribution(10, 640) },
+ merge_to_deploy: { scope: distribution(1.1, 19), repo: distribution(1.1, 640) },
+ },
+}
+
+const NOW = '2026-07-02T12:00:00Z'
+
+function timeline(
+ number: number,
+ title: string,
+ startedAt: string,
+ steps: [PRTimelineApi['segments'][number]['kind'], number][],
+ options: { merged?: boolean; draft?: boolean } = {}
+): PRTimelineApi {
+ let cursor = Date.parse(startedAt)
+ const segments = steps.map(([kind, hours]) => {
+ const start = cursor
+ cursor += hours * HOUR * 1000
+ return { kind, started_at: new Date(start).toISOString(), ended_at: new Date(cursor).toISOString() }
+ })
+ const end = new Date(cursor).toISOString()
+ return {
+ number,
+ title,
+ author: { handle: 'jane-dev', display_name: 'jane-dev', avatar_url: '', is_bot: false },
+ repo: { provider: 'github', owner: 'PostHog', name: 'posthog' },
+ state: options.merged ? 'merged' : 'open',
+ is_draft: !!options.draft,
+ created_at: startedAt,
+ started_at: startedAt,
+ merged_at: options.merged ? end : null,
+ pushes: steps.filter(([kind]) => kind === 'ci_running').length,
+ estimated_cost_usd: 4.2 * number,
+ billable_minutes: 40 * number,
+ segments,
+ }
+}
+
+// Open rows run exactly to NOW, so their last step length is the gap from the running total to NOW.
+const TIMELINES: PullRequestTimelinesApi = {
+ scope_kind: 'author',
+ scope: 'jane-dev',
+ has_membership_data: false,
+ review_data_available: true,
+ jobs_available: true,
+ merge_queue_state_available: true,
+ generated_at: NOW,
+ truncated: false,
+ limit: 200,
+ items: [
+ timeline(4101, 'feat(insights): stream breakdown legends into the composer', '2026-06-29T14:40:00Z', [
+ ['waiting_for_review', 17.5],
+ ['changes_requested', 3],
+ ['ci_running', 0.6],
+ ['red_fixed_by_push', 1.2],
+ ['ci_running', 0.5],
+ ['approved_not_enqueued', 0.9],
+ ['merge_queue', 0.8],
+ ['out_of_merge_queue', 44.83],
+ ]),
+ timeline(4102, 'fix(tasks): keep sandbox logs after a resume', '2026-07-01T09:05:00Z', [
+ ['ci_running', 0.4],
+ ['red_passed_on_rerun', 2.1],
+ ['ci_running', 0.5],
+ ['waiting_for_review', 23.9],
+ ]),
+ timeline(4103, 'chore(signals): drop the unused research prompt', '2026-07-02T09:10:00Z', [
+ ['ci_running', 0.5],
+ ['red_master_broken', 2.33],
+ ]),
+ timeline(
+ 4090,
+ 'feat(cohorts): cache static cohort sizes',
+ '2026-06-22T08:00:00Z',
+ [
+ ['ci_running', 0.5],
+ ['waiting_for_review', 26],
+ ['changes_requested', 20],
+ ['ci_running', 0.6],
+ ['red_not_provable', 5],
+ ['ci_running', 0.5],
+ ['approved_not_enqueued', 2],
+ ['merge_queue', 1.2],
+ ],
+ { merged: true }
+ ),
+ timeline(
+ 4094,
+ 'fix(cohorts): handle an empty cohort in the query builder',
+ '2026-06-25T10:30:00Z',
+ [
+ ['ci_running', 0.5],
+ ['waiting_for_review', 15],
+ ['approved_not_enqueued', 1],
+ ['merge_queue', 0.9],
+ ],
+ { merged: true }
+ ),
+ timeline(
+ 4097,
+ 'chore(ci): bump the runner image',
+ '2026-06-30T07:15:00Z',
+ [
+ ['ci_running', 0.4],
+ ['waiting_for_review', 1.5],
+ ['merge_queue', 0.6],
+ ],
+ { merged: true }
+ ),
+ timeline(4105, 'feat(signals): let scouts reuse research', '2026-06-30T10:00:00Z', [['draft', 50]], {
+ draft: true,
+ }),
+ ],
+}
+
+const WORKFLOW_COSTS: WorkflowCostApi[] = [
+ {
+ workflow_name: 'Backend CI',
+ billable_minutes: 1720,
+ estimated_cost_usd: 131.2,
+ costed_jobs: 820,
+ unsettled_jobs: 0,
+ excluded_jobs: 12,
+ },
+ {
+ workflow_name: 'Frontend CI',
+ billable_minutes: 640,
+ estimated_cost_usd: 58.4,
+ costed_jobs: 310,
+ unsettled_jobs: 0,
+ excluded_jobs: 4,
+ },
+ {
+ workflow_name: 'E2E - Playwright',
+ billable_minutes: 580,
+ estimated_cost_usd: 42.2,
+ costed_jobs: 96,
+ unsettled_jobs: 1,
+ excluded_jobs: 0,
+ },
+]
+
+const meta: Meta = {
+ component: App,
+ title: 'Scenes-App/Engineering Analytics/Author',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2026-07-02',
+ featureFlags: [FEATURE_FLAGS.ENGINEERING_ANALYTICS],
+ pageUrl: urls.engineeringAnalyticsAuthor('jane-dev'),
+ testOptions: {
+ waitForSelector: '[data-attr="engineering-analytics-day-view"]',
+ },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ 'api/projects/:team_id/engineering_analytics/delivery_summary/': SUMMARY,
+ 'api/projects/:team_id/engineering_analytics/pull_request_timelines/': TIMELINES,
+ 'api/projects/:team_id/engineering_analytics/author_workflow_costs/': WORKFLOW_COSTS,
+ },
+ }),
+ ],
+}
+export default meta
+
+type Story = StoryObj<typeof meta>
+
+export const Author: Story = {
+ render: () => <App />,
+}
+
+// A docked side panel leaves the scene about 520px wide: the cards stack and the day view drops its
+// explanation column.
+export const AuthorNarrow: Story = {
+ render: () => <App />,
+ parameters: { testOptions: { viewport: { width: 900, height: 1800 } } },
+}
+
+export const AuthorWithoutReviewsOrDeploys: Story = {
+ render: () => <App />,
+ decorators: [
+ mswDecorator({
+ get: {
+ 'api/projects/:team_id/engineering_analytics/delivery_summary/': {
+ ...SUMMARY,
+ review_data_available: false,
+ lead_time: { ...SUMMARY.lead_time, deploy_data_available: false, environment_scope: '' },
+ },
+ 'api/projects/:team_id/engineering_analytics/pull_request_timelines/': {
+ ...TIMELINES,
+ review_data_available: false,
+ },
+ },
+ }),
+ ],
+}
diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx
index 0e3bbd66a11a..68214c19e4de 100644
--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsAuthorScene.tsx
@@ -15,19 +15,18 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { EntityHeader, VerdictPill } from '../components/EntityHeader'
-import { MetricTile } from '../components/MetricTile'
-import { PullRequestTable } from '../components/PullRequestTable'
import { formatCost, formatMinutes } from '../components/runTables'
import { RepoScopeChip, ScopeBar } from '../components/ScopeBar'
+import { ScopePanel } from '../components/ScopePanel'
import { Section } from '../components/Section'
import { ShareRow } from '../components/ShareRow'
import { AuthorLogicProps, authorLogic } from './authorLogic'
+import { DeliverySections } from './DeliverySections'
+import { deliverySummaryLogic } from './deliverySummaryLogic'
import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
+import { pullRequestTimelinesLogic } from './pullRequestTimelinesLogic'
-// date_from only (the list floors on it); "all time" / week+month snaps and Custom are out. Every option
-// here stays within the list's 365d load window (max preset is 180d / YTD), so the client-side cost tiles
-// are always a subset of the loaded PRs — a Custom range could reach past the load and desync the tiles
-// from the server-windowed workflow breakdown.
+// Relative presets only: the backend caps a window at a year, and every preset here stays inside it.
const AUTHOR_DATE_OPTIONS = dateMapping.filter(({ key }) =>
['Last 7 days', 'Last 14 days', 'Last 30 days', 'Last 90 days', 'Last 180 days', 'This year'].includes(key)
)
@@ -42,32 +41,21 @@ export const scene: SceneExport<AuthorLogicProps> = {
}
export function EngineeringAnalyticsAuthorScene(): JSX.Element {
- const {
- handle,
- prs,
- prsLoading,
- windowedRows,
- totalCostUsd,
- totalBillableMinutes,
- totalLoops,
- openPrCount,
- workflowCosts,
- workflowCostsLoading,
- sourceId,
- } = useValues(authorLogic)
+ const { handle, sourceId, deliveryScope, workflowCosts, workflowCostsLoading } = useValues(authorLogic)
+ const { summary, summaryLoading } = useValues(deliverySummaryLogic({ scope: deliveryScope, sourceId }))
+ const { timelines, timelinesLoading, repoSlugs } = useValues(
+ pullRequestTimelinesLogic({ scope: deliveryScope, sourceId })
+ )
const { dateFrom, dateTo } = useValues(engineeringAnalyticsFiltersLogic)
const { setDateRange } = useActions(engineeringAnalyticsFiltersLogic)
const hubUrl = combineUrl(urls.engineeringAnalytics(), sourceId ? { source: sourceId } : {}).url
- const avatarUrl = prs[0]?.authorAvatarUrl
- const costPerLoop = totalCostUsd != null && totalLoops > 0 ? totalCostUsd / totalLoops : null
+ const avatarUrl = timelines?.items[0]?.author.avatar_url
const workflowCostsTotal = workflowCosts.reduce((sum, c) => sum + (c.estimated_cost_usd ?? 0), 0)
// Ranked, biggest spend first; the bar length is each workflow's share of the window's total.
const rankedCosts = [...workflowCosts].sort((a, b) => (b.estimated_cost_usd ?? 0) - (a.estimated_cost_usd ?? 0))
- // A source can hold several repos, so the author's PRs may span repos. Only claim one repo (and link
- // per-workflow into it) when they all agree; otherwise the page is genuinely cross-repo.
- const repoSlugs = Array.from(new Set(prs.map((pr) => `${pr.repoOwner}/${pr.repoName}`)))
- const singleRepo = repoSlugs.length === 1 ? prs[0] : null
+ // Only claim one repo (and link per-workflow into it) when every listed pull request agrees.
+ const singleRepo = repoSlugs.length === 1 ? timelines?.items[0]?.repo : null
return (
<SceneContent className="pb-16">
@@ -83,15 +71,6 @@ export function EngineeringAnalyticsAuthorScene(): JSX.Element {
}
lensFilter={{ label: `author: ${handle}`, to: hubUrl }}
showDate={false}
- extra={
- <DateFilter
- dateFrom={dateFrom}
- dateTo={dateTo}
- onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
- dateOptions={AUTHOR_DATE_OPTIONS}
- size="small"
- />
- }
/>
<EntityHeader
icon={
@@ -108,59 +87,26 @@ export function EngineeringAnalyticsAuthorScene(): JSX.Element {
</Link>
}
right={
- prsLoading ? undefined : <VerdictPill kind="muted">{pluralize(openPrCount, 'open PR')}</VerdictPill>
+ summary ? (
+ <VerdictPill kind="muted">{pluralize(summary.open_pr_count, 'open PR')}</VerdictPill>
+ ) : undefined
}
/>
- {/* The author page is a way to find and explain one's own work — it lists this author's PRs and
- their CI cost. It carries no per-developer performance/ranking metric (no cycle time, no flaky
- score): the cost figures are transparent spend, not a scoreboard (SPEC §2). */}
- <div className="flex flex-col gap-4">
- {/* The scope-bar date picker scopes everything below it: these tiles, the PR list, and the
- breakdown. Tiles and list re-filter the already-loaded PRs client-side, so a date change
- updates them instantly (no skeleton); the skeleton is only for the initial PR fetch, so
- the tiles don't flash a zero before the list lands. */}
- <div className="flex flex-wrap gap-2.5">
- <MetricTile
- label="Pull requests opened"
- value={windowedRows.length.toLocaleString()}
- sub="in the selected window"
- loading={prsLoading}
- />
- <MetricTile
- label="CI cost"
- tooltip="Full CI cost of the PRs opened in the selected window, across each PR's whole history — not only runs inside the window. The 'Where their CI minutes go' breakdown below counts CI runs started in the window instead, so the two won't reconcile exactly."
- value={formatCost(totalCostUsd)}
- sub={
- totalCostUsd != null
- ? `${formatMinutes(totalBillableMinutes)} billable`
- : 'no cost data yet'
- }
- loading={prsLoading}
- />
- <MetricTile
- label="Cost per loop"
- tooltip="A loop is one push and the CI it triggered. Cost per loop = total CI cost ÷ total pushes across the PRs opened in the window — the spend of one iteration, not a running total."
- value={formatCost(costPerLoop)}
- sub={
- costPerLoop != null
- ? `${totalLoops.toLocaleString()} loops in the window`
- : 'no cost data yet'
- }
- loading={prsLoading}
- />
- </div>
-
- <Section id="author-prs" title="Pull requests">
- <PullRequestTable
- rows={windowedRows}
- loading={prsLoading}
- sourceId={sourceId}
- showAuthor={false}
- showCreated
- dataAttr="engineering-analytics-author-pr-table"
- emptyState={`No pull requests for ${handle} in the selected window.`}
+ {/* The page explains one author's own friction against the repository. It never compares
+ authors with each other (SPEC §2). */}
+ <ScopePanel
+ busy={summaryLoading || timelinesLoading || workflowCostsLoading}
+ controls={
+ <DateFilter
+ dateFrom={dateFrom}
+ dateTo={dateTo}
+ onChange={(from, to) => setDateRange(from ?? SHARED_DEFAULT_DATE_FROM, to ?? null)}
+ dateOptions={AUTHOR_DATE_OPTIONS}
+ size="small"
/>
- </Section>
+ }
+ >
+ <DeliverySections scope={deliveryScope} scopeLabel="This author" sourceId={sourceId} />
<Section id="author-cost" title="Where their CI minutes go">
{workflowCostsLoading ? (
@@ -205,8 +151,8 @@ export function EngineeringAnalyticsAuthorScene(): JSX.Element {
singleRepo
? combineUrl(
urls.engineeringAnalyticsWorkflowRuns(
- singleRepo.repoOwner,
- singleRepo.repoName,
+ singleRepo.owner,
+ singleRepo.name,
cost.workflow_name
),
sourceId ? { source: sourceId } : {}
@@ -229,7 +175,7 @@ export function EngineeringAnalyticsAuthorScene(): JSX.Element {
</span>
)}
</Section>
- </div>
+ </ScopePanel>
</SceneContent>
)
}
diff --git a/products/engineering_analytics/frontend/scenes/authorLogic.ts b/products/engineering_analytics/frontend/scenes/authorLogic.ts
index 69d1973630f7..0fc08b0802b2 100644
--- a/products/engineering_analytics/frontend/scenes/authorLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/authorLogic.ts
@@ -2,28 +2,18 @@ import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props, s
import { loaders } from 'kea-loaders'
import { ApiConfig } from 'lib/api'
-import { dayjs } from 'lib/dayjs'
-import { dateStringToDayJs } from 'lib/utils/dateFilters'
import { urls } from 'scenes/urls'
import { Breadcrumb } from '~/types'
-import { engineeringAnalyticsAuthorWorkflowCosts, engineeringAnalyticsPullRequests } from '../generated/api'
+import { engineeringAnalyticsAuthorWorkflowCosts } from '../generated/api'
import type { WorkflowCostApi } from '../generated/api.schemas'
+import { DeliveryScope } from '../lib/deliveryScope'
import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
-import { PullRequestRow, toPullRequestRow } from './engineeringAnalyticsLogic'
-
-const projectId = (): string => String(ApiConfig.getCurrentProjectId())
-
-// The author page is a filtered view of the PR list (author as a filter for finding work — SPEC §2),
-// not an aggregation level. The list load needs a floor for finished PRs — wide so it reads as "this
-// author's recent PRs", and wider than any cost-tile window so the tiles stay a subset. Open PRs come
-// back regardless.
-const LIST_WINDOW = '-365d'
export interface AuthorLogicProps {
handle: string
- // Which GitHub source the list was scoped to, threaded from `?source=` via paramsToProps.
+ // Which GitHub source the page was scoped to, threaded from `?source=` via paramsToProps.
sourceId: string | null
}
@@ -32,51 +22,21 @@ export interface authorLogicValues {
dateFrom: string | null // engineeringAnalyticsFiltersLogic
dateTo: string | null // engineeringAnalyticsFiltersLogic
breadcrumbs: Breadcrumb[]
+ deliveryScope: DeliveryScope
handle: string
- openPrCount: number
- prs: PullRequestRow[]
- prsLoading: boolean
sourceId: string | null
- totalBillableMinutes: number | null
- totalCostUsd: number | null
- totalLoops: number
- windowedRows: PullRequestRow[]
workflowCosts: WorkflowCostApi[]
workflowCostsLoading: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface authorLogicActions {
- loadPrs: () => any
- loadPrsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadPrsSuccess: (
- prs: PullRequestRow[],
- payload?: any
- ) => {
- prs: PullRequestRow[]
- payload?: any
- }
loadWorkflowCosts: () => any
- loadWorkflowCostsFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
+ loadWorkflowCostsFailure: (error: string, errorObject?: any) => { error: string; errorObject?: any }
loadWorkflowCostsSuccess: (
workflowCosts: WorkflowCostApi[],
payload?: any
- ) => {
- workflowCosts: WorkflowCostApi[]
- payload?: any
- }
+ ) => { workflowCosts: WorkflowCostApi[]; payload?: any }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -85,11 +45,7 @@ export interface authorLogicMeta {
__keaTypeGenInternalSelectorTypes: {
sourceId: (arg: string | null) => string | null
handle: (arg: string) => string
- windowedRows: (prs: PullRequestRow[], dateFrom: string | null, dateTo: string | null) => PullRequestRow[]
- totalCostUsd: (windowedRows: PullRequestRow[]) => number | null
- totalBillableMinutes: (windowedRows: PullRequestRow[]) => number | null
- totalLoops: (windowedRows: PullRequestRow[]) => number
- openPrCount: (prs: PullRequestRow[]) => number
+ deliveryScope: (handle: string) => DeliveryScope
breadcrumbs: (handle: string) => Breadcrumb[]
}
}
@@ -101,35 +57,18 @@ export const authorLogic = kea<authorLogicType>([
props({} as AuthorLogicProps),
key((props) => `author/${props.handle}@${props.sourceId ?? ''}`),
- // Shares the CI-analytics window, but only to scope the cost tiles (a client-side filter over the
- // already-loaded PRs) — the PR list below is never re-scoped, so changing the window never reloads it.
connect(() => ({
values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo']],
})),
loaders(({ props, values }) => ({
- prs: [
- [] as PullRequestRow[],
- {
- // Loaded once: the author's recent PRs, mapped to the shared table row shape. Stable across
- // date changes — the picker only scopes the cost tiles.
- loadPrs: async (): Promise<PullRequestRow[]> => {
- const result = await engineeringAnalyticsPullRequests(projectId(), {
- author: props.handle,
- date_from: LIST_WINDOW,
- source_id: props.sourceId ?? undefined,
- })
- return result.items.map(toPullRequestRow)
- },
- },
- ],
- // The author's CI spend split by workflow over the shared window — "where their CI minutes go".
- // [] when the job-level source isn't synced.
+ // The author's CI spend split by workflow, for "where their CI minutes go". [] when the job-level
+ // source isn't synced.
workflowCosts: [
[] as WorkflowCostApi[],
{
- loadWorkflowCosts: async (): Promise<WorkflowCostApi[]> =>
- await engineeringAnalyticsAuthorWorkflowCosts(projectId(), {
+ loadWorkflowCosts: async () =>
+ await engineeringAnalyticsAuthorWorkflowCosts(String(ApiConfig.getCurrentProjectId()), {
author: props.handle,
date_from: values.dateFrom ?? undefined,
date_to: values.dateTo ?? undefined,
@@ -140,7 +79,6 @@ export const authorLogic = kea<authorLogicType>([
})),
listeners(({ actions }) => ({
- // The shared window scopes the cost breakdown — reload it when the picker changes.
[engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {
actions.loadWorkflowCosts()
},
@@ -152,44 +90,8 @@ export const authorLogic = kea<authorLogicType>([
(sourceId: string | null): string | null => sourceId,
],
handle: [() => [(_, p: AuthorLogicProps) => p.handle], (handle: string): string => handle],
- // The cost-tile scope: PRs opened within the selected window. The list shows every loaded PR; only
- // the cost KPIs narrow to this subset, so the date picker reads as "CI cost of PRs opened in window".
- windowedRows: [
- (s) => [s.prs, s.dateFrom, s.dateTo],
- (prs: PullRequestRow[], dateFrom: string | null, dateTo: string | null): PullRequestRow[] => {
- const from = dateFrom ? dateStringToDayJs(dateFrom) : null
- const to = dateTo ? dateStringToDayJs(dateTo) : null
- return prs.filter((pr) => {
- const created = dayjs(pr.createdAt)
- // Inclusive of both bounds so a PR opened on the boundary day isn't dropped.
- return (!from || !created.isBefore(from)) && (!to || !created.isAfter(to))
- })
- },
- ],
- // Author CI cost across the in-window PRs — null when nothing was costable / the job source is unsynced.
- totalCostUsd: [
- (s) => [s.windowedRows],
- (rows: PullRequestRow[]): number | null => {
- const costs = rows.map((pr) => pr.estimatedCostUsd).filter((c): c is number => c != null)
- return costs.length ? costs.reduce((sum, c) => sum + c, 0) : null
- },
- ],
- totalBillableMinutes: [
- (s) => [s.windowedRows],
- (rows: PullRequestRow[]): number | null => {
- const minutes = rows.map((pr) => pr.billableMinutes).filter((m): m is number => m != null)
- return minutes.length ? minutes.reduce((sum, m) => sum + m, 0) : null
- },
- ],
- // A loop is one push and the CI it triggered; total loops = pushes across the in-window PRs.
- totalLoops: [
- (s) => [s.windowedRows],
- (rows: PullRequestRow[]): number => rows.reduce((sum, pr) => sum + pr.pushes, 0),
- ],
- openPrCount: [
- (s) => [s.prs],
- (prs: PullRequestRow[]): number => prs.filter((pr) => pr.state === 'open').length,
- ],
+ // Memoized, so the delivery logics keyed by this scope see one stable object per author.
+ deliveryScope: [(s) => [s.handle], (handle: string): DeliveryScope => ({ kind: 'author', author: handle })],
breadcrumbs: [
(_, p) => [p.handle],
(handle: string): Breadcrumb[] => [
@@ -211,7 +113,6 @@ export const authorLogic = kea<authorLogicType>([
}),
afterMount(({ actions }) => {
- actions.loadPrs()
actions.loadWorkflowCosts()
}),
])
diff --git a/products/engineering_analytics/frontend/scenes/deliverySummaryLogic.ts b/products/engineering_analytics/frontend/scenes/deliverySummaryLogic.ts
new file mode 100644
index 000000000000..24e29951401f
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/deliverySummaryLogic.ts
@@ -0,0 +1,94 @@
+import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { ApiConfig } from 'lib/api'
+
+import { engineeringAnalyticsDeliverySummary } from '../generated/api'
+import type { DeliverySummaryApi } from '../generated/api.schemas'
+import { DeliveryScope, deliveryScopeKey, deliveryScopeParams } from '../lib/deliveryScope'
+import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
+
+export interface DeliverySummaryLogicProps {
+ // An author or a GitHub team; the summary endpoint rejects a single pull request.
+ scope: DeliveryScope
+ sourceId: string | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface deliverySummaryLogicValues {
+ dateFrom: string | null // engineeringAnalyticsFiltersLogic
+ dateTo: string | null // engineeringAnalyticsFiltersLogic
+ summary: DeliverySummaryApi | null
+ summaryFailed: boolean
+ summaryLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface deliverySummaryLogicActions {
+ loadSummary: () => any
+ loadSummaryFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSummarySuccess: (
+ summary: DeliverySummaryApi,
+ payload?: any
+ ) => {
+ summary: DeliverySummaryApi
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface deliverySummaryLogicMeta {
+ key: string
+}
+
+export type deliverySummaryLogicType = MakeLogicType<
+ deliverySummaryLogicValues,
+ deliverySummaryLogicActions,
+ DeliverySummaryLogicProps,
+ deliverySummaryLogicMeta
+>
+
+export const deliverySummaryLogic = kea<deliverySummaryLogicType>([
+ path(['products', 'engineering_analytics', 'frontend', 'scenes', 'deliverySummaryLogic']),
+ props({} as DeliverySummaryLogicProps),
+ key((props) => `${deliveryScopeKey(props.scope)}@${props.sourceId ?? ''}`),
+
+ connect(() => ({
+ values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo']],
+ })),
+
+ loaders(({ props, values }) => ({
+ summary: [
+ null as DeliverySummaryApi | null,
+ {
+ loadSummary: async () =>
+ await engineeringAnalyticsDeliverySummary(String(ApiConfig.getCurrentProjectId()), {
+ ...deliveryScopeParams(props.scope),
+ date_from: values.dateFrom ?? undefined,
+ date_to: values.dateTo ?? undefined,
+ source_id: props.sourceId ?? undefined,
+ }),
+ },
+ ],
+ })),
+
+ reducers({
+ summaryFailed: [false, { loadSummary: () => false, loadSummaryFailure: () => true }],
+ }),
+
+ listeners(({ actions }) => ({
+ [engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {
+ actions.loadSummary()
+ },
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadSummary()
+ }),
+])
diff --git a/products/engineering_analytics/frontend/scenes/pullRequestTimelinesLogic.ts b/products/engineering_analytics/frontend/scenes/pullRequestTimelinesLogic.ts
new file mode 100644
index 000000000000..0360d36e25c3
--- /dev/null
+++ b/products/engineering_analytics/frontend/scenes/pullRequestTimelinesLogic.ts
@@ -0,0 +1,145 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { ApiConfig } from 'lib/api'
+
+import { engineeringAnalyticsPullRequestTimelines } from '../generated/api'
+import type { PullRequestTimelinesApi } from '../generated/api.schemas'
+import { DeliveryScope, deliveryScopeKey, deliveryScopeParams } from '../lib/deliveryScope'
+import {
+ DayViewAlignment,
+ DayViewGroup,
+ RedTimeByCause,
+ axisDays,
+ groupTimelines,
+ redTimeByCause,
+} from '../lib/pullRequestDayView'
+import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
+
+export interface PullRequestTimelinesLogicProps {
+ scope: DeliveryScope
+ sourceId: string | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pullRequestTimelinesLogicValues {
+ dateFrom: string | null // engineeringAnalyticsFiltersLogic
+ dateTo: string | null // engineeringAnalyticsFiltersLogic
+ dayViewAlignment: DayViewAlignment
+ dayViewAxisDays: number
+ dayViewGroups: DayViewGroup[]
+ redTime: RedTimeByCause
+ repoSlugs: string[]
+ timelines: PullRequestTimelinesApi | null
+ timelinesFailed: boolean
+ timelinesLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pullRequestTimelinesLogicActions {
+ loadTimelines: () => any
+ loadTimelinesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadTimelinesSuccess: (
+ timelines: PullRequestTimelinesApi,
+ payload?: any
+ ) => {
+ timelines: PullRequestTimelinesApi
+ payload?: any
+ }
+ setDayViewAlignment: (alignment: DayViewAlignment) => {
+ alignment: DayViewAlignment
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface pullRequestTimelinesLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ dayViewGroups: (timelines: PullRequestTimelinesApi | null) => DayViewGroup[]
+ dayViewAxisDays: (timelines: PullRequestTimelinesApi | null, dayViewAlignment: DayViewAlignment) => number
+ redTime: (timelines: PullRequestTimelinesApi | null) => RedTimeByCause
+ repoSlugs: (timelines: PullRequestTimelinesApi | null) => string[]
+ }
+}
+
+export type pullRequestTimelinesLogicType = MakeLogicType<
+ pullRequestTimelinesLogicValues,
+ pullRequestTimelinesLogicActions,
+ PullRequestTimelinesLogicProps,
+ pullRequestTimelinesLogicMeta
+>
+
+export const pullRequestTimelinesLogic = kea<pullRequestTimelinesLogicType>([
+ path(['products', 'engineering_analytics', 'frontend', 'scenes', 'pullRequestTimelinesLogic']),
+ props({} as PullRequestTimelinesLogicProps),
+ key((props) => `${deliveryScopeKey(props.scope)}@${props.sourceId ?? ''}`),
+
+ connect(() => ({
+ values: [engineeringAnalyticsFiltersLogic, ['dateFrom', 'dateTo']],
+ })),
+
+ actions({
+ setDayViewAlignment: (alignment: DayViewAlignment) => ({ alignment }),
+ }),
+
+ loaders(({ props, values }) => ({
+ timelines: [
+ null as PullRequestTimelinesApi | null,
+ {
+ loadTimelines: async () =>
+ await engineeringAnalyticsPullRequestTimelines(String(ApiConfig.getCurrentProjectId()), {
+ ...deliveryScopeParams(props.scope),
+ date_from: values.dateFrom ?? undefined,
+ date_to: values.dateTo ?? undefined,
+ source_id: props.sourceId ?? undefined,
+ }),
+ },
+ ],
+ })),
+
+ reducers({
+ dayViewAlignment: ['days' as DayViewAlignment, { setDayViewAlignment: (_, { alignment }) => alignment }],
+ timelinesFailed: [false, { loadTimelines: () => false, loadTimelinesFailure: () => true }],
+ }),
+
+ listeners(({ actions, props }) => ({
+ // A single pull request is shown whatever its age, so only list scopes follow the window.
+ [engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {
+ if (props.scope.kind !== 'pull_request') {
+ actions.loadTimelines()
+ }
+ },
+ })),
+
+ selectors({
+ dayViewGroups: [
+ (s) => [s.timelines],
+ (timelines: PullRequestTimelinesApi | null): DayViewGroup[] => groupTimelines(timelines?.items ?? []),
+ ],
+ dayViewAxisDays: [
+ (s) => [s.timelines, s.dayViewAlignment],
+ (timelines: PullRequestTimelinesApi | null, alignment: DayViewAlignment): number =>
+ axisDays(timelines?.items ?? [], alignment),
+ ],
+ redTime: [
+ (s) => [s.timelines],
+ (timelines: PullRequestTimelinesApi | null): RedTimeByCause => redTimeByCause(timelines?.items ?? []),
+ ],
+ // A source can hold several repos, so the listed pull requests may span repos.
+ repoSlugs: [
+ (s) => [s.timelines],
+ (timelines: PullRequestTimelinesApi | null): string[] =>
+ Array.from(new Set((timelines?.items ?? []).map((pr) => `${pr.repo.owner}/${pr.repo.name}`))),
+ ],
+ }),
+
+ afterMount(({ actions }) => {
+ actions.loadTimelines()
+ }),
+])
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index af4342dafef3..d086727e9f34 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-summary:
+ operation: engineering_analytics_delivery_summary
+ enabled: false
engineering-analytics-dora:
operation: engineering_analytics_dora
enabled: false
@@ -156,6 +159,9 @@ tools:
engineering-analytics-pr-runs:
operation: engineering_analytics_pr_runs
enabled: false
+ engineering-analytics-pull-request-timelines:
+ operation: engineering_analytics_pull_request_timelines
+ enabled: false
engineering-analytics-quarantine:
operation: engineering_analytics_quarantine
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index cbe9058ad50f..207499950771 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -28791,6 +28791,75 @@ export namespace Schemas {
include_posthog_hint?: boolean;
}
+ export interface DurationDistribution {
+ /** Pull requests in the distribution. Every statistic is null when this is 0. */
+ pr_count: number;
+ /**
+ * Fastest duration, in seconds.
+ * @nullable
+ */
+ min_seconds: number | null;
+ /**
+ * 5th percentile, in seconds: the lower whisker.
+ * @nullable
+ */
+ p05_seconds: number | null;
+ /**
+ * 25th percentile, in seconds: the box's lower edge.
+ * @nullable
+ */
+ p25_seconds: number | null;
+ /**
+ * Median, in seconds.
+ * @nullable
+ */
+ p50_seconds: number | null;
+ /**
+ * Mean, in seconds.
+ * @nullable
+ */
+ mean_seconds: number | null;
+ /**
+ * 75th percentile, in seconds: the box's upper edge.
+ * @nullable
+ */
+ p75_seconds: number | null;
+ /**
+ * 95th percentile, in seconds: the upper whisker.
+ * @nullable
+ */
+ p95_seconds: number | null;
+ /**
+ * Slowest duration, in seconds.
+ * @nullable
+ */
+ max_seconds: number | null;
+ }
+
+ export interface ScopeRepoDistribution {
+ /** The deployed pull requests in scope. */
+ scope: DurationDistribution;
+ /** Every deployed pull request in the repository. */
+ repo: DurationDistribution;
+ }
+
+ export interface DeliveryLeadTime {
+ /** Open to the first successful deploy containing the merge, over PRs deployed in the window. */
+ open_to_deploy: ScopeRepoDistribution;
+ /** Open to merge over the same deployed PRs, so it composes with merge_to_deploy. Includes draft time. */
+ open_to_merge: ScopeRepoDistribution;
+ /** Merge to deploy over the same deployed PRs. */
+ merge_to_deploy: ScopeRepoDistribution;
+ /** False when the deployments and deployment statuses tables aren't synced. The distributions are then empty. */
+ deploy_data_available: boolean;
+ /** The deploy environments lead time was scoped to: production by default. Empty when deploy data is not available. */
+ environment_scope: string;
+ /** PRs in scope merged in the window (bots and drafts excluded). */
+ merged_pr_count: number;
+ /** Of merged_pr_count, the PRs a successful in-scope deploy contains. The rest are still waiting for a deploy or fall outside the scan. */
+ deployed_merged_pr_count: number;
+ }
+
/**
* * `open_to_gate` - OPEN_TO_GATE
* * `gate_to_merge` - GATE_TO_MERGE
@@ -28830,6 +28899,96 @@ export namespace Schemas {
merged_pr_count: number;
}
+ /**
+ * * `author` - AUTHOR
+ * * `github_team` - GITHUB_TEAM
+ * * `pull_request` - PULL_REQUEST
+ */
+ export type DeliveryScopeKindEnum = typeof DeliveryScopeKindEnum[keyof typeof DeliveryScopeKindEnum];
+
+
+ export const DeliveryScopeKindEnum = {
+ Author: 'author',
+ GithubTeam: 'github_team',
+ PullRequest: 'pull_request',
+ } as const;
+
+ export interface ScopeRepoFigure {
+ /**
+ * The figure over the pull requests in scope. Null when the scope has nothing to measure.
+ * @nullable
+ */
+ scope: number | null;
+ /**
+ * The same figure over every non-bot pull request in the repository, the scope included. Null when the repository has nothing to measure.
+ * @nullable
+ */
+ repo: number | null;
+ }
+
+ export interface DeliverySummary {
+ /** Median estimated CI cost per merged PR, in USD, over every run linked to the PR (merge-queue gate runs included) that started up to 30 days before the window. Null when the jobs table isn't synced. */
+ cost_per_merged_pr_usd: ScopeRepoFigure;
+ /** Median billable runner minutes per merged PR, on the billed clock. Null when the jobs table isn't synced. */
+ billable_minutes_per_merged_pr: ScopeRepoFigure;
+ /** Total CI cost divided by total pushes over the merged PRs: the price of one iteration. A push is a distinct head commit that triggered CI. */
+ cost_per_push_usd: ScopeRepoFigure;
+ /** Median seconds from the last ready_for_review to merge. Null when issue events aren't synced. */
+ median_ready_to_merge_seconds: ScopeRepoFigure;
+ /** 90th percentile of the ready-to-merge seconds. */
+ p90_ready_to_merge_seconds: ScopeRepoFigure;
+ /** Median seconds from ready to the first approval. An approval given while the PR was a draft counts as 0. PRs merged without an approval are left out. Null when reviews aren't synced. */
+ median_ready_to_first_approval_seconds: ScopeRepoFigure;
+ /** Median seconds from the first approval to merge. This median and the one before it do not add up to the ready-to-merge median. */
+ median_first_approval_to_merge_seconds: ScopeRepoFigure;
+ /** Share (0 to 1) of all ready-to-merge hours spent before the first approval, summed over the PRs, so long PRs weigh more. The rest came after the approval. */
+ before_first_approval_share: ScopeRepoFigure;
+ /** Mean pushes after the first approval per merged PR, over PRs with an approval. */
+ pushes_after_approval_per_merged_pr: ScopeRepoFigure;
+ /** Mean merge-queue gate attempts per merged PR that went through the queue. A bisection probe folds into its attempt. */
+ merge_queue_attempts_per_merged_pr: ScopeRepoFigure;
+ /** Share (0 to 1) of queue-landed merged PRs with at least one failed gate attempt. A failure caused by another PR ahead in the queue also counts, because the queue history is not in the warehouse. */
+ failed_merge_queue_share: ScopeRepoFigure;
+ /** Lead time to deploy for the scope against the repository. */
+ lead_time: DeliveryLeadTime;
+ /** What the read covers: 'author' (one GitHub login), 'github_team' (the members of one GitHub team, through the team membership table), or 'pull_request' (one pull request).
+ *
+ * * `author` - AUTHOR
+ * * `github_team` - GITHUB_TEAM
+ * * `pull_request` - PULL_REQUEST */
+ scope_kind: DeliveryScopeKindEnum;
+ /** The GitHub login or GitHub team slug the summary is for. */
+ scope: string;
+ /** True when the team membership table is synced. A github_team scope without it matches no pull requests, so every scope figure is empty rather than the whole repository. */
+ has_membership_data: boolean;
+ /** True when the workflow jobs table is synced, which cost needs. */
+ jobs_available: boolean;
+ /** True when the reviews table is synced, which the approval split needs. */
+ review_data_available: boolean;
+ /** True when issue events are synced, which ready-to-merge time needs. */
+ ready_data_available: boolean;
+ /** PRs in scope opened in the window, drafts included, bots excluded. */
+ opened_pr_count: number;
+ /** PRs in scope merged in the window (bots and drafts excluded): the population of every per-merged-PR figure. */
+ merged_pr_count: number;
+ /** PRs in scope that are open and not drafts right now. Ignores the window. */
+ open_pr_count: number;
+ /** PRs in scope that are open drafts right now. Ignores the window. */
+ draft_pr_count: number;
+ /**
+ * Estimated CI cost summed over the merged PRs in scope. Null when nothing was costable.
+ * @nullable
+ */
+ total_cost_usd: number | null;
+ /**
+ * Billable minutes summed over the merged PRs in scope. Null when the jobs table isn't synced.
+ * @nullable
+ */
+ total_billable_minutes: number | null;
+ /** Pushes summed over the merged PRs in scope. */
+ push_count: number;
+ }
+
export interface DependentFlag {
/** Feature flag ID */
id: number;
@@ -56538,6 +56697,102 @@ export namespace Schemas {
metric_quality?: MetricQualityEnum;
}
+ /**
+ * * `draft` - DRAFT
+ * * `waiting_for_review` - WAITING_FOR_REVIEW
+ * * `changes_requested` - CHANGES_REQUESTED
+ * * `approved_not_enqueued` - APPROVED_NOT_ENQUEUED
+ * * `review_state_unknown` - REVIEW_STATE_UNKNOWN
+ * * `ci_running` - CI_RUNNING
+ * * `red_passed_on_rerun` - RED_PASSED_ON_RERUN
+ * * `red_master_broken` - RED_MASTER_BROKEN
+ * * `red_fixed_by_push` - RED_FIXED_BY_PUSH
+ * * `red_not_provable` - RED_NOT_PROVABLE
+ * * `merge_queue` - MERGE_QUEUE
+ * * `out_of_merge_queue` - OUT_OF_MERGE_QUEUE
+ */
+ export type PRTimelineSegmentKindEnum = typeof PRTimelineSegmentKindEnum[keyof typeof PRTimelineSegmentKindEnum];
+
+
+ export const PRTimelineSegmentKindEnum = {
+ Draft: 'draft',
+ WaitingForReview: 'waiting_for_review',
+ ChangesRequested: 'changes_requested',
+ ApprovedNotEnqueued: 'approved_not_enqueued',
+ ReviewStateUnknown: 'review_state_unknown',
+ CiRunning: 'ci_running',
+ RedPassedOnRerun: 'red_passed_on_rerun',
+ RedMasterBroken: 'red_master_broken',
+ RedFixedByPush: 'red_fixed_by_push',
+ RedNotProvable: 'red_not_provable',
+ MergeQueue: 'merge_queue',
+ OutOfMergeQueue: 'out_of_merge_queue',
+ } as const;
+
+ export interface PRTimelineSegment {
+ /** What the PR waited on: draft; waiting_for_review (no approval yet, or re-review after a push); changes_requested (no push since); approved_not_enqueued (approved, with no failing or running check); review_state_unknown (reviews not synced); ci_running; red_passed_on_rerun (the failed workflows passed a re-run of the same commit); red_master_broken (the failed jobs also failed on the default branch within 12 hours); red_fixed_by_push (a later commit arrived); red_not_provable; merge_queue (every queue state collapsed); out_of_merge_queue (open PR, Trunk says failed or cancelled).
+ *
+ * * `draft` - DRAFT
+ * * `waiting_for_review` - WAITING_FOR_REVIEW
+ * * `changes_requested` - CHANGES_REQUESTED
+ * * `approved_not_enqueued` - APPROVED_NOT_ENQUEUED
+ * * `review_state_unknown` - REVIEW_STATE_UNKNOWN
+ * * `ci_running` - CI_RUNNING
+ * * `red_passed_on_rerun` - RED_PASSED_ON_RERUN
+ * * `red_master_broken` - RED_MASTER_BROKEN
+ * * `red_fixed_by_push` - RED_FIXED_BY_PUSH
+ * * `red_not_provable` - RED_NOT_PROVABLE
+ * * `merge_queue` - MERGE_QUEUE
+ * * `out_of_merge_queue` - OUT_OF_MERGE_QUEUE */
+ kind: PRTimelineSegmentKindEnum;
+ /** Segment start. */
+ started_at: string;
+ /** Segment end: the next segment's start, the merge or close, or now. */
+ ended_at: string;
+ }
+
+ export interface PRTimeline {
+ /** The repository the pull request belongs to. */
+ repo: RepoRef;
+ /** Consecutive segments from started_at to the merge, the close, or now, with no gaps. */
+ segments: PRTimelineSegment[];
+ /** Pull request number. */
+ number: number;
+ /** Pull request title. */
+ title: string;
+ /** The pull request's author. */
+ author: Author;
+ /** open, merged, or closed. Author and team scopes list open and merged PRs only; a pull_request scope returns the PR whatever its state.
+ *
+ * * `open` - OPEN
+ * * `closed` - CLOSED
+ * * `merged` - MERGED */
+ state: EngineeringAnalyticsPRStateEnum;
+ /** True when the PR is a draft right now. */
+ is_draft: boolean;
+ /** When the PR was opened. */
+ created_at: string;
+ /** Where the timeline starts: the last ready_for_review before the end, else created_at. A PR listed for an author or a team starts no earlier than 30 days before the window, because older CI is not read. */
+ started_at: string;
+ /**
+ * Merge time; null when not merged.
+ * @nullable
+ */
+ merged_at: string | null;
+ /** Distinct head commits that triggered CI, merge-queue gate runs excluded. */
+ pushes: number;
+ /**
+ * Estimated CI cost over the PR's runs, in USD. Null when nothing was costable.
+ * @nullable
+ */
+ estimated_cost_usd: number | null;
+ /**
+ * Billable minutes over the PR's runs. Null when the jobs table isn't synced.
+ * @nullable
+ */
+ billable_minutes: number | null;
+ }
+
export interface PaginatedAccountChannelSummaryList {
count: number;
/** @nullable */
@@ -74896,6 +75151,33 @@ export namespace Schemas {
readonly reaction: PullRequestCommentReaction;
}
+ export interface PullRequestTimelines {
+ /** The pull requests in scope, newest first: open PRs plus PRs merged in the window, or the one pull request of a pull_request scope. */
+ items: PRTimeline[];
+ /** What the read covers: 'author' (one GitHub login), 'github_team' (the members of one GitHub team, through the team membership table), or 'pull_request' (one pull request).
+ *
+ * * `author` - AUTHOR
+ * * `github_team` - GITHUB_TEAM
+ * * `pull_request` - PULL_REQUEST */
+ scope_kind: DeliveryScopeKindEnum;
+ /** The GitHub login, GitHub team slug, or 'owner/name#number' the timelines are for. */
+ scope: string;
+ /** True when the team membership table is synced. A github_team scope without it lists no pull requests. */
+ has_membership_data: boolean;
+ /** False when reviews aren't synced: review stretches read review_state_unknown. */
+ review_data_available: boolean;
+ /** False when workflow jobs aren't synced: a check a re-run turned green is not visible, and no red stretch reads red_master_broken. */
+ jobs_available: boolean;
+ /** True when the Trunk merge-queue table is synced, so out_of_merge_queue can appear. */
+ merge_queue_state_available: boolean;
+ /** The now every open PR's timeline ends at. */
+ generated_at: string;
+ /** True when more PRs matched than the limit. */
+ truncated: boolean;
+ /** The maximum number of PRs returned. */
+ limit: number;
+ }
+
/**
* * `run` - RUN
* * `skip` - SKIP
@@ -98480,6 +98762,33 @@ export namespace Schemas {
source_id?: string;
};
+ export type EngineeringAnalyticsDeliverySummaryParams = {
+ /**
+ * GitHub login: scope the read to this author's pull requests. Pass exactly one scope.
+ */
+ 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;
+ /**
+ * GitHub team slug: scope the read to pull requests authored by the team's members, through the team membership table. Pass exactly one scope.
+ */
+ github_team?: string;
+ /**
+ * '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 EngineeringAnalyticsDoraParams = {
/**
* Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
@@ -98668,6 +98977,37 @@ export namespace Schemas {
source_id?: string;
};
+ export type EngineeringAnalyticsPullRequestTimelinesParams = {
+ /**
+ * GitHub login: scope the read to this author's pull requests. Pass exactly one scope.
+ */
+ 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;
+ /**
+ * GitHub team slug: scope the read to pull requests authored by the team's members, through the team membership table. Pass exactly one scope.
+ */
+ github_team?: string;
+ /**
+ * Pull request number: scope the read to this one pull request. Needs repo. Pass exactly one scope.
+ */
+ 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 EngineeringAnalyticsPullRequestsParams = {
/**
* Optional GitHub login to scope the list to one author's pull requests.