:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(engineering-analytics): add an engineering health tab with DORA metrics (#89744)
Paul D'Ambraa59822f30f88
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 65c090c00182..af5dffe6e44e 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6392,6 +6392,18 @@ snapshots:hash: v1.k794b7964.fadc2b2c0b5eedb49391586e0b3e5ea2aa845dd0b27c006cfad7389017158568.9Gke9ur_lx2xjtG29fVYUTYyUhDzjVg-dWWgpo5znTQscenes-app-discussions--threads--light:hash: v1.k794b7964.28ac830bf83be5cbb6d7a397d67c9b9c61711904a822de38402b82220b0f7a49.7wENY7hvo1-qAJwq5fcsvKGJsfRAF_vDkpnM8iqFZcc+ scenes-app-engineering-analytics-health--health--dark:+ hash: v1.k794b7964.b8902c89008241c64ee3bfdcb8c44487b554e2497a8584f97cc67f43cb4c1c69.QPnLLWzp2_Ws0wFksijbEcIvTfD8Fb874rD2NISaVEE+ scenes-app-engineering-analytics-health--health--light:+ hash: v1.k794b7964.459fb12016f38047bfbf269d4635f49f6e66f5f92957d1ad9530d3471a8154ae.xBetEUqMF_2UZCjM3dC_O-XVan0KimokVlMyt70U144+ scenes-app-engineering-analytics-health--health-without-deploy-data--dark:+ hash: v1.k794b7964.58b497c9d65b91a820cd6fbf7decc0627b6006946df570824ec6f3a68e49c230.MKWpeh48gtixnh7IiCceKSqs7MGfIZOC5hnQgArT4CE+ scenes-app-engineering-analytics-health--health-without-deploy-data--light:+ hash: v1.k794b7964.83590800de556a39cd9e85c19cde97d011a2e56765b06dc765868b03dd886097.3Ilkg3NQEt-PVwQaBuo6EVIwqwPH_1o7MFPzNddaPPI+ scenes-app-engineering-analytics-merge-to-deploy-box-plot--default--dark:+ hash: v1.k794b7964.1c0d26b47aadd2aa58a53db3c1c43d50bf74204bf46fa0aa1206e77a96049c07.hdnRtkYHoot4Nik9IeOYVGzQP5bsA0b93Jb6jkvZ-h0+ scenes-app-engineering-analytics-merge-to-deploy-box-plot--default--light:+ hash: v1.k794b7964.f9dd9678e343abe67837ac9177e67678b401b1a483b2737ab864c68b4e709e96.wQEuD6-8vgiJ-VBOdfNXccMoMwGBy2OLrzoGnFq_hSUscenes-app-engineering-analytics-repo-overview--repo-overview--dark:hash: v1.k794b7964.93f0784927beb8f29f7060b98795fc4200dc169ef7f5da3fe255cf5e143c0ff3.-5znSrlummkvLSBLsYSKNzJ3Co4GxMNxsndYCtHeMmsscenes-app-engineering-analytics-repo-overview--repo-overview--light:diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 16bfa07fa5f4..e255aea953e0 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -145,6 +145,7 @@ export const productRoutes: Record<string, [string, string]> = {'/engineering-analytics/workflows': ['EngineeringAnalytics', 'engineeringAnalyticsWorkflows'],'/engineering-analytics/test-health': ['EngineeringAnalytics', 'engineeringAnalyticsTestHealth'],'/engineering-analytics/teams': ['EngineeringAnalytics', 'engineeringAnalyticsTeams'],+ '/engineering-analytics/health': ['EngineeringAnalytics', 'engineeringAnalyticsHealth'],'/engineering-analytics/teams/:ownerTeam': ['EngineeringAnalyticsTeam', 'engineeringAnalyticsTeam'],'/engineering-analytics/repos/:repoOwner/:repoName/pull-requests/:number': ['EngineeringAnalyticsPullRequest',@@ -1205,6 +1206,7 @@ export const productUrls = {engineeringAnalyticsWorkflows: (): string => '/engineering-analytics/workflows',engineeringAnalyticsTestHealth: (): string => '/engineering-analytics/test-health',engineeringAnalyticsTeams: (): string => '/engineering-analytics/teams',+ engineeringAnalyticsHealth: (): string => '/engineering-analytics/health',engineeringAnalyticsTeam: (ownerTeam: string): string =>`/engineering-analytics/teams/${encodeURIComponent(ownerTeam)}`,engineeringAnalyticsPullRequest: (repoOwner: string, repoName: string, number: number | string): string =>diff --git a/products/engineering_analytics/README.md b/products/engineering_analytics/README.mdindex ad809283ee62..19a66d9d0558 100644--- a/products/engineering_analytics/README.md+++ b/products/engineering_analytics/README.md@@ -93,16 +93,18 @@ 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) |-| Time-in-review, approvals | PR lifecycle events (webhooks to events, PR as group type): deferred |-| Deploys and DORA | Deploy data: deferred |+| 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` |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.+Deploys left that deferral: unlike the snapshots, `github_deployment_statuses` is an append-oriented, webhook-fed status history (one row per transition), so DORA reads don't need the events destination.+Change failure rate and time-to-restore still lack an incident link, so they ship as honest deploy-status proxies — the caveat rides in the field docs (`failed_deployment_share`, `median_failed_deploy_to_next_success_seconds`), the aggregate-endpoint pattern; a typed `metric_quality` field is reserved for deep tools like `pr_lifecycle`.## Locked decisionsdiff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex ee21f92d2a56..3146d1e84d90 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -164,7 +164,9 @@ Other products read as sources:**Freshness caveat:** a run's `conclusion` settles via the `workflow_run` webhook, which can lag or miss deliveries; the read layer surfaces `status` honestly rather than implying a settled conclusion.-Lifecycle data the snapshots can't hold and `github_issue_events` doesn't carry (reviews/approvals, deploys, DORA) needs immutable timestamped events (GitHub webhooks → PostHog events, PR as group type). That is the only thing the deferred events destination is for. See README → "The data boundary".+- `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".## 8. Reference readingdiff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex dd459004ce71..e8bbc887f1e4 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -31,6 +31,7 @@ from products.engineering_analytics.backend.facade.contracts import (CISignalsConfig,CITestRunner,CurrentBranchHealth,+ DoraOverview,FlakyTestList,GitHubSource,MasterFailureGroup,@@ -483,6 +484,26 @@ def get_repo_overview()+def get_dora_overview(+ *,+ team: Team,+ date_from: str | None = None,+ date_to: str | None = None,+ environment: str | None = None,+ github_team: str | None = None,+ source_id: str | None = None,+ repo: str | None = None,+ user_access_control: "UserAccessControl | None" = None,+) -> DoraOverview:+ return logic.build_dora_overview(+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),+ date_from=date_from,+ date_to=date_to,+ environment=environment,+ github_team=github_team,+ )++def get_current_branch_health(*,team: Team,diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex fe1575392986..c3da69a76c4f 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -1160,6 +1160,122 @@ class RepoOverview:ready_to_merge_series_granularity: str+@dataclass(frozen=True)+class DeploymentFrequencyBucket:+ """One time bucket of successful deployments, keyed on the deploy's first success status.+ Empty buckets are zero-filled with 0 — no deploy in a bucket genuinely means nothing shipped.+ """++ # Bucket start, aligned to the granularity (top of hour / midnight / Monday).+ bucket_start: datetime+ # Deployments whose first success status landed in this bucket, within the environment scope.+ deployment_count: int+++@dataclass(frozen=True)+class MergeToDeployBucket:+ """One time bucket of per-PR merge-to-deploy seconds — the box-plot distribution of how long+ merged PRs waited until the first successful deployment containing their merge (resolved+ through the deploy's head commit; bots and drafts excluded, per the locked cycle-time+ recipe). Keyed on deploy time: a PR lands in the bucket its deploy succeeded in. The measure+ is named for exactly what it is: merge to deploy, not the full commit-to-deploy DORA lead+ time (pre-merge time is on the other cards).+ Buckets where nothing deployed carry ``deployed_pr_count`` 0 and null stats (a gap).+ """++ # Bucket start, aligned to the granularity (top of hour / midnight / Monday).+ bucket_start: datetime+ # PRs whose first post-merge successful deployment landed in this bucket.+ deployed_pr_count: int+ # Distribution of merged_at → first successful deploy, in seconds, over those PRs — the+ # six-number summary a box plot draws (box p25→p75, median line, mean marker, whiskers).+ min_seconds: float | None+ p25_seconds: float | None+ p50_seconds: float | None+ mean_seconds: float | None+ p75_seconds: float | None+ max_seconds: float | None+++@dataclass(frozen=True)+class DoraOverview:+ """DORA-style deploy metrics over the window, each headline with its previous-window twin.++ Built from the GitHub ``deployments`` + ``deployment_statuses`` warehouse pair. The four DORA+ quadrants map onto honest fields: deployment frequency and merge-to-deploy lead time are+ computed directly; change failure rate and time-to-restore have no incident link yet, so they+ ship as deploy-status proxies under names that say what is actually measured+ (``failed_deployment_share``, ``median_failed_deploy_to_next_success_seconds``).++ ``deploy_data_available`` is False when the deploy tables aren't synced — every other field is+ then empty/None, never a fake zero. A ``github_team`` filter narrows only the PR-scoped+ merge-to-deploy figures (deploy counts are repo events, not team events); when membership data+ isn't synced the filter can't be honored, so those figures go empty rather than silently+ unfiltered (``has_membership_data``).+ """++ # False when the deployments/deployment_statuses tables aren't synced for the selected repo.+ deploy_data_available: bool+ # What the environment filter resolved to: 'production' (deployments GitHub marks+ # production_environment), an exact environment name (the one the caller passed, or —+ # when nothing is marked production — the busiest persistent environment, so a multi-region+ # repo doesn't multiply every count), or 'persistent' (no persistent environment deployed in+ # the window at all, so every non-transient one counts). Transient environments (ephemeral+ # per-PR previews) never join a default scope. The scope resolves from deployments in the+ # scan window, so two different windows can resolve different scopes and are not always comparable.+ environment_scope: str+ # Distinct persistent environments deployed to in the scan window, most-deployed first — the+ # picker's options. Transient environments are omitted but stay reachable by exact name.+ environments: list[str]+ # True when the optional team-membership snapshot is synced (the github_team filter's substrate).+ has_membership_data: bool+ # Distinct GitHub team slugs from the membership snapshot, sorted — the team picker's options.+ github_teams: list[str]+ # Deployments whose first success status landed in the window, within the environment scope.+ deployment_count: int+ deployment_count_prev: int+ # deployment_count normalized by the window length in days. Null only when the deploy tables aren't synced.+ deployments_per_day: float | None+ deployments_per_day_prev: float | None+ # Median seconds from a PR's merge to the first successful deployment containing it —+ # containment resolved through the deploy's head commit, not the deploy's success time+ # (bots/drafts excluded; narrowed by github_team when given). Keyed on deploy time.+ median_merge_to_deploy_seconds: float | None+ median_merge_to_deploy_seconds_prev: float | None+ # PRs first deployed in the window (the population behind the medians and the box plot).+ deployed_pr_count: int+ deployed_pr_count_prev: int+ # Deployments with at least one failure/error status, keyed on the first failure time.+ failed_deployment_count: int+ failed_deployment_count_prev: int+ # failed deployments / deployments that reached any outcome (success or failure). A change+ # failure *proxy*: no incident data is linked, so a deploy that succeeded but broke production+ # is not counted. None when nothing reached an outcome.+ failed_deployment_share: float | None+ failed_deployment_share_prev: float | None+ # Median seconds from a deployment's first failure status to the next successful deployment in+ # the same environment. A time-to-restore *proxy*: recovery by anything other than a deploy is+ # invisible, and failures not yet recovered are excluded. None when no failed deploy recovered.+ median_failed_deploy_to_next_success_seconds: float | None+ median_failed_deploy_to_next_success_seconds_prev: float | None+ # PRs merged in the window (bots/drafts excluded; narrowed by github_team when given) — the+ # denominator behind unattributed_merged_pr_share.+ merged_pr_count: int+ # Share of merged_pr_count no successful in-scope deployment attributed: recent merges still+ # waiting for their deploy, plus merges whose deploy the scope or scan bounds miss. None when+ # nothing merged in the window.+ unattributed_merged_pr_share: float | None+ # The newest deployment status row synced, any environment — how fresh the deploy data is.+ # Windows ending after this instant undercount. None when the deploy tables are empty.+ latest_deploy_status_at: datetime | None+ # Successful deployments per bucket across the window, oldest first, zero-filled.+ deployment_frequency_series: list[DeploymentFrequencyBucket]+ # Merge-to-deploy distribution per bucket across the window, oldest first — the box-plot series.+ merge_to_deploy_series: list[MergeToDeployBucket]+ # Bucket width of both series, chosen to fit the window: 'hour', 'day', or 'week'.+ series_granularity: str++@dataclass(frozen=True)class CurrentBranchHealth:"""Current default-branch CI verdict over the last 24 hours.diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.pyindex 4366a111c37c..371b67b154a1 100644--- a/products/engineering_analytics/backend/logic/__init__.py+++ b/products/engineering_analytics/backend/logic/__init__.py@@ -18,6 +18,7 @@ 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.dora import build_dora_overview as build_dora_overviewfrom products.engineering_analytics.backend.logic.pull_requests import (build_author_workflow_costs as build_author_workflow_costs,build_ci_cards as build_ci_cards,diff --git a/products/engineering_analytics/backend/logic/dora.py b/products/engineering_analytics/backend/logic/dora.pynew file mode 100644index 000000000000..6cf47e30edda--- /dev/null+++ b/products/engineering_analytics/backend/logic/dora.py@@ -0,0 +1,25 @@+"""Orchestration for the DORA deploy-metrics read."""++from products.engineering_analytics.backend.facade.contracts import DoraOverview+from products.engineering_analytics.backend.logic._shared import _DEFAULT_WINDOW, _parse_window+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource+from products.engineering_analytics.backend.logic.queries.dora import query_dora_overview+++def build_dora_overview(+ *,+ curated: CuratedGitHubSource,+ date_from: str | None = None,+ date_to: str | None = None,+ environment: str | None = None,+ github_team: str | None = None,+) -> DoraOverview:+ parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)+ return query_dora_overview(+ curated=curated,+ date_from=parsed_from,+ date_to=parsed_to,+ # Blank means "no filter", matching the branch-filter convention.+ environment=(environment or "").strip() or None,+ github_team=(github_team or "").strip() or None,+ )diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.pyindex 19b7066c61e4..37279ef7ff1c 100644--- a/products/engineering_analytics/backend/logic/queries/_curated.py+++ b/products/engineering_analytics/backend/logic/queries/_curated.py@@ -25,6 +25,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.clickhouse.workload import Workload+from posthog.dataclasses import frozenfrom posthog.models.team import Teamfrom products.engineering_analytics.backend.logic.sources import (@@ -33,6 +34,7 @@ from products.engineering_analytics.backend.logic.sources import (resolve_trunk_merge_queue_table,)from products.engineering_analytics.backend.logic.views import (+ deployments,issue_events,job_costs,pull_requests,@@ -54,6 +56,14 @@ class _IssueEventsWindow:end: str+@frozen+class DeploySources:+ """The curated deploy pair's ``SELECT`` subqueries, resolved and gated together."""++ deployments: str+ statuses: str++_READY_BY_PR_JOIN = "LEFT JOIN ready_by_pr AS re ON re.pr_number = pr.number"@@ -205,6 +215,17 @@ class CuratedGitHubSource:return Nonereturn f"({issue_events.build_query(self._tables.issue_events)})"+ 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+ status rows, so one table without the other can't serve an honest read."""+ if not (self._tables.deployments and self._tables.deployment_statuses):+ return None+ return DeploySources(+ deployments=f"({deployments.build_deployments_query(self._tables.deployments)})",+ statuses=f"({deployments.build_deployment_statuses_query(self._tables.deployment_statuses)})",+ )+def ready_to_merge_sql(self) -> ReadyToMergeSql:"""SQL for the per-PR ready-to-merge measure, off the PR source aliased ``pr``. Degrades toa constant NULL when the optional issue-events table isn't synced, so every consumer readsdiff --git a/products/engineering_analytics/backend/logic/queries/dora.py b/products/engineering_analytics/backend/logic/queries/dora.pynew file mode 100644index 000000000000..6fb5f253377f--- /dev/null+++ b/products/engineering_analytics/backend/logic/queries/dora.py@@ -0,0 +1,655 @@+"""Curated query: DORA-style deploy metrics over the GitHub deployments pair.++Four quadrants, honestly named (SPEC §4):++- Deployment frequency: deployments whose first ``success`` status landed in the+ window, within the environment scope. Computed directly.+- Lead time: ``merge_to_deploy_seconds`` — a merged PR's wait until the first+ successful deployment that *contains* its merge. Containment is resolved through+ the deploy's head commit: the deploy's SHA is some merged PR's ``merge_commit_sha``,+ and every merge at or before that head merge is on board. Success time alone+ cannot decide this — deploys ship pre-built images, so a deploy routinely+ succeeds *after* a merge it does not contain. The field name says merge-to-deploy,+ not the full commit-to-deploy DORA definition (pre-merge time is measured elsewhere).+- Change failure: ``failed_deployment_share`` — deployments with a failure/error+ status over deployments that reached any outcome. A proxy: no incident link, so+ a deploy that succeeded but broke production is invisible.+- Restore: ``median_failed_deploy_to_next_success_seconds`` — first failure status+ to the next successful deployment in the same environment. A proxy: recovery by+ anything other than a deploy is invisible, and unrecovered failures are excluded.++The PR-scoped lead-time reads follow the locked cycle-time recipe (bots and drafts+excluded) and accept the ``team_members`` join for a GitHub-team filter — a team+surface, aggregates only (SPEC §6). Deploy counts are repo events and ignore the+team filter by design.+"""++from datetime import datetime, timedelta+from typing import Any++from posthog.schema import HogQLQueryResponse++from posthog.hogql import ast++from posthog.dataclasses import frozen++from products.engineering_analytics.backend.facade.contracts import (+ DeploymentFrequencyBucket,+ DoraOverview,+ MergeToDeployBucket,+)+from products.engineering_analytics.backend.logic.queries._buckets import (+ Granularity,+ bucket_expr,+ normalize_bucket,+ pick_granularity,+ window_buckets,+)+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_float+from products.engineering_analytics.backend.logic.queries._workflow_filters import window_pair_predicates++# PRs merged this long before the scan window are outside lead-time attribution: the PR snapshot+# holds every PR ever, so the deployed-PR join needs a floor. On a continuous-deploy repo a merge+# waits minutes-to-hours for its deploy, so the bound is generous; a merge deployed more than this+# much later is dropped rather than scanning the whole snapshot.+_MERGE_SCAN_LOOKBACK = timedelta(days=30)++# Slack below the scan window so a deployment created before the window still counts when its+# outcome lands inside it. A week covers even a badly stalled rollout; the deploy tables are+# per-repo and small enough that the wider floor costs nothing measurable.+_DEPLOY_SCAN_SLACK = timedelta(days=7)++_ENVIRONMENTS_LIMIT = 100+_TEAMS_LIMIT = 500++# One row per deployment with its outcome timestamps: statuses are append-only transitions, so the+# first success / first failure are the outcome edges every read keys on. INNER JOIN drops+# deployments with no status rows — they never reached an outcome. __ENV_PREDICATE__ is one of the+# trusted variants below (never user input; the exact-match variant reads a placeholder).+# Assumes one deployment id per attempt (GitHub's normal shape): a deployment carrying both a+# failure and a later success status on the same id would count toward both outcomes and could+# pair with itself in the restore self-join.+_DEPLOYS_CTE = """+ deploys AS (+ SELECT+ d.id AS id,+ any(d.sha) AS sha,+ any(d.environment) AS environment,+ minIf(s.created_at, s.state = 'success') AS first_success_at,+ minIf(s.created_at, s.state IN ('failure', 'error')) AS first_failure_at+ FROM __DEPLOYMENTS_SOURCE__ AS d+ INNER JOIN __STATUSES_SOURCE__ AS s ON s.deployment_id = d.id+ WHERE d.created_at >= {deploy_scan_floor} AND __ENV_PREDICATE__+ GROUP BY d.id+ )+"""++# Outcome counts, the restore proxy, and the data-freshness edge in ONE round trip: every half+# aggregates to a single row, so the CROSS JOINs just glue the rows side by side and the deploys+# CTE is scanned once instead of twice.+#+# The restore half measures recovery per failed deployment: the next successful deployment in the+# SAME environment. The self-join fans out and the min collapses it back to one row per failure;+# deploy tables are small (per-repo, windowed) so the quadratic pairing stays cheap.+# __DATE_TO_RECOVERY__ bounds the recovery to the requested horizon, so a historical report's+# "no recovery" doesn't flip to recovered once a later, out-of-range deployment succeeds.+_OUTCOMES_SELECT = """+ SELECT+ outcomes.deployment_count,+ outcomes.deployment_count_prev,+ outcomes.failed_count,+ outcomes.failed_count_prev,+ outcomes.outcome_count,+ outcomes.outcome_count_prev,+ restore.restore_median_cur,+ restore.restore_median_prev,+ freshness.latest_status_at+ FROM (+ SELECT+ countIf(first_success_at IS NOT NULL AND __CUR_SUCCESS__) AS deployment_count,+ countIf(first_success_at IS NOT NULL AND __PREV_SUCCESS__) AS deployment_count_prev,+ countIf(first_failure_at IS NOT NULL AND __CUR_FAILURE__) AS failed_count,+ countIf(first_failure_at IS NOT NULL AND __PREV_FAILURE__) AS failed_count_prev,+ countIf((first_success_at IS NOT NULL AND __CUR_SUCCESS__)+ OR (first_failure_at IS NOT NULL AND __CUR_FAILURE__)) AS outcome_count,+ countIf((first_success_at IS NOT NULL AND __PREV_SUCCESS__)+ OR (first_failure_at IS NOT NULL AND __PREV_FAILURE__)) AS outcome_count_prev+ FROM deploys+ ) AS outcomes+ CROSS JOIN (+ SELECT+ quantileIf(0.5)(recovery_seconds, __CUR_FAILURE__) AS restore_median_cur,+ quantileIf(0.5)(recovery_seconds, __PREV_FAILURE__) AS restore_median_prev+ FROM (+ SELECT+ f.first_failure_at AS first_failure_at,+ dateDiff('second', f.first_failure_at, min(r.first_success_at)) AS recovery_seconds+ FROM deploys AS f+ INNER JOIN deploys AS r ON r.environment = f.environment+ WHERE f.first_failure_at IS NOT NULL+ AND r.first_success_at IS NOT NULL+ AND r.first_success_at >= f.first_failure_at+ __DATE_TO_RECOVERY__+ GROUP BY f.id, f.first_failure_at+ )+ ) AS restore+ CROSS JOIN (+ SELECT max(created_at) AS latest_status_at FROM __STATUSES_SOURCE__ AS ls+ ) AS freshness+"""++_FREQUENCY_SERIES_SELECT = """+ SELECT __BUCKET_FN__ AS bucket_start, count() AS deployment_count+ FROM deploys+ WHERE first_success_at IS NOT NULL AND first_success_at >= {date_from} __DATE_TO_SUCCESS__+ GROUP BY bucket_start+ LIMIT 40000+"""++# Each successful deployment's head merge time: the deploy's SHA is the merge commit of some+# merged PR, and that PR's merged_at says which merges the deploy contains. The sanctioned+# merge_commit_sha exception (SPEC §6): gated on merged_at (an open PR carries a throwaway+# test-merge SHA) and collapsed to one row per deployment (min breaks a shared-SHA tie).+# Deploys whose SHA is no PR's merge commit (direct pushes) resolve no head and attribute nothing.+# Bot merges stay in as heads on purpose: a bot's merge commit still names what a deploy contains.+_DEPLOY_HEADS_CTE = """+ deploy_heads AS (+ SELECT+ d.id AS id,+ any(d.first_success_at) AS first_success_at,+ min(hp.merged_at) AS head_merged_at+ FROM deploys AS d+ INNER JOIN __PR_SOURCE__ AS hp ON hp.merge_commit_sha = d.sha+ WHERE d.first_success_at IS NOT NULL+ AND d.sha != ''+ AND hp.merged_at IS NOT NULL+ AND hp.merged_at >= {merge_scan_floor}+ GROUP BY d.id+ )+"""++# Each merged PR's first successful deployment that CONTAINS it: the deploy's head merge is at or+# after the PR's merge. Ground-truthed against deploys whose SHA is exactly a PR's merge commit:+# this rule agrees on 99.7% of them with a 0-minute median error, where pairing on the deploy's+# success time instead picked an in-flight deploy built before the merge for roughly half.+# CROSS JOIN + the WHERE range condition is the attribution: HogQL joins take equality keys only,+# and the windowed populations are small enough that the pairing stays cheap. The locked+# cycle-time recipe applies (bots/drafts excluded).+_DEPLOYED_PRS_CTE = """+ deployed_prs AS (+ SELECT+ pr.number AS number,+ pr.merged_at AS merged_at,+ min(h.first_success_at) AS deployed_at+ FROM __PR_SOURCE__ AS pr+ CROSS JOIN deploy_heads AS h+ WHERE pr.merged_at IS NOT NULL+ AND pr.merged_at >= {merge_scan_floor}+ AND NOT pr.is_bot+ AND NOT pr.is_draft+ __TEAM_FILTER__+ AND h.head_merged_at >= pr.merged_at+ GROUP BY pr.number, pr.merged_at+ )+"""++_LEAD_TIME_INNER = "SELECT deployed_at, dateDiff('second', merged_at, deployed_at) AS lead_seconds FROM deployed_prs"++# The two one-row CROSS JOIN halves put attribution coverage on the same round trip: how many+# PRs merged in the window at all (same bot/draft/team recipe), and how many of those an+# in-scope deployment attributed — the honest denominator behind unattributed_merged_pr_share.+_LEAD_TIME_HEADLINE_SELECT = f"""+ SELECT+ lead.deployed_cur,+ lead.deployed_prev,+ lead.median_cur,+ lead.median_prev,+ attributed.attributed_cur,+ merged.merged_cur+ FROM (+ SELECT+ countIf(__CUR_DEPLOYED__) AS deployed_cur,+ countIf(__PREV_DEPLOYED__) AS deployed_prev,+ quantileIf(0.5)(lead_seconds, __CUR_DEPLOYED__) AS median_cur,+ quantileIf(0.5)(lead_seconds, __PREV_DEPLOYED__) AS median_prev+ FROM ({_LEAD_TIME_INNER})+ ) AS lead+ CROSS JOIN (+ SELECT countIf(__CUR_MERGED__) AS attributed_cur FROM deployed_prs+ ) AS attributed+ CROSS JOIN (+ SELECT countIf(__CUR_MERGED__) AS merged_cur+ FROM __PR_SOURCE__ AS pr+ WHERE pr.merged_at IS NOT NULL+ AND pr.merged_at >= {{merge_scan_floor}}+ AND NOT pr.is_bot+ AND NOT pr.is_draft+ __TEAM_FILTER__+ ) AS merged+"""++_LEAD_TIME_SERIES_SELECT = f"""+ SELECT+ __BUCKET_FN__ AS bucket_start,+ count() AS deployed_pr_count,+ min(lead_seconds) AS min_seconds,+ quantile(0.25)(lead_seconds) AS p25_seconds,+ quantile(0.5)(lead_seconds) AS p50_seconds,+ avg(lead_seconds) AS mean_seconds,+ quantile(0.75)(lead_seconds) AS p75_seconds,+ max(lead_seconds) AS max_seconds+ FROM ({_LEAD_TIME_INNER})+ WHERE deployed_at >= {{date_from}} __DATE_TO_DEPLOYED__+ GROUP BY bucket_start+ LIMIT 40000+"""++# Transient environments (ephemeral per-PR previews on this repo) are excluded from the picker+# options and the default scope: a busy repo deploys previews hundreds of times a week, which+# would swamp every deploy count. An exact ``environment`` filter can still reach one by name.+_ENVIRONMENTS_SELECT = f"""+ SELECT environment, max(is_production_environment) AS is_production, count() AS n+ FROM __DEPLOYMENTS_SOURCE__ AS d+ WHERE d.created_at >= {{prev_from}} AND NOT d.is_transient_environment __DATE_TO_CREATED__+ GROUP BY environment+ ORDER BY n DESC, environment ASC+ LIMIT {_ENVIRONMENTS_LIMIT}+"""++_TEAMS_SELECT = f"""+ SELECT DISTINCT team_slug+ FROM __MEMBERS_SOURCE__ AS m+ WHERE team_slug != ''+ ORDER BY team_slug ASC+ LIMIT {_TEAMS_LIMIT}+"""++_TEAM_FILTER = (+ "AND pr.author_handle IN (SELECT member_handle FROM __MEMBERS_SOURCE__ AS m WHERE m.team_slug = {github_team})"+)+++def _date_to_clause(date_to: datetime | None, column: str) -> str:+ """The optional window-end clause on ``column``; empty when the window is open-ended."""+ return f"AND {column} <= {{date_to}}" if date_to is not None else ""+++@frozen+class _EnvironmentScope:+ # 'production', 'persistent', or the exact environment the caller passed (see DoraOverview).+ scope: str+ # The trusted SQL predicate variant for the deploys CTE.+ predicate: str+++@frozen+class _DoraScan:+ """One request's bound scan state — the curated handle, the environment-scoped deploys CTE,+ the shared placeholder registry, and the window — composed by every deploy sub-query."""++ curated: CuratedGitHubSource+ deploys_cte: str+ statuses_source: str+ placeholders: dict[str, ast.Expr]+ date_from: datetime+ date_to: datetime | None+ granularity: Granularity++ def run(self, sql: str, *, query_type: str) -> HogQLQueryResponse:+ return self.curated.run(sql, query_type=query_type, placeholders=self.placeholders)++ def date_to_filter(self, column: str) -> str:+ return _date_to_clause(self.date_to, column)++ def window_buckets(self) -> list[datetime]:+ return window_buckets(self.date_from, self.date_to, self.granularity)+++def _resolve_environment_scope(environment: str | None, environments: list[tuple[str, bool]]) -> _EnvironmentScope:+ """Pick the deploy population: the caller's exact environment when given; otherwise the+ deployments GitHub marks production; otherwise the single busiest persistent environment,+ so a repo that never sets the production flag still gets numbers instead of a false zero.+ Busiest-single, not every-persistent: a multi-region repo deploys each merge to several+ persistent environments (and to dev, package registries, ...), which would multiply every+ deploy count and hand lead time to whichever region deploys first. 'persistent' survives+ only when the window has no persistent environment at all. Transient environments never+ join a default scope: they are ephemeral per-PR previews, and on this repo they outnumber+ real deploys by an order of magnitude."""+ if environment:+ return _EnvironmentScope(scope=environment, predicate="d.environment = {environment}")+ if any(is_production for _, is_production in environments):+ return _EnvironmentScope(scope="production", predicate="d.is_production_environment")+ if environments:+ return _EnvironmentScope(scope=environments[0][0], predicate="d.environment = {environment}")+ return _EnvironmentScope(scope="persistent", predicate="NOT d.is_transient_environment")+++def _empty_overview(+ *,+ deploy_data_available: bool,+ environment_scope: str,+ environments: list[str],+ has_membership_data: bool,+ github_teams: list[str],+ granularity: Granularity,+) -> DoraOverview:+ return DoraOverview(+ deploy_data_available=deploy_data_available,+ environment_scope=environment_scope,+ environments=environments,+ has_membership_data=has_membership_data,+ github_teams=github_teams,+ deployment_count=0,+ deployment_count_prev=0,+ deployments_per_day=None,+ deployments_per_day_prev=None,+ median_merge_to_deploy_seconds=None,+ median_merge_to_deploy_seconds_prev=None,+ deployed_pr_count=0,+ deployed_pr_count_prev=0,+ failed_deployment_count=0,+ failed_deployment_count_prev=0,+ failed_deployment_share=None,+ failed_deployment_share_prev=None,+ median_failed_deploy_to_next_success_seconds=None,+ median_failed_deploy_to_next_success_seconds_prev=None,+ merged_pr_count=0,+ unattributed_merged_pr_share=None,+ latest_deploy_status_at=None,+ deployment_frequency_series=[],+ merge_to_deploy_series=[],+ series_granularity=granularity,+ )+++@frozen+class _DeployOutcomes:+ """Deploy outcome counts and the restore-proxy medians over the window pair, straight off+ the deploys rollup."""++ deployment_count: int+ deployment_count_prev: int+ failed_count: int+ failed_count_prev: int+ outcome_count: int+ outcome_count_prev: int+ # Median failed-deploy-to-next-success seconds (the restore proxy); None when nothing recovered.+ restore_median_seconds: float | None+ restore_median_seconds_prev: float | None+ # The newest status row synced, any environment — how fresh the deploy data is.+ latest_status_at: datetime | None++ @property+ def failed_share(self) -> float | None:+ return self.failed_count / self.outcome_count if self.outcome_count else None++ @property+ def failed_share_prev(self) -> float | None:+ return self.failed_count_prev / self.outcome_count_prev if self.outcome_count_prev else None+++def _query_deploy_outcomes(scan: _DoraScan) -> _DeployOutcomes:+ success = window_pair_predicates("first_success_at", date_to=scan.date_to)+ failure = window_pair_predicates("first_failure_at", date_to=scan.date_to)+ sql = f"WITH {scan.deploys_cte} " + (+ _OUTCOMES_SELECT.replace("__CUR_SUCCESS__", success.current)+ .replace("__PREV_SUCCESS__", success.previous)+ .replace("__CUR_FAILURE__", failure.current)+ .replace("__PREV_FAILURE__", failure.previous)+ .replace("__DATE_TO_RECOVERY__", scan.date_to_filter("r.first_success_at"))+ .replace("__STATUSES_SOURCE__", scan.statuses_source)+ )+ response = scan.run(sql, query_type="engineering_analytics.dora_deploys")+ deploy_count, deploy_count_prev, failed, failed_prev, outcome, outcome_prev, restore_cur, restore_prev, latest = (+ response.results[0] if response.results else (0, 0, 0, 0, 0, 0, None, None, None)+ )+ return _DeployOutcomes(+ deployment_count=int(deploy_count or 0),+ deployment_count_prev=int(deploy_count_prev or 0),+ failed_count=int(failed or 0),+ failed_count_prev=int(failed_prev or 0),+ outcome_count=int(outcome or 0),+ outcome_count_prev=int(outcome_prev or 0),+ restore_median_seconds=opt_float(restore_cur),+ restore_median_seconds_prev=opt_float(restore_prev),+ latest_status_at=latest if isinstance(latest, datetime) else None,+ )+++def _query_frequency_series(scan: _DoraScan) -> list[DeploymentFrequencyBucket]:+ """Successful deployments per bucket across the window, oldest first, zero-filled."""+ sql = f"WITH {scan.deploys_cte} " + (+ _FREQUENCY_SERIES_SELECT.replace("__BUCKET_FN__", bucket_expr(scan.granularity, "first_success_at")).replace(+ "__DATE_TO_SUCCESS__", scan.date_to_filter("first_success_at")+ )+ )+ response = scan.run(sql, query_type="engineering_analytics.dora_frequency")+ count_by_bucket = {+ normalize_bucket(bucket_start, scan.granularity): int(count or 0)+ for bucket_start, count in response.results or []+ }+ return [+ DeploymentFrequencyBucket(bucket_start=bucket, deployment_count=count_by_bucket.get(bucket, 0))+ for bucket in scan.window_buckets()+ ]+++@frozen+class _LeadTime:+ """The PR-scoped merge-to-deploy figures: window-pair counts and medians, attribution+ coverage, plus the box-plot series."""++ deployed_count: int+ deployed_count_prev: int+ median_seconds: float | None+ median_seconds_prev: float | None+ # PRs merged in the window (the locked recipe), and how many of those a deploy attributed.+ merged_count: int+ attributed_count: int+ series: list[MergeToDeployBucket]++ @property+ def unattributed_share(self) -> float | None:+ return 1 - self.attributed_count / self.merged_count if self.merged_count else None+++_EMPTY_LEAD_TIME = _LeadTime(+ deployed_count=0,+ deployed_count_prev=0,+ median_seconds=None,+ median_seconds_prev=None,+ merged_count=0,+ attributed_count=0,+ series=[],+)+++def _query_lead_time(scan: _DoraScan, *, github_team: str | None, members_source: str | None) -> _LeadTime:+ # A team filter without membership data cannot be honored: empty lead-time figures, never+ # silently unfiltered ones.+ if github_team and members_source is None:+ return _EMPTY_LEAD_TIME+ team_filter = ""+ if github_team and members_source is not None:+ scan.placeholders["github_team"] = ast.Constant(value=github_team)+ team_filter = _TEAM_FILTER.replace("__MEMBERS_SOURCE__", members_source)+ pr_source = scan.curated.pr_source()+ attribution_ctes = f"{scan.deploys_cte}, {_DEPLOY_HEADS_CTE}, {_DEPLOYED_PRS_CTE}".replace(+ "__PR_SOURCE__", pr_source+ ).replace("__TEAM_FILTER__", team_filter)++ windows = window_pair_predicates("deployed_at", date_to=scan.date_to)+ merged_window = window_pair_predicates("merged_at", date_to=scan.date_to)+ headline_sql = f"WITH {attribution_ctes} " + (+ _LEAD_TIME_HEADLINE_SELECT.replace("__CUR_DEPLOYED__", windows.current)+ .replace("__PREV_DEPLOYED__", windows.previous)+ .replace("__CUR_MERGED__", merged_window.current)+ .replace("__PR_SOURCE__", pr_source)+ .replace("__TEAM_FILTER__", team_filter)+ )+ headline = scan.run(headline_sql, query_type="engineering_analytics.dora_lead_time")+ deployed_cur, deployed_prev, median_cur, median_prev, attributed_cur, merged_cur = (+ headline.results[0] if headline.results else (0, 0, None, None, 0, 0)+ )++ series_sql = f"WITH {attribution_ctes} " + (+ _LEAD_TIME_SERIES_SELECT.replace("__BUCKET_FN__", bucket_expr(scan.granularity, "deployed_at")).replace(+ "__DATE_TO_DEPLOYED__", scan.date_to_filter("deployed_at")+ )+ )+ rows = scan.run(series_sql, query_type="engineering_analytics.dora_lead_time_series")+ stats_by_bucket = {normalize_bucket(row[0], scan.granularity): row[1:] for row in (rows.results or [])}+ return _LeadTime(+ deployed_count=int(deployed_cur or 0),+ deployed_count_prev=int(deployed_prev or 0),+ median_seconds=opt_float(median_cur),+ median_seconds_prev=opt_float(median_prev),+ merged_count=int(merged_cur or 0),+ attributed_count=int(attributed_cur or 0),+ series=[_lead_time_bucket(bucket, stats_by_bucket.get(bucket)) for bucket in scan.window_buckets()],+ )+++def query_dora_overview(+ *,+ curated: CuratedGitHubSource,+ date_from: datetime,+ date_to: datetime | None,+ environment: str | None = None,+ github_team: str | None = None,+) -> DoraOverview:+ granularity = 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=environment or "persistent",+ environments=[],+ has_membership_data=has_membership_data,+ github_teams=github_teams,+ granularity=granularity,+ )++ 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),+ "prev_from": ast.Constant(value=prev_from),+ "deploy_scan_floor": ast.Constant(value=prev_from - _DEPLOY_SCAN_SLACK),+ "merge_scan_floor": ast.Constant(value=prev_from - _MERGE_SCAN_LOOKBACK),+ }+ if date_to is not None:+ placeholders["date_to"] = ast.Constant(value=date_to)++ environments = _query_environments(+ curated,+ deploy_sources.deployments,+ placeholders=placeholders,+ date_to_filter=_date_to_clause(date_to, "d.created_at"),+ )+ env_scope = _resolve_environment_scope(environment, environments)+ # The busiest-environment fallback binds the same placeholder as an explicit filter: either+ # way the scope string IS the environment the predicate matches.+ if "{environment}" in env_scope.predicate:+ placeholders["environment"] = ast.Constant(value=env_scope.scope)++ scan = _DoraScan(+ curated=curated,+ deploys_cte=(+ _DEPLOYS_CTE.replace("__DEPLOYMENTS_SOURCE__", deploy_sources.deployments)+ .replace("__STATUSES_SOURCE__", deploy_sources.statuses)+ .replace("__ENV_PREDICATE__", env_scope.predicate)+ ),+ statuses_source=deploy_sources.statuses,+ placeholders=placeholders,+ date_from=date_from,+ date_to=date_to,+ granularity=granularity,+ )+ outcomes = _query_deploy_outcomes(scan)+ lead = _query_lead_time(scan, github_team=github_team, members_source=members_source)++ return DoraOverview(+ deploy_data_available=True,+ environment_scope=env_scope.scope,+ environments=[name for name, _ in environments],+ has_membership_data=has_membership_data,+ github_teams=github_teams,+ deployment_count=outcomes.deployment_count,+ deployment_count_prev=outcomes.deployment_count_prev,+ deployments_per_day=outcomes.deployment_count / window_days,+ deployments_per_day_prev=outcomes.deployment_count_prev / window_days,+ median_merge_to_deploy_seconds=lead.median_seconds,+ median_merge_to_deploy_seconds_prev=lead.median_seconds_prev,+ deployed_pr_count=lead.deployed_count,+ deployed_pr_count_prev=lead.deployed_count_prev,+ failed_deployment_count=outcomes.failed_count,+ failed_deployment_count_prev=outcomes.failed_count_prev,+ failed_deployment_share=outcomes.failed_share,+ failed_deployment_share_prev=outcomes.failed_share_prev,+ median_failed_deploy_to_next_success_seconds=outcomes.restore_median_seconds,+ median_failed_deploy_to_next_success_seconds_prev=outcomes.restore_median_seconds_prev,+ merged_pr_count=lead.merged_count,+ unattributed_merged_pr_share=lead.unattributed_share,+ latest_deploy_status_at=outcomes.latest_status_at,+ deployment_frequency_series=_query_frequency_series(scan),+ merge_to_deploy_series=lead.series,+ series_granularity=granularity,+ )+++def _lead_time_bucket(bucket: datetime, stats: tuple[Any, Any, Any, Any, Any, Any, Any] | None) -> MergeToDeployBucket:+ if not stats:+ return MergeToDeployBucket(+ bucket_start=bucket,+ deployed_pr_count=0,+ min_seconds=None,+ p25_seconds=None,+ p50_seconds=None,+ mean_seconds=None,+ p75_seconds=None,+ max_seconds=None,+ )+ n, min_s, p25, p50, mean, p75, max_s = stats+ return MergeToDeployBucket(+ bucket_start=bucket,+ deployed_pr_count=int(n or 0),+ min_seconds=opt_float(min_s),+ p25_seconds=opt_float(p25),+ p50_seconds=opt_float(p50),+ mean_seconds=opt_float(mean),+ p75_seconds=opt_float(p75),+ max_seconds=opt_float(max_s),+ )+++def _query_environments(+ curated: CuratedGitHubSource,+ deployments_source: str,+ *,+ placeholders: dict[str, ast.Expr],+ date_to_filter: str,+) -> list[tuple[str, bool]]:+ """``(environment, is_production)`` pairs deployed to in the scan window, most-deployed first."""+ sql = _ENVIRONMENTS_SELECT.replace("__DEPLOYMENTS_SOURCE__", deployments_source).replace(+ "__DATE_TO_CREATED__", date_to_filter+ )+ response = curated.run(sql, query_type="engineering_analytics.dora_environments", placeholders=placeholders)+ return [(str(name), bool(is_production)) for name, is_production, _ in (response.results or []) if name]+++def _query_github_teams(curated: CuratedGitHubSource, members_source: str | None) -> list[str]:+ """Distinct GitHub team slugs from the membership snapshot — the team filter's options."""+ if members_source is None:+ return []+ response = curated.run(+ _TEAMS_SELECT.replace("__MEMBERS_SOURCE__", members_source),+ query_type="engineering_analytics.dora_github_teams",+ )+ return [str(slug) for (slug,) in (response.results or []) if slug]diff --git a/products/engineering_analytics/backend/logic/queries/repo_overview.py b/products/engineering_analytics/backend/logic/queries/repo_overview.pyindex 1235c1a6b7b2..00a3b9f1affb 100644--- a/products/engineering_analytics/backend/logic/queries/repo_overview.py+++ b/products/engineering_analytics/backend/logic/queries/repo_overview.py@@ -18,6 +18,8 @@ from datetime import datetimefrom posthog.hogql import ast+from posthog.dataclasses import frozen+from products.engineering_analytics.backend.facade.contracts import (CostPerMergeBucket,OpenToMergeBucket,@@ -43,6 +45,7 @@ from products.engineering_analytics.backend.logic.queries.merge_queue_overview iquery_merge_queue_trunk_outcomes,)from products.engineering_analytics.backend.logic.queries.pr_cost import (+ WindowCostsWithPrev,query_cost_per_merge_series,query_workflow_window_costs_with_prev,)@@ -327,18 +330,28 @@ def empty_repo_series(*, date_from: datetime, date_to: datetime | None) -> RepoS)-def query_repo_overview(+@frozen+class _RunHeadlines:+ """The runs scan's window-pair aggregates plus the observed default branch."""++ run_count: int+ run_count_prev: int+ success_rate: float | None+ success_rate_prev: float | None+ rerun_cycles: int+ rerun_cycles_prev: int+ default_branch: str+++def _query_run_headlines(*,curated: CuratedGitHubSource,date_from: datetime,date_to: datetime | None,- series: RepoSeries,-) -> RepoOverview:- end = date_to or datetime.now(tz=date_from.tzinfo)- prev_from = date_from - (end - date_from)+ prev_from: datetime,+) -> _RunHeadlines:date_to_clause = "AND run_started_at <= {date_to}" if date_to is not None else ""- run_windows = window_pair_predicates("run_started_at", date_to=date_to)-+ windows = window_pair_predicates("run_started_at", date_to=date_to)placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from),"prev_from": ast.Constant(value=prev_from),@@ -348,77 +361,157 @@ def query_repo_overview(}if date_to is not None:placeholders["date_to"] = ast.Constant(value=date_to)-- runs_sql = (- _RUNS_SELECT.replace("__CUR__", run_windows.current)- .replace("__PREV__", run_windows.previous)+ sql = (+ _RUNS_SELECT.replace("__CUR__", windows.current)+ .replace("__PREV__", windows.previous).replace("__RUNS_SOURCE__", curated.run_source(started_floor=True)).replace("__DATE_TO__", date_to_clause))- runs_response = curated.run(- runs_sql, query_type="engineering_analytics.repo_overview_runs", placeholders=placeholders- )- row = runs_response.results[0] if runs_response.results else (0, 0, None, None, 0, 0, 0, 0)+ response = curated.run(sql, query_type="engineering_analytics.repo_overview_runs", placeholders=placeholders)+ row = response.results[0] if response.results else (0, 0, None, None, 0, 0, 0, 0)run_count, run_count_prev, success_rate, success_rate_prev, reruns, reruns_prev, master_runs, main_runs = row- default_branch = "main" if (main_runs or 0) > (master_runs or 0) else "master"+ return _RunHeadlines(+ run_count=run_count,+ run_count_prev=run_count_prev,+ success_rate=opt_float(success_rate),+ success_rate_prev=opt_float(success_rate_prev),+ rerun_cycles=reruns,+ rerun_cycles_prev=reruns_prev,+ default_branch="main" if (main_runs or 0) > (master_runs or 0) else "master",+ )- merge_windows = window_pair_predicates("merged_at", date_to=date_to)++@frozen+class _MergeHeadlines:+ """The PR scan's window-pair merge medians (the locked cycle-time recipe) and merge counts."""++ median_open_to_merge_seconds: float | None+ median_open_to_merge_seconds_prev: float | None+ median_ready_to_merge_seconds: float | None+ median_ready_to_merge_seconds_prev: float | None+ merged_count: int+ merged_count_prev: int+++def _query_merge_headlines(+ *,+ curated: CuratedGitHubSource,+ date_from: datetime,+ date_to: datetime | None,+ prev_from: datetime,+) -> _MergeHeadlines:+ windows = window_pair_predicates("merged_at", date_to=date_to)ready = curated.ready_to_merge_sql()- pr_sql = ready.with_clause + (- _PR_SELECT.replace("__READY_MEDIAN_CUR__", ready.median(scope=f"{merge_windows.current} AND {_HUMAN_MERGES}"))- .replace("__READY_MEDIAN_PREV__", ready.median(scope=f"{merge_windows.previous} AND {_HUMAN_MERGES}"))+ placeholders: dict[str, ast.Expr] = {+ "date_from": ast.Constant(value=date_from),+ "prev_from": ast.Constant(value=prev_from),+ }+ if date_to is not None:+ placeholders["date_to"] = ast.Constant(value=date_to)+ sql = ready.with_clause + (+ _PR_SELECT.replace("__READY_MEDIAN_CUR__", ready.median(scope=f"{windows.current} AND {_HUMAN_MERGES}"))+ .replace("__READY_MEDIAN_PREV__", ready.median(scope=f"{windows.previous} AND {_HUMAN_MERGES}")).replace("__READY_JOIN__", ready.join)- .replace("__CUR_MERGED__", merge_windows.current)- .replace("__PREV_MERGED__", merge_windows.previous)+ .replace("__CUR_MERGED__", windows.current)+ .replace("__PREV_MERGED__", windows.previous).replace("__PR_SOURCE__", curated.pr_source()))- pr_response = curated.run(pr_sql, query_type="engineering_analytics.repo_overview_prs", placeholders=placeholders)- median_cur, median_prev, ready_median_cur, ready_median_prev, merged_cur, merged_prev = (- pr_response.results[0] if pr_response.results else (None, None, None, None, 0, 0)- )-- jobs_available = curated.jobs_source() is not None- queue = query_merge_queue_overview(curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from)- trunk = query_merge_queue_trunk_outcomes(curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from)- time_to_green = query_time_to_green_window(- curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from+ response = curated.run(sql, query_type="engineering_analytics.repo_overview_prs", placeholders=placeholders)+ median_cur, median_prev, ready_cur, ready_prev, merged_cur, merged_prev = (+ response.results[0] if response.results else (None, None, None, None, 0, 0))- costs = query_workflow_window_costs_with_prev(- curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from+ return _MergeHeadlines(+ median_open_to_merge_seconds=opt_float(median_cur),+ median_open_to_merge_seconds_prev=opt_float(median_prev),+ median_ready_to_merge_seconds=opt_float(ready_cur),+ median_ready_to_merge_seconds_prev=opt_float(ready_prev),+ merged_count=int(merged_cur or 0),+ merged_count_prev=int(merged_prev or 0),)+++@frozen+class _CostHeadlines:+ """The window-pair cost rollup derived from the per-workflow cost scan."""++ billable_minutes: float | None+ billable_minutes_prev: float | None+ estimated_cost_usd: float | None+ estimated_cost_usd_prev: float | None+ cost_per_merge_usd: float | None+ cost_per_merge_usd_prev: float | None+ merge_queue_billable_minutes: float | None+ merge_queue_billable_minutes_prev: float | None+++def _derive_cost_headlines(costs: WindowCostsWithPrev, *, merged_count: int, merged_count_prev: int) -> _CostHeadlines:cost_cur, cost_prev = costs.by_workflow, costs.by_workflow_prev# Per-workflow figures can be None (billable time on an unknown tier) — sum what's known.billable_seconds = sum(c.billable_seconds or 0.0 for c in cost_cur.values()) if cost_cur else Nonebillable_seconds_prev = sum(c.billable_seconds or 0.0 for c in cost_prev.values()) if cost_prev else Nonecost_usd = sum(c.estimated_cost_usd or 0.0 for c in cost_cur.values()) if cost_cur else Nonecost_usd_prev = sum(c.estimated_cost_usd or 0.0 for c in cost_prev.values()) if cost_prev else None- # The queue slice mirrors billable_minutes' null gating so both go null together.- queue_minutes = costs.merge_queue_billable_seconds / 60 if cost_cur else None- queue_minutes_prev = costs.merge_queue_billable_seconds_prev / 60 if cost_prev else None- cost_per_merge = cost_usd / int(merged_cur) if cost_usd is not None and merged_cur else None- cost_per_merge_prev = cost_usd_prev / int(merged_prev) if cost_usd_prev is not None and merged_prev else None-- return RepoOverview(- run_count=run_count,- run_count_prev=run_count_prev,- success_rate=opt_float(success_rate),- success_rate_prev=opt_float(success_rate_prev),- rerun_cycles=reruns,- rerun_cycles_prev=reruns_prev,- merged_pr_count=int(merged_cur or 0),- merged_pr_count_prev=int(merged_prev or 0),- median_open_to_merge_seconds=opt_float(median_cur),- median_open_to_merge_seconds_prev=opt_float(median_prev),- median_ready_to_merge_seconds=opt_float(ready_median_cur),- median_ready_to_merge_seconds_prev=opt_float(ready_median_prev),+ return _CostHeadlines(billable_minutes=billable_seconds / 60 if billable_seconds is not None else None,billable_minutes_prev=billable_seconds_prev / 60 if billable_seconds_prev is not None else None,estimated_cost_usd=opt_float(cost_usd),estimated_cost_usd_prev=opt_float(cost_usd_prev),- cost_per_merge_usd=opt_float(cost_per_merge),- cost_per_merge_usd_prev=opt_float(cost_per_merge_prev),- merge_queue_billable_minutes=queue_minutes,- merge_queue_billable_minutes_prev=queue_minutes_prev,+ cost_per_merge_usd=opt_float(cost_usd / merged_count) if cost_usd is not None and merged_count else None,+ cost_per_merge_usd_prev=opt_float(cost_usd_prev / merged_count_prev)+ if cost_usd_prev is not None and merged_count_prev+ else None,+ # The queue slice mirrors billable_minutes' null gating so both go null together.+ merge_queue_billable_minutes=costs.merge_queue_billable_seconds / 60 if cost_cur else None,+ merge_queue_billable_minutes_prev=costs.merge_queue_billable_seconds_prev / 60 if cost_prev else None,+ )+++def query_repo_overview(+ *,+ curated: CuratedGitHubSource,+ date_from: datetime,+ date_to: datetime | None,+ series: RepoSeries,+) -> RepoOverview:+ end = date_to or datetime.now(tz=date_from.tzinfo)+ prev_from = date_from - (end - date_from)++ runs = _query_run_headlines(curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from)+ merges = _query_merge_headlines(curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from)+ queue = query_merge_queue_overview(curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from)+ trunk = query_merge_queue_trunk_outcomes(curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from)+ time_to_green = query_time_to_green_window(+ curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from+ )+ costs = _derive_cost_headlines(+ query_workflow_window_costs_with_prev(+ curated=curated, date_from=date_from, date_to=date_to, prev_from=prev_from+ ),+ merged_count=merges.merged_count,+ merged_count_prev=merges.merged_count_prev,+ )++ return RepoOverview(+ run_count=runs.run_count,+ run_count_prev=runs.run_count_prev,+ success_rate=runs.success_rate,+ success_rate_prev=runs.success_rate_prev,+ rerun_cycles=runs.rerun_cycles,+ rerun_cycles_prev=runs.rerun_cycles_prev,+ merged_pr_count=merges.merged_count,+ merged_pr_count_prev=merges.merged_count_prev,+ median_open_to_merge_seconds=merges.median_open_to_merge_seconds,+ median_open_to_merge_seconds_prev=merges.median_open_to_merge_seconds_prev,+ median_ready_to_merge_seconds=merges.median_ready_to_merge_seconds,+ median_ready_to_merge_seconds_prev=merges.median_ready_to_merge_seconds_prev,+ billable_minutes=costs.billable_minutes,+ billable_minutes_prev=costs.billable_minutes_prev,+ estimated_cost_usd=costs.estimated_cost_usd,+ estimated_cost_usd_prev=costs.estimated_cost_usd_prev,+ cost_per_merge_usd=costs.cost_per_merge_usd,+ cost_per_merge_usd_prev=costs.cost_per_merge_usd_prev,+ merge_queue_billable_minutes=costs.merge_queue_billable_minutes,+ merge_queue_billable_minutes_prev=costs.merge_queue_billable_minutes_prev,merge_queue_merged_pr_count=queue.merged_pr_count,merge_queue_merged_pr_count_prev=queue.merged_pr_count_prev,merge_queue_median_first_gate_to_merge_seconds=queue.median_first_gate_to_merge_seconds,@@ -442,8 +535,8 @@ def query_repo_overview(merge_queue_skip_the_line_count_prev=trunk.skip_the_line_count_prev,median_time_to_green_seconds=time_to_green.median_seconds,median_time_to_green_seconds_prev=time_to_green.median_seconds_prev,- jobs_available=jobs_available,- default_branch=default_branch,+ jobs_available=curated.jobs_source() is not None,+ default_branch=runs.default_branch,cost_series=series.cost,cost_series_granularity=series.granularity,time_to_green_series=series.time_to_green,diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.pyindex e4d95d3932d4..6965beed8d8a 100644--- a/products/engineering_analytics/backend/logic/sources.py+++ b/products/engineering_analytics/backend/logic/sources.py@@ -52,11 +52,24 @@ TEAM_MEMBERS_SCHEMA = "team_members"# Immutable issue/PR events, the substrate for ready-to-merge timing. Optional at the source,# so reads must degrade gracefully (no transition data) exactly like workflow_jobs.ISSUE_EVENTS_SCHEMA = "issue_events"+# Deploy requests and their append-oriented status history, the DORA substrate. Both are+# optional at the source and only useful together (a deployment without statuses never+# succeeded or failed), so reads must degrade gracefully when either is unsynced.+DEPLOYMENTS_SCHEMA = "deployments"+DEPLOYMENT_STATUSES_SCHEMA = "deployment_statuses"# The curated endpoints we resolve per repo. A source's other synced endpoints (issues, commits,# teams, …) are irrelevant to the CI/PR read layer and dropped during grouping._CURATED_ENDPOINTS = frozenset(- {PULL_REQUESTS_SCHEMA, WORKFLOW_RUNS_SCHEMA, WORKFLOW_JOBS_SCHEMA, TEAM_MEMBERS_SCHEMA, ISSUE_EVENTS_SCHEMA}+ {+ PULL_REQUESTS_SCHEMA,+ WORKFLOW_RUNS_SCHEMA,+ WORKFLOW_JOBS_SCHEMA,+ TEAM_MEMBERS_SCHEMA,+ ISSUE_EVENTS_SCHEMA,+ DEPLOYMENTS_SCHEMA,+ DEPLOYMENT_STATUSES_SCHEMA,+ })# Resolved names are interpolated into HogQL ``FROM`` clauses. Warehouse table names are@@ -78,6 +91,10 @@ class GitHubTables:team_members: str | None = None# Optional: present only once issue events are synced; None means "no transition data".issue_events: str | None = None+ # Optional pair: present only once deploys are synced; None means "no deploy data". Only+ # useful together, so consumers gate on both.+ deployments: str | None = None+ deployment_statuses: str | None = None# Used to scope cross-store reads such as CI traces to the selected source's repository.repository: str = ""@@ -147,6 +164,8 @@ def resolve_github_tables(workflow_jobs=tables.get(WORKFLOW_JOBS_SCHEMA),team_members=tables.get(TEAM_MEMBERS_SCHEMA),issue_events=tables.get(ISSUE_EVENTS_SCHEMA),+ deployments=tables.get(DEPLOYMENTS_SCHEMA),+ deployment_statuses=tables.get(DEPLOYMENT_STATUSES_SCHEMA),repository=candidate.repository,)if source_id is not None:diff --git a/products/engineering_analytics/backend/logic/views/deployments.py b/products/engineering_analytics/backend/logic/views/deployments.pynew file mode 100644index 000000000000..76e7eb076b35--- /dev/null+++ b/products/engineering_analytics/backend/logic/views/deployments.py@@ -0,0 +1,41 @@+"""Curated deployments and deployment-statuses query builders.++Maps the raw GitHub deploy snapshots (the ``deployments`` webhook feed and its+``deployment_statuses`` fan-out) into query-able columns. A deployment row is the+*request* to deploy a SHA to an environment; its outcome lives entirely in the+status rows (one per transition: pending → in_progress → success/failure/error,+plus the ``inactive`` a later deploy or rollback marks it with). The DORA reads+therefore always join the two — a deployment with no status rows has no outcome.++Same source discipline as every builder here: table names are resolved per team+(``logic.sources``), timestamps land as strings and parse via+``parseDateTimeBestEffort``, Nullable columns are ``ifNull``-guarded before use+(see ``source_schema``).+"""+++def build_deployments_query(table_name: str) -> str:+ return f"""+ SELECT+ id,+ ifNull(sha, '') AS sha,+ ifNull(ref, '') AS ref,+ ifNull(environment, '') AS environment,+ coalesce(production_environment, false) AS is_production_environment,+ coalesce(transient_environment, false) AS is_transient_environment,+ parseDateTimeBestEffort(created_at) AS created_at,+ parseDateTimeBestEffort(updated_at) AS updated_at+ FROM {table_name}+ """+++def build_deployment_statuses_query(table_name: str) -> str:+ return f"""+ SELECT+ id,+ deployment_id,+ ifNull(state, '') AS state,+ ifNull(environment, '') AS environment,+ parseDateTimeBestEffort(created_at) AS created_at+ FROM {table_name}+ """diff --git a/products/engineering_analytics/backend/logic/views/pull_requests.py b/products/engineering_analytics/backend/logic/views/pull_requests.pyindex 9426b41d7281..4eb71191280a 100644--- a/products/engineering_analytics/backend/logic/views/pull_requests.py+++ b/products/engineering_analytics/backend/logic/views/pull_requests.py@@ -69,6 +69,7 @@ def build_query(table_name: str) -> str:updated_at,merged_at,closed_at,+ merge_commit_sha,head_sha,head_branch,base_branch,@@ -99,7 +100,10 @@ def build_query(table_name: str) -> str:parseDateTimeBestEffort(created_at) AS created_at,parseDateTimeBestEffort(updated_at) AS updated_at,parseDateTimeBestEffort(merged_at) AS merged_at,- parseDateTimeBestEffort(closed_at) AS closed_at+ parseDateTimeBestEffort(closed_at) AS closed_at,+ -- Terminal only on a merged PR; on an open PR GitHub fills it with a throwaway+ -- test-merge commit, so every read joining on it must gate on merged_at.+ ifNull(merge_commit_sha, '') AS merge_commit_shaFROM {table_name})WHERE NOT {merge_queue_branch_expr("head_branch", queue_actor_column="author_handle")}diff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.pyindex 13be0d274a78..9d74e8ca97ac 100644--- a/products/engineering_analytics/backend/logic/views/source_schema.py+++ b/products/engineering_analytics/backend/logic/views/source_schema.py@@ -110,6 +110,43 @@ TEAM_MEMBERS_COLUMNS: dict[str, dict[str, str]] = {"team_name": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},}+# Contract for the ``github_deployments`` warehouse source: one row per deploy request (a SHA+# aimed at an environment), webhook-fed. The outcome lives on the status children below, so the+# DORA reads always join the two. Same Nullable/string discipline as above.+DEPLOYMENTS_COLUMNS: dict[str, dict[str, str]] = {+ "id": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},+ "sha": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "ref": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "task": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "environment": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "original_environment": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "description": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "creator": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "payload": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "production_environment": {"clickhouse": "Nullable(Bool)", "hogql": "BooleanDatabaseField"},+ "transient_environment": {"clickhouse": "Nullable(Bool)", "hogql": "BooleanDatabaseField"},+ "created_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "updated_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+}++# Contract for the ``github_deployment_statuses`` warehouse source: one row per status transition+# of a deployment (pending / in_progress / queued / success / failure / error / inactive), with the+# parent's id injected by the source fan-out. Append-oriented — the transition history is what the+# DORA change-failure and restore proxies read. Same Nullable/string discipline as above.+DEPLOYMENT_STATUSES_COLUMNS: dict[str, dict[str, str]] = {+ "id": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},+ "deployment_id": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},+ "state": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "creator": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "description": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "environment": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "target_url": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "log_url": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "environment_url": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "created_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ "updated_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+}+# The Trunk merge-queue snapshot (TrunkIo source, opt-in MergeQueuePullRequests endpoint): one row# per queue entry with the state it last reached. Trunk keeps no state history, so# ``state_changed_at`` is the entry's last transition, not a timeline. Typed by the trunk_iodiff --git a/products/engineering_analytics/backend/presentation/serializers/dora.py b/products/engineering_analytics/backend/presentation/serializers/dora.pynew file mode 100644index 000000000000..35cd65da0e21--- /dev/null+++ b/products/engineering_analytics/backend/presentation/serializers/dora.py@@ -0,0 +1,180 @@+"""Payloads for the DORA deploy-metrics read."""++from rest_framework_dataclasses.serializers import DataclassSerializer++from products.engineering_analytics.backend.facade.contracts import (+ DeploymentFrequencyBucket,+ DoraOverview,+ MergeToDeployBucket,+)+++class DeploymentFrequencyBucketSerializer(DataclassSerializer):+ class Meta:+ dataclass = DeploymentFrequencyBucket+ extra_kwargs = {+ "bucket_start": {+ "help_text": "Bucket start, aligned to series_granularity (top of hour, midnight, or Monday)."+ },+ "deployment_count": {+ "help_text": "Deployments whose first success status landed in this bucket, within the "+ "environment scope. Zero-filled: 0 means nothing shipped."+ },+ }+++class MergeToDeployBucketSerializer(DataclassSerializer):+ class Meta:+ dataclass = MergeToDeployBucket+ extra_kwargs = {+ "bucket_start": {+ "help_text": "Bucket start, aligned to series_granularity (top of hour, midnight, or Monday). "+ "Keyed on deploy time: a PR lands in the bucket its first post-merge deploy succeeded in."+ },+ "deployed_pr_count": {+ "help_text": "PRs whose first post-merge successful deployment landed in this bucket "+ "(bots and drafts excluded; narrowed by github_team when given)."+ },+ "min_seconds": {+ "help_text": "Fastest merge-to-deploy in this bucket, in seconds. Null when nothing deployed.",+ "allow_null": True,+ },+ "p25_seconds": {+ "help_text": "25th percentile merge-to-deploy seconds. Null when nothing deployed.",+ "allow_null": True,+ },+ "p50_seconds": {+ "help_text": "Median merge-to-deploy seconds. Null when nothing deployed.",+ "allow_null": True,+ },+ "mean_seconds": {+ "help_text": "Mean merge-to-deploy seconds. Null when nothing deployed.",+ "allow_null": True,+ },+ "p75_seconds": {+ "help_text": "75th percentile merge-to-deploy seconds. Null when nothing deployed.",+ "allow_null": True,+ },+ "max_seconds": {+ "help_text": "Slowest merge-to-deploy in this bucket, in seconds. Null when nothing deployed.",+ "allow_null": True,+ },+ }+++class DoraOverviewSerializer(DataclassSerializer):+ deployment_frequency_series = DeploymentFrequencyBucketSerializer(+ many=True,+ help_text="Successful deployments per bucket across the window, oldest first, zero-filled, "+ "bucketed by series_granularity. Empty when the deploy tables aren't synced.",+ )+ merge_to_deploy_series = MergeToDeployBucketSerializer(+ many=True,+ help_text="Merge-to-deploy distribution per bucket across the window, oldest first — the box-plot "+ "series (min/p25/p50/mean/p75/max seconds per bucket). Empty when the deploy tables aren't synced, "+ "or when github_team was passed without membership data synced.",+ )++ class Meta:+ dataclass = DoraOverview+ extra_kwargs = {+ "deploy_data_available": {+ "help_text": "False when the deployments/deployment_statuses tables aren't synced for the "+ "selected repo; every other field is then empty or null, never a fake zero."+ },+ "environment_scope": {+ "help_text": "What the environment filter resolved to: 'production' (deployments GitHub marks "+ "production_environment), an exact environment name (the one passed, or the busiest persistent "+ "environment when nothing is marked production), or 'persistent' (no persistent environment "+ "deployed in the window, so every non-transient one counts). Transient environments (ephemeral "+ "per-PR previews) never join a default scope. The scope resolves from deployments in the scan "+ "window, so two different windows can resolve different scopes and are not always comparable."+ },+ "environments": {+ "help_text": "Distinct persistent environments deployed to in the scan window, most-deployed "+ "first — the environment picker's options. Transient environments are omitted but stay "+ "reachable by exact name."+ },+ "has_membership_data": {+ "help_text": "True when the optional team-membership snapshot is synced. When false, a "+ "github_team filter cannot be honored and the merge-to-deploy figures go empty rather than "+ "silently unfiltered."+ },+ "github_teams": {+ "help_text": "Distinct GitHub team slugs from the membership snapshot, sorted — the team "+ "picker's options. Empty when membership isn't synced."+ },+ "deployment_count": {+ "help_text": "Deployments whose first success status landed in the window, within the "+ "environment scope."+ },+ "deployment_count_prev": {"help_text": "Same count over the equal-length window before date_from."},+ "deployments_per_day": {+ "help_text": "deployment_count normalized by the window length in days. Null only when the deploy tables aren't synced.",+ "allow_null": True,+ },+ "deployments_per_day_prev": {+ "help_text": "Previous-window twin of deployments_per_day. Null only when the deploy tables aren't synced.",+ "allow_null": True,+ },+ "median_merge_to_deploy_seconds": {+ "help_text": "Median seconds from a PR's merge to the first successful deployment containing "+ "it (bots/drafts excluded; narrowed by github_team when given). Containment is resolved "+ "through the deploy's head commit, not the deploy's success time. Keyed on deploy time. This "+ "is merge-to-deploy, not full commit-to-deploy DORA lead time. Null when nothing deployed in "+ "the window.",+ "allow_null": True,+ },+ "median_merge_to_deploy_seconds_prev": {+ "help_text": "Previous-window twin of median_merge_to_deploy_seconds.",+ "allow_null": True,+ },+ "deployed_pr_count": {+ "help_text": "PRs first deployed in the window — the population behind the merge-to-deploy "+ "median and box plot."+ },+ "deployed_pr_count_prev": {"help_text": "Previous-window twin of deployed_pr_count."},+ "failed_deployment_count": {+ "help_text": "Deployments with at least one failure/error status, keyed on the first failure time."+ },+ "failed_deployment_count_prev": {"help_text": "Previous-window twin of failed_deployment_count."},+ "failed_deployment_share": {+ "help_text": "Failed deployments over deployments that reached any outcome (success or "+ "failure). A change-failure proxy: no incident data is linked, so a deploy that succeeded but "+ "broke production is not counted. Null when nothing reached an outcome.",+ "allow_null": True,+ },+ "failed_deployment_share_prev": {+ "help_text": "Previous-window twin of failed_deployment_share.",+ "allow_null": True,+ },+ "median_failed_deploy_to_next_success_seconds": {+ "help_text": "Median seconds from a deployment's first failure status to the next successful "+ "deployment in the same environment. A time-to-restore proxy: recovery by anything other than "+ "a deploy is invisible, and failures not yet recovered are excluded. Null when no failed "+ "deploy recovered in the window.",+ "allow_null": True,+ },+ "median_failed_deploy_to_next_success_seconds_prev": {+ "help_text": "Previous-window twin of median_failed_deploy_to_next_success_seconds.",+ "allow_null": True,+ },+ "merged_pr_count": {+ "help_text": "PRs merged in the window (bots and drafts excluded; narrowed by github_team "+ "when given) — the denominator behind unattributed_merged_pr_share."+ },+ "unattributed_merged_pr_share": {+ "help_text": "Share of merged_pr_count no successful in-scope deployment attributed: recent "+ "merges still waiting for their deploy, plus merges whose deploy the scope or scan bounds "+ "miss. Null when nothing merged in the window.",+ "allow_null": True,+ },+ "latest_deploy_status_at": {+ "help_text": "The newest deployment status row synced, any environment — how fresh the deploy "+ "data is. Windows ending after this instant undercount. Null when the deploy tables are empty.",+ "allow_null": True,+ },+ "series_granularity": {+ "help_text": "Bucket width of both series, chosen to fit the window: 'hour', 'day', or 'week'."+ },+ }diff --git a/products/engineering_analytics/backend/presentation/views/__init__.py b/products/engineering_analytics/backend/presentation/views/__init__.pyindex c44bba03ddb9..925e2c6e7b7c 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.dora import DoraActionsMixinfrom products.engineering_analytics.backend.presentation.views.pull_requests import PullRequestActionsMixinfrom products.engineering_analytics.backend.presentation.views.sources import SourcesMixinfrom products.engineering_analytics.backend.presentation.views.suite_health import SuiteHealthActionsMixin@@ -27,6 +28,7 @@ class EngineeringAnalyticsViewSet(WorkflowActionsMixin,SuiteHealthActionsMixin,TeamActionsMixin,+ DoraActionsMixin,EngineeringAnalyticsViewSetBase,):"""PR and CI lifecycle analytics over the GitHub warehouse data."""@@ -40,6 +42,7 @@ class EngineeringAnalyticsViewSet(*WorkflowActionsMixin.READ_ACTIONS,*SuiteHealthActionsMixin.READ_ACTIONS,*TeamActionsMixin.READ_ACTIONS,+ *DoraActionsMixin.READ_ACTIONS,]scope_object_write_actions: list[str] = [*CISignalsConfigMixin.WRITE_ACTIONS,diff --git a/products/engineering_analytics/backend/presentation/views/dora.py b/products/engineering_analytics/backend/presentation/views/dora.pynew file mode 100644index 000000000000..135e02b8b145--- /dev/null+++ b/products/engineering_analytics/backend/presentation/views/dora.py@@ -0,0 +1,74 @@+"""DORA deploy-metrics read."""++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.dora import DoraOverviewSerializer+from products.engineering_analytics.backend.presentation.views._base import (+ _DATE_FROM,+ _DATE_TO,+ _REPO,+ _SOURCE_ID,+ EngineeringAnalyticsViewSetBase,+ _bad_request,+)++_ENVIRONMENT = OpenApiParameter(+ name="environment",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Exact deploy environment to scope to (from the response's `environments` list). Omit to scope "+ "to production-marked deployments, falling back to every persistent (non-transient) environment when none "+ "are marked production.",+)++_GITHUB_TEAM = OpenApiParameter(+ name="github_team",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="GitHub team slug (from the response's `github_teams` list) to narrow the PR-scoped "+ "merge-to-deploy figures to that team's authors. Deploy counts stay repo-wide. Needs the team-membership "+ "snapshot synced; without it the merge-to-deploy figures return empty rather than silently unfiltered.",+)+++class DoraActionsMixin(EngineeringAnalyticsViewSetBase):+ READ_ACTIONS = ["dora"]++ @extend_schema(+ operation_id="engineering_analytics_dora",+ parameters=[_DATE_FROM, _DATE_TO, _ENVIRONMENT, _GITHUB_TEAM, _SOURCE_ID, _REPO],+ responses={+ 200: DoraOverviewSerializer,+ 400: OpenApiResponse(description="Invalid date_from, date_to, or source_id."),+ },+ description=(+ "DORA-style deploy metrics over the GitHub deployments + deployment_statuses warehouse pair, each "+ "headline with its previous-window twin: deployment frequency, merge-to-deploy lead time (with a "+ "per-bucket box-plot series), and honest proxies for change failure rate and time to restore "+ "(deploy-status based — no incident data is linked). deploy_data_available is false when the deploy "+ "tables aren't synced."+ ),+ )+ @action(detail=False, methods=["get"], pagination_class=None)+ def dora(self, request: Request, **kwargs) -> Response:+ try:+ result = api.get_dora_overview(+ team=self.team,+ date_from=request.query_params.get("date_from") or None,+ date_to=request.query_params.get("date_to") or None,+ environment=request.query_params.get("environment") or None,+ github_team=request.query_params.get("github_team") 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 date_from, date_to, or source_id")+ return Response(DoraOverviewSerializer(instance=result).data)diff --git a/products/engineering_analytics/backend/tests/test_dora.py b/products/engineering_analytics/backend/tests/test_dora.pynew file mode 100644index 000000000000..d51d97dc783e--- /dev/null+++ b/products/engineering_analytics/backend/tests/test_dora.py@@ -0,0 +1,382 @@+from datetime import UTC, datetime+from typing import Any++from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin++from rest_framework import status++from posthog.models.team import Team++from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource+from products.engineering_analytics.backend.logic.queries.dora import query_dora_overview+from products.engineering_analytics.backend.logic.sources import GitHubTables+from products.engineering_analytics.backend.logic.views.source_schema import (+ DEPLOYMENT_STATUSES_COLUMNS,+ DEPLOYMENTS_COLUMNS,+ PULL_REQUESTS_COLUMNS,+ TEAM_MEMBERS_COLUMNS,+)+from products.engineering_analytics.backend.tests._github_fixtures import (+ _pr_row,+ connect_github_source_without_data,+ create_github_warehouse_table,+)+++def _deployment_row(+ deployment_id: int, sha: str, environment: str, created_at: str, *, production: bool, transient: bool = False+) -> dict:+ return {+ "id": deployment_id,+ "sha": sha,+ "ref": "master",+ "task": "deploy",+ "environment": environment,+ "original_environment": environment,+ "description": "",+ "creator": "{}",+ "payload": "{}",+ "production_environment": production,+ "transient_environment": transient,+ "created_at": created_at,+ "updated_at": created_at,+ }+++def _status_row(status_id: int, deployment_id: int, state: str, environment: str, created_at: str) -> dict:+ return {+ "id": status_id,+ "deployment_id": deployment_id,+ "state": state,+ "creator": "{}",+ "description": "",+ "environment": environment,+ "target_url": "",+ "log_url": "",+ "environment_url": "",+ "created_at": created_at,+ "updated_at": created_at,+ }+++class TestDoraEndpoint(ClickhouseTestMixin, APIBaseTest):+ def test_degrades_without_deploy_tables(self):+ # The source resolves (pull_requests + workflow_runs) but has no deployments schemas:+ # the endpoint must answer deploy_data_available=false instead of querying missing tables.+ connect_github_source_without_data(self.team, prefix="dora", repository="PostHog/posthog")++ response = self.client.get(f"/api/projects/{self.team.id}/engineering_analytics/dora/")+ assert response.status_code == status.HTTP_200_OK, response.content+ payload = response.json()+ assert payload["deploy_data_available"] is False+ assert payload["deployment_count"] == 0+ assert payload["deployments_per_day"] is None+ assert payload["deployment_frequency_series"] == []+ assert payload["merge_to_deploy_series"] == []+++class TestDoraQuery(ClickhouseTestMixin, BaseTest):+ def _curated(+ self,+ team: Team,+ *,+ deployment_rows: list[dict[str, Any]],+ status_rows: list[dict[str, Any]],+ pr_rows: list[dict[str, Any]],+ member_rows: list[dict[str, Any]] | None = None,+ ) -> CuratedGitHubSource:+ deployments_table = create_github_warehouse_table(+ self, "github_deployments", DEPLOYMENTS_COLUMNS, deployment_rows+ )+ statuses_table = create_github_warehouse_table(+ self, "github_deployment_statuses", DEPLOYMENT_STATUSES_COLUMNS, status_rows+ )+ pr_table = create_github_warehouse_table(self, "github_pull_requests", PULL_REQUESTS_COLUMNS, pr_rows)+ members_table = (+ create_github_warehouse_table(self, "github_team_members", TEAM_MEMBERS_COLUMNS, member_rows)+ if member_rows is not None+ else None+ )+ return CuratedGitHubSource(+ team=team,+ tables=GitHubTables(+ pull_requests=pr_table,+ workflow_runs="unused",+ team_members=members_table,+ deployments=deployments_table,+ deployment_statuses=statuses_table,+ ),+ )++ def _seeded_curated(self, member_rows: list[dict[str, Any]] | None) -> CuratedGitHubSource:+ # Window 2026-01-10 → 2026-01-20; previous window 2025-12-31 → 2026-01-10.+ # prod: d1 succeeds Jan 12, d2 fails Jan 13, d3 succeeds Jan 13 (d2's recovery, 2h later),+ # d5 succeeded in the previous window, d6 never reached an outcome (no status rows).+ # Each successful deploy's sha is a merged PR's merge_commit_sha (its head): PR 1 heads+ # d1, PR 2 heads d3, PR 5 heads d5. Attribution follows head merge order, not success+ # time: PR 6 (carol) merges Jan 12 09:00, AFTER d1's head merge (08:00), so d1 — despite+ # succeeding later that day — does not contain it and it waits for d3.+ # staging: d4 succeeds Jan 12 09:00 — before d1 — so a production-scope leak would+ # change PR 1's lead time from 2h to 1h.+ return self._curated(+ self.team,+ deployment_rows=[+ _deployment_row(1, "sha-a", "prod", "2026-01-12 09:30:00", production=True),+ _deployment_row(2, "sha-b", "prod", "2026-01-13 09:30:00", production=True),+ _deployment_row(3, "sha-c", "prod", "2026-01-13 11:30:00", production=True),+ _deployment_row(4, "sha-d", "staging", "2026-01-12 08:30:00", production=False),+ _deployment_row(5, "sha-e", "prod", "2026-01-05 09:30:00", production=True),+ _deployment_row(6, "sha-f", "prod", "2026-01-14 09:30:00", production=True),+ ],+ status_rows=[+ _status_row(11, 1, "in_progress", "prod", "2026-01-12 09:31:00"),+ _status_row(12, 1, "success", "prod", "2026-01-12 10:00:00"),+ _status_row(21, 2, "failure", "prod", "2026-01-13 10:00:00"),+ _status_row(31, 3, "success", "prod", "2026-01-13 12:00:00"),+ _status_row(41, 4, "success", "staging", "2026-01-12 09:00:00"),+ _status_row(51, 5, "success", "prod", "2026-01-05 10:00:00"),+ ],+ pr_rows=[+ # alice heads d1 and merges 2h before its success; bob heads d3, 2.5h before its.+ _pr_row(+ 1,+ "alice",+ "closed",+ 0,+ "2026-01-11 08:00:00",+ merged_at="2026-01-12 08:00:00",+ merge_commit_sha="sha-a",+ ),+ _pr_row(+ 2,+ "bob",+ "closed",+ 0,+ "2026-01-12 08:00:00",+ merged_at="2026-01-13 09:30:00",+ merge_commit_sha="sha-c",+ ),+ # Bot merge in the same slot as PR 1: must not move the lead-time figures.+ _pr_row(3, "dependabot[bot]", "closed", 0, "2026-01-11 08:00:00", merged_at="2026-01-12 08:00:00"),+ # Merged but never deployed in the window: not part of the deployed population.+ _pr_row(4, "alice", "closed", 0, "2026-01-19 08:00:00", merged_at="2026-01-19 23:00:00"),+ # Previous window: deployed by d5 (which it heads), backing the _prev twins.+ _pr_row(+ 5,+ "alice",+ "closed",+ 0,+ "2026-01-05 06:00:00",+ merged_at="2026-01-05 08:00:00",+ merge_commit_sha="sha-e",+ ),+ # Merged after d1's head merge but before d1's success: the success-time rule would+ # wrongly hand it d1 (1h lead); containment makes it wait for d3 (27h lead).+ _pr_row(6, "carol", "closed", 0, "2026-01-11 09:00:00", merged_at="2026-01-12 09:00:00"),+ ],+ member_rows=member_rows,+ )++ def test_dora_over_seeded_deploys(self):+ # Guards the freshly written HogQL end to end over the real nullable string schema:+ # production scoping, success/failure keying, the recovery self-join, the merged-PR+ # deploy attribution (bots excluded), and both zero-filled series.+ curated = self._seeded_curated(member_rows=None)+ result = query_dora_overview(+ curated=curated,+ date_from=datetime(2026, 1, 10, tzinfo=UTC),+ date_to=datetime(2026, 1, 20, tzinfo=UTC),+ )++ assert result.deploy_data_available is True+ assert result.environment_scope == "production"+ assert result.environments == ["prod", "staging"]+ assert result.has_membership_data is False+ assert result.github_teams == []++ assert result.deployment_count == 2 # d1 + d3; d2 never succeeded, d4 is staging+ assert result.deployment_count_prev == 1 # d5+ assert result.deployments_per_day == 0.2+ assert result.failed_deployment_count == 1 # d2+ assert result.failed_deployment_share == 1 / 3 # outcomes in window: d1, d2, d3+ assert result.median_failed_deploy_to_next_success_seconds == 7200.0 # d2 10:00 → d3 12:00++ assert result.deployed_pr_count == 3 # PRs 1, 2, 6; bot and undeployed merges excluded+ assert result.deployed_pr_count_prev == 1 # PR 5 via d5+ # PR 1: 7200 via d1. PR 2: 9000 via d3. PR 6: 97200 via d3 — the containment rule at+ # work: d1 succeeded after PR 6's merge but its head merged before it, so d1 doesn't count.+ assert result.median_merge_to_deploy_seconds == 9000.0+ assert result.median_merge_to_deploy_seconds_prev == 7200.0+ assert result.merged_pr_count == 4 # PRs 1, 2, 4, 6; the bot merge is excluded+ assert result.unattributed_merged_pr_share == 0.25 # PR 4 merged Jan 19, never deployed+ assert result.latest_deploy_status_at == datetime(2026, 1, 13, 12, 0, tzinfo=UTC)++ assert result.series_granularity == "day"+ frequency = {bucket.bucket_start: bucket.deployment_count for bucket in result.deployment_frequency_series}+ assert len(result.deployment_frequency_series) == 11 # zero-filled Jan 10 → Jan 20+ assert frequency[datetime(2026, 1, 12)] == 1+ assert frequency[datetime(2026, 1, 13)] == 1+ assert frequency[datetime(2026, 1, 15)] == 0++ lead = {bucket.bucket_start: bucket for bucket in result.merge_to_deploy_series}+ assert len(result.merge_to_deploy_series) == 11+ jan_12 = lead[datetime(2026, 1, 12)]+ assert jan_12.deployed_pr_count == 1+ assert jan_12.min_seconds == jan_12.max_seconds == jan_12.p50_seconds == jan_12.mean_seconds == 7200.0+ jan_13 = lead[datetime(2026, 1, 13)]+ assert jan_13.deployed_pr_count == 2 # PRs 2 and 6, both deployed by d3+ assert jan_13.min_seconds == 9000.0+ assert jan_13.max_seconds == 97200.0+ empty = lead[datetime(2026, 1, 15)]+ assert empty.deployed_pr_count == 0+ assert empty.p50_seconds is None++ def test_restore_recovery_excluded_when_it_lands_after_date_to(self):+ # d2 fails Jan 13 10:00, recovers via d3's success at Jan 13 12:00 (see _seeded_curated).+ # A historical report ending before that recovery must not count it: "no recovery in the+ # window" should stay null instead of reaching past date_to for the next success.+ curated = self._seeded_curated(member_rows=None)+ result = query_dora_overview(+ curated=curated,+ date_from=datetime(2026, 1, 10, tzinfo=UTC),+ date_to=datetime(2026, 1, 13, 11, 0, 0, tzinfo=UTC),+ )++ assert result.failed_deployment_count == 1 # d2 still counts as a failure in this window+ assert result.median_failed_deploy_to_next_success_seconds is None++ def test_github_team_filter_narrows_lead_time_only(self):+ curated = self._seeded_curated(+ member_rows=[+ {"id": 1, "login": "alice", "team_id": 1, "team_slug": "team-replay", "team_name": "team-replay"},+ {"id": 2, "login": "bob", "team_id": 2, "team_slug": "team-ingestion", "team_name": "team-ingestion"},+ ]+ )+ result = query_dora_overview(+ curated=curated,+ date_from=datetime(2026, 1, 10, tzinfo=UTC),+ date_to=datetime(2026, 1, 20, tzinfo=UTC),+ github_team="team-replay",+ )++ assert result.has_membership_data is True+ assert result.github_teams == ["team-ingestion", "team-replay"]+ # Only alice's merges count toward lead time and coverage; deploy counts stay repo-wide.+ assert result.deployed_pr_count == 1+ assert result.median_merge_to_deploy_seconds == 7200.0+ assert result.merged_pr_count == 2 # alice's PRs 1 and 4+ assert result.unattributed_merged_pr_share == 0.5 # PR 4 never deployed+ assert result.deployment_count == 2++ def test_team_filter_without_membership_returns_empty_lead_time(self):+ curated = self._seeded_curated(member_rows=None)+ result = query_dora_overview(+ curated=curated,+ date_from=datetime(2026, 1, 10, tzinfo=UTC),+ date_to=datetime(2026, 1, 20, tzinfo=UTC),+ github_team="team-replay",+ )++ # The filter can't be honored, so the lead-time figures go empty, never silently unfiltered.+ assert result.has_membership_data is False+ assert result.deployed_pr_count == 0+ assert result.median_merge_to_deploy_seconds is None+ assert result.merge_to_deploy_series == []+ # Deploy-scoped figures are unaffected.+ assert result.deployment_count == 2++ def test_busiest_environment_fallback_excludes_transient_and_sibling_environments(self):+ # Nothing is production-marked (this repo's real shape), so the default scope falls back+ # to the single busiest persistent environment: the ephemeral per-PR preview deploys and+ # the quieter sibling environment (a second region, dev, a package registry) must stay+ # out of the counts — every-persistent counted them all and multiplied every metric.+ curated = self._curated(+ self.team,+ deployment_rows=[+ _deployment_row(1, "sha-a", "prod-us", "2026-01-12 09:30:00", production=False),+ _deployment_row(2, "sha-b", "preview-pr-123", "2026-01-12 09:30:00", production=False, transient=True),+ _deployment_row(3, "sha-c", "prod-us", "2026-01-13 09:30:00", production=False),+ _deployment_row(4, "sha-d", "dev", "2026-01-12 09:30:00", production=False),+ ],+ status_rows=[+ _status_row(11, 1, "success", "prod-us", "2026-01-12 10:00:00"),+ _status_row(21, 2, "success", "preview-pr-123", "2026-01-12 10:00:00"),+ _status_row(31, 3, "success", "prod-us", "2026-01-13 10:00:00"),+ _status_row(41, 4, "success", "dev", "2026-01-12 10:00:00"),+ ],+ # One never-merged PR keeps the seeded CSV non-empty without joining any deploy.+ pr_rows=[_pr_row(1, "alice", "open", 0, "2026-01-11 08:00:00")],+ )+ result = query_dora_overview(+ curated=curated,+ date_from=datetime(2026, 1, 10, tzinfo=UTC),+ date_to=datetime(2026, 1, 20, tzinfo=UTC),+ )++ assert result.environment_scope == "prod-us"+ assert result.environments == ["prod-us", "dev"]+ assert result.deployment_count == 2++ def test_deploy_scan_slack_bounds_prewindow_deployments(self):+ # A deployment created before the scan window still counts when its success lands inside+ # it, up to the 7-day slack; beyond the slack it is excluded even with an in-window success.+ curated = self._curated(+ self.team,+ deployment_rows=[+ # Created 3 days before prev_from (2025-12-31): inside the slack.+ _deployment_row(1, "sha-a", "prod", "2025-12-28 09:00:00", production=True),+ # Created 9 days before prev_from: outside the slack, excluded from every read.+ _deployment_row(2, "sha-b", "prod", "2025-12-22 09:00:00", production=True),+ ],+ status_rows=[+ _status_row(11, 1, "success", "prod", "2026-01-12 10:00:00"),+ _status_row(21, 2, "success", "prod", "2026-01-13 10:00:00"),+ ],+ pr_rows=[_pr_row(1, "alice", "open", 0, "2026-01-11 08:00:00")],+ )+ result = query_dora_overview(+ curated=curated,+ date_from=datetime(2026, 1, 10, tzinfo=UTC),+ date_to=datetime(2026, 1, 20, tzinfo=UTC),+ )++ assert result.deployment_count == 1++ def test_exact_environment_scope(self):+ # A dedicated fixture, not _seeded_curated: that shared fixture's PR 5 (merged Jan 5) has+ # no earlier production match once scoped to staging-only, so it would fall through and+ # pair with staging's one deployment too, contaminating the median this test isolates.+ curated = self._curated(+ self.team,+ deployment_rows=[+ _deployment_row(1, "sha-a", "prod", "2026-01-12 09:30:00", production=True),+ _deployment_row(4, "sha-d", "staging", "2026-01-12 08:30:00", production=False),+ ],+ status_rows=[+ _status_row(11, 1, "success", "prod", "2026-01-12 10:00:00"),+ _status_row(41, 4, "success", "staging", "2026-01-12 09:00:00"),+ ],+ pr_rows=[+ _pr_row(+ 1,+ "alice",+ "closed",+ 0,+ "2026-01-11 08:00:00",+ merged_at="2026-01-12 08:00:00",+ merge_commit_sha="sha-d",+ ),+ ],+ )+ result = query_dora_overview(+ curated=curated,+ date_from=datetime(2026, 1, 10, tzinfo=UTC),+ date_to=datetime(2026, 1, 20, tzinfo=UTC),+ environment="staging",+ )++ assert result.environment_scope == "staging"+ assert result.deployment_count == 1 # d4 only; d1 (prod) excluded by the exact scope+ assert result.failed_deployment_count == 0+ # PR 1 (merged Jan 12 08:00) reaches staging's 09:00 success: a 1h lead time.+ assert result.median_merge_to_deploy_seconds == 3600.0diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.pyindex 6dce0a336216..69a055458dae 100644--- a/products/engineering_analytics/backend/tests/test_views.py+++ b/products/engineering_analytics/backend/tests/test_views.py@@ -239,7 +239,7 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):"(SELECT 100 AS id, 5 AS number, 'PR 5' AS title, 'open' AS state, false AS draft, "f"nullIf('', '') AS user, '{head_json}' AS head, '{base_json}' AS base, '[]' AS labels, ""'2026-01-10 10:00:00' AS created_at, '2026-01-10 10:00:00' AS updated_at, "- "nullIf('', '') AS merged_at, nullIf('', '') AS closed_at)"+ "nullIf('', '') AS merged_at, nullIf('', '') AS closed_at, nullIf('', '') AS merge_commit_sha)")rows = self._select(f"SELECT author_handle, author_avatar_url, is_bot FROM ({pull_requests.build_query(raw)}) AS pr"diff --git a/products/engineering_analytics/frontend/components/MergeToDeployBoxPlot.stories.tsx b/products/engineering_analytics/frontend/components/MergeToDeployBoxPlot.stories.tsxnew file mode 100644index 000000000000..47008e57b990--- /dev/null+++ b/products/engineering_analytics/frontend/components/MergeToDeployBoxPlot.stories.tsx@@ -0,0 +1,73 @@+import type { Meta, StoryObj } from '@storybook/react'++import { MergeToDeployBoxPlot, type BoxPlotBucket } from './MergeToDeployBoxPlot'++function bucket(+ label: string,+ count: number,+ seconds: [number, number, number, number, number, number]+): BoxPlotBucket {+ const [min, p25, p50, mean, p75, max] = seconds+ return {+ label,+ count,+ minSeconds: min,+ p25Seconds: p25,+ p50Seconds: p50,+ meanSeconds: mean,+ p75Seconds: p75,+ maxSeconds: max,+ }+}++const EMPTY_BUCKET: BoxPlotBucket = {+ label: 'Jul 13',+ count: 0,+ minSeconds: null,+ p25Seconds: null,+ p50Seconds: null,+ meanSeconds: null,+ p75Seconds: null,+ maxSeconds: null,+}++const BUCKETS: BoxPlotBucket[] = [+ bucket('Jul 7', 14, [600, 1800, 3600, 4600, 7200, 14400]),+ bucket('Jul 8', 22, [900, 2400, 4200, 5200, 6000, 21600]),+ bucket('Jul 9', 9, [1200, 3000, 5400, 6800, 9600, 18000]),+ bucket('Jul 10', 17, [600, 1500, 2700, 3400, 4800, 9000]),+ bucket('Jul 11', 5, [1800, 3600, 7200, 11500, 14400, 43200]),+ bucket('Jul 12', 1, [5400, 5400, 5400, 5400, 5400, 5400]),+ { ...EMPTY_BUCKET },+ bucket('Jul 14', 11, [600, 1200, 2400, 2900, 3600, 7200]),+]++const meta: Meta<typeof MergeToDeployBoxPlot> = {+ title: 'Scenes-App/Engineering Analytics/Merge To Deploy Box Plot',+ component: MergeToDeployBoxPlot,+ parameters: {+ layout: 'fullscreen',+ testOptions: {+ snapshotBrowsers: ['chromium'],+ waitForSelector: '[data-attr="merge-to-deploy-box-plot-story"] canvas',+ viewport: { width: 1280, height: 400 },+ },+ },+ decorators: [+ (Story) => (+ <div className="p-6" data-attr="merge-to-deploy-box-plot-story">+ <Story />+ </div>+ ),+ ],+ args: {+ buckets: BUCKETS,+ formatSeconds: (seconds: number) => `${Math.round(seconds / 60)}m`,+ },+}++export default meta++type Story = StoryObj<typeof meta>++export const Default: Story = {}diff --git a/products/engineering_analytics/frontend/components/MergeToDeployBoxPlot.tsx b/products/engineering_analytics/frontend/components/MergeToDeployBoxPlot.tsxnew file mode 100644index 000000000000..aa9668139c35--- /dev/null+++ b/products/engineering_analytics/frontend/components/MergeToDeployBoxPlot.tsx@@ -0,0 +1,130 @@+import { useMemo } from 'react'++import { BoxPlot, TooltipSurface, useChartTheme } from '@posthog/quill-charts'+import type { BoxPlotDatum, BoxPlotSeries, BoxPlotTooltipContext } from '@posthog/quill-charts'++import { cn } from 'lib/utils/css-classes'++export interface BoxPlotBucket {+ /** x-axis and tooltip label for the bucket (e.g. its date). Must be unique across buckets. */+ label: string+ /** Samples in the bucket; 0 renders an empty slot. */+ count: number+ minSeconds: number | null+ p25Seconds: number | null+ p50Seconds: number | null+ meanSeconds: number | null+ p75Seconds: number | null+ maxSeconds: number | null+}++export interface MergeToDeployBoxPlotProps {+ /** One entry per bucket, oldest first. */+ buckets: BoxPlotBucket[]+ /** Value formatter for the tooltip rows (seconds in, short label out). */+ formatSeconds: (seconds: number) => string+ className?: string+}++/** Per-bucket sample counts, carried into the tooltip through the series meta. */+interface BucketMeta {+ counts: number[]+}++function toDatum(bucket: BoxPlotBucket): BoxPlotDatum | null {+ if (+ bucket.count === 0 ||+ bucket.minSeconds == null ||+ bucket.p25Seconds == null ||+ bucket.p50Seconds == null ||+ bucket.meanSeconds == null ||+ bucket.p75Seconds == null ||+ bucket.maxSeconds == null+ ) {+ return null+ }+ return {+ min: bucket.minSeconds,+ p25: bucket.p25Seconds,+ median: bucket.p50Seconds,+ mean: bucket.meanSeconds,+ p75: bucket.p75Seconds,+ max: bucket.maxSeconds,+ }+}++/**+ * One box-and-whisker per bucket (quill BoxPlot): whisker min→max, box p25→p75, a median line+ * and a mean dot, on a shared seconds scale. Empty buckets stay empty slots so a quiet stretch+ * reads as "nothing deployed", not missing data.+ */+export function MergeToDeployBoxPlot({ buckets, formatSeconds, className }: MergeToDeployBoxPlotProps): JSX.Element {+ const theme = useChartTheme()+ const labels = useMemo(() => buckets.map((bucket) => bucket.label), [buckets])+ const series = useMemo<BoxPlotSeries<BucketMeta>[]>(+ () => [+ {+ key: 'merge_to_deploy',+ label: 'Merge to deploy',+ data: buckets.map(toDatum),+ meta: { counts: buckets.map((bucket) => bucket.count) },+ },+ ],+ [buckets]+ )+ return (+ // The chart's root is a `flex-1` child, so the sized wrapper must be a flex column —+ // in a plain block parent the canvas measures 0px tall and paints nothing.+ <div className={cn('flex h-64 flex-col', className)}>+ <BoxPlot<BucketMeta>+ series={series}+ labels={labels}+ theme={theme}+ config={{ yTickFormatter: formatSeconds }}+ dataAttr="merge-to-deploy-box-plot"+ tooltip={(ctx) => <BucketTooltip ctx={ctx} formatSeconds={formatSeconds} />}+ />+ </div>+ )+}++function BucketTooltip({+ ctx,+ formatSeconds,+}: {+ ctx: BoxPlotTooltipContext<BucketMeta>+ formatSeconds: (seconds: number) => string+}): JSX.Element | null {+ const entry = ctx.seriesData[0]+ const datum = entry?.series.meta?.datums?.[ctx.dataIndex]+ if (!datum) {+ return null+ }+ const count = entry?.series.meta?.user?.counts?.[ctx.dataIndex] ?? 0+ const rows: [string, number][] = [+ ['Max', datum.max],+ ['75th percentile', datum.p75],+ ['Median', datum.median],+ ['Mean', datum.mean],+ ['25th percentile', datum.p25],+ ['Min', datum.min],+ ]+ return (+ <TooltipSurface data-attr="merge-to-deploy-box-plot-tooltip">+ <div className="font-semibold">{ctx.label}</div>+ <div className="mb-1 opacity-70">+ {count} PR{count === 1 ? '' : 's'} deployed+ </div>+ <table className="border-collapse">+ <tbody>+ {rows.map(([label, value]) => (+ <tr key={label}>+ <td className="pr-3 opacity-70">{label}</td>+ <td className="font-medium">{formatSeconds(value)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </TooltipSurface>+ )+}diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex d93060faaf7e..f76a1118eafd 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -201,6 +201,133 @@ export interface CurrentBranchHealthApi {failing_workflow_names: string[]}+export interface DeploymentFrequencyBucketApi {+ /** Bucket start, aligned to series_granularity (top of hour, midnight, or Monday). */+ bucket_start: string+ /** Deployments whose first success status landed in this bucket, within the environment scope. Zero-filled: 0 means nothing shipped. */+ deployment_count: number+}++export interface MergeToDeployBucketApi {+ /** Bucket start, aligned to series_granularity (top of hour, midnight, or Monday). Keyed on deploy time: a PR lands in the bucket its first post-merge deploy succeeded in. */+ bucket_start: string+ /** PRs whose first post-merge successful deployment landed in this bucket (bots and drafts excluded; narrowed by github_team when given). */+ deployed_pr_count: number+ /**+ * Fastest merge-to-deploy in this bucket, in seconds. Null when nothing deployed.+ * @nullable+ */+ min_seconds: number | null+ /**+ * 25th percentile merge-to-deploy seconds. Null when nothing deployed.+ * @nullable+ */+ p25_seconds: number | null+ /**+ * Median merge-to-deploy seconds. Null when nothing deployed.+ * @nullable+ */+ p50_seconds: number | null+ /**+ * Mean merge-to-deploy seconds. Null when nothing deployed.+ * @nullable+ */+ mean_seconds: number | null+ /**+ * 75th percentile merge-to-deploy seconds. Null when nothing deployed.+ * @nullable+ */+ p75_seconds: number | null+ /**+ * Slowest merge-to-deploy in this bucket, in seconds. Null when nothing deployed.+ * @nullable+ */+ max_seconds: number | null+}++export interface DoraOverviewApi {+ /** Successful deployments per bucket across the window, oldest first, zero-filled, bucketed by series_granularity. Empty when the deploy tables aren't synced. */+ deployment_frequency_series: DeploymentFrequencyBucketApi[]+ /** Merge-to-deploy distribution per bucket across the window, oldest first — the box-plot series (min/p25/p50/mean/p75/max seconds per bucket). Empty when the deploy tables aren't synced, or when github_team was passed without membership data synced. */+ merge_to_deploy_series: MergeToDeployBucketApi[]+ /** False when the deployments/deployment_statuses tables aren't synced for the selected repo; every other field is then empty or null, never a fake zero. */+ deploy_data_available: boolean+ /** What the environment filter resolved to: 'production' (deployments GitHub marks production_environment), an exact environment name (the one passed, or the busiest persistent environment when nothing is marked production), or 'persistent' (no persistent environment deployed in the window, so every non-transient one counts). Transient environments (ephemeral per-PR previews) never join a default scope. The scope resolves from deployments in the scan window, so two different windows can resolve different scopes and are not always comparable. */+ environment_scope: string+ /** Distinct persistent environments deployed to in the scan window, most-deployed first — the environment picker's options. Transient environments are omitted but stay reachable by exact name. */+ environments: string[]+ /** True when the optional team-membership snapshot is synced. When false, a github_team filter cannot be honored and the merge-to-deploy figures go empty rather than silently unfiltered. */+ has_membership_data: boolean+ /** Distinct GitHub team slugs from the membership snapshot, sorted — the team picker's options. Empty when membership isn't synced. */+ github_teams: string[]+ /** Deployments whose first success status landed in the window, within the environment scope. */+ deployment_count: number+ /** Same count over the equal-length window before date_from. */+ deployment_count_prev: number+ /**+ * deployment_count normalized by the window length in days. Null only when the deploy tables aren't synced.+ * @nullable+ */+ deployments_per_day: number | null+ /**+ * Previous-window twin of deployments_per_day. Null only when the deploy tables aren't synced.+ * @nullable+ */+ deployments_per_day_prev: number | null+ /**+ * Median seconds from a PR's merge to the first successful deployment containing it (bots/drafts excluded; narrowed by github_team when given). Containment is resolved through the deploy's head commit, not the deploy's success time. Keyed on deploy time. This is merge-to-deploy, not full commit-to-deploy DORA lead time. Null when nothing deployed in the window.+ * @nullable+ */+ median_merge_to_deploy_seconds: number | null+ /**+ * Previous-window twin of median_merge_to_deploy_seconds.+ * @nullable+ */+ median_merge_to_deploy_seconds_prev: number | null+ /** PRs first deployed in the window — the population behind the merge-to-deploy median and box plot. */+ deployed_pr_count: number+ /** Previous-window twin of deployed_pr_count. */+ deployed_pr_count_prev: number+ /** Deployments with at least one failure/error status, keyed on the first failure time. */+ failed_deployment_count: number+ /** Previous-window twin of failed_deployment_count. */+ failed_deployment_count_prev: number+ /**+ * Failed deployments over deployments that reached any outcome (success or failure). A change-failure proxy: no incident data is linked, so a deploy that succeeded but broke production is not counted. Null when nothing reached an outcome.+ * @nullable+ */+ failed_deployment_share: number | null+ /**+ * Previous-window twin of failed_deployment_share.+ * @nullable+ */+ failed_deployment_share_prev: number | null+ /**+ * Median seconds from a deployment's first failure status to the next successful deployment in the same environment. A time-to-restore proxy: recovery by anything other than a deploy is invisible, and failures not yet recovered are excluded. Null when no failed deploy recovered in the window.+ * @nullable+ */+ median_failed_deploy_to_next_success_seconds: number | null+ /**+ * Previous-window twin of median_failed_deploy_to_next_success_seconds.+ * @nullable+ */+ median_failed_deploy_to_next_success_seconds_prev: number | null+ /** PRs merged in the window (bots and drafts excluded; narrowed by github_team when given) — the denominator behind unattributed_merged_pr_share. */+ merged_pr_count: number+ /**+ * Share of merged_pr_count no successful in-scope deployment attributed: recent merges still waiting for their deploy, plus merges whose deploy the scope or scan bounds miss. Null when nothing merged in the window.+ * @nullable+ */+ unattributed_merged_pr_share: number | null+ /**+ * The newest deployment status row synced, any environment — how fresh the deploy data is. Windows ending after this instant undercount. Null when the deploy tables are empty.+ * @nullable+ */+ latest_deploy_status_at: string | null+ /** Bucket width of both series, chosen to fit the window: 'hour', 'day', or 'week'. */+ series_granularity: string+}+/*** * `pytest` - PYTEST* * `jest` - JEST@@ -1456,6 +1583,33 @@ export type EngineeringAnalyticsCurrentBranchHealthParams = {source_id?: string}+export type EngineeringAnalyticsDoraParams = {+ /**+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.+ */+ date_from?: string+ /**+ * Window end: relative or ISO8601. Defaults to now.+ */+ date_to?: string+ /**+ * Exact deploy environment to scope to (from the response's `environments` list). Omit to scope to production-marked deployments, falling back to every persistent (non-transient) environment when none are marked production.+ */+ environment?: string+ /**+ * GitHub team slug (from the response's `github_teams` list) to narrow the PR-scoped merge-to-deploy figures to that team's authors. Deploy counts stay repo-wide. Needs the team-membership snapshot synced; without it the merge-to-deploy figures return empty rather than silently unfiltered.+ */+ github_team?: string+ /**+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.+ */+ 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 EngineeringAnalyticsFlakyTestsParams = {/*** Window start: relative ('-7d', '-30d') or ISO8601. Defaults to -7d; the window may span at most 30 days.diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.tsindex a10c9a24cb35..503c0c7b6dd9 100644--- a/products/engineering_analytics/frontend/generated/api.ts+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -16,11 +16,13 @@ import type {CISignalsConfigApi,CISignalsConfigUpdateApi,CurrentBranchHealthApi,+ DoraOverviewApi,EngineeringAnalyticsAuthorWorkflowCostsParams,EngineeringAnalyticsBrokenTestsParams,EngineeringAnalyticsCiCardsParams,EngineeringAnalyticsCiFailureLogsParams,EngineeringAnalyticsCurrentBranchHealthParams,+ EngineeringAnalyticsDoraParams,EngineeringAnalyticsFlakyTestsParams,EngineeringAnalyticsJobAggregatesParams,EngineeringAnalyticsMasterFailuresParams,@@ -264,6 +266,36 @@ export const engineeringAnalyticsCurrentBranchHealth = async (})}+export const getEngineeringAnalyticsDoraUrl = (projectId: string, params?: EngineeringAnalyticsDoraParams) => {+ 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/dora/?${stringifiedParams}`+ : `/api/projects/${projectId}/engineering_analytics/dora/`+}++/**+ * DORA-style deploy metrics over the GitHub deployments + deployment_statuses warehouse pair, each headline with its previous-window twin: deployment frequency, merge-to-deploy lead time (with a per-bucket box-plot series), and honest proxies for change failure rate and time to restore (deploy-status based — no incident data is linked). deploy_data_available is false when the deploy tables aren't synced.+ */+export const engineeringAnalyticsDora = async (+ projectId: string,+ params?: EngineeringAnalyticsDoraParams,+ options?: RequestInit+): Promise<DoraOverviewApi> => {+ return apiMutator<DoraOverviewApi>(getEngineeringAnalyticsDoraUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getEngineeringAnalyticsFlakyTestsUrl = (projectId: string,params?: EngineeringAnalyticsFlakyTestsParamsdiff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsHealth.stories.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsHealth.stories.tsxnew file mode 100644index 000000000000..169d150f273c--- /dev/null+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsHealth.stories.tsx@@ -0,0 +1,173 @@+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 { DoraOverviewApi, GitHubSourceApi } from '../generated/api.schemas'++const SOURCES: GitHubSourceApi[] = [{ id: 'src-1', repo: 'PostHog/posthog', prefix: '', synced: true }]++// Eight daily buckets ending at the mock date, with a quiet weekend (Jul 12 thin, Jul 13 empty)+// so the box plot shows both dense boxes and a gap slot.+const BUCKET_DAYS = ['08', '09', '10', '11', '12', '13', '14', '15']++const FREQUENCY_COUNTS = [9, 11, 12, 8, 2, 0, 10, 8]++// Per-bucket [count, min, p25, p50, mean, p75, max] in seconds; null marks the empty weekend day.+const LEAD_TIME_STATS: (number[] | null)[] = [+ [16, 480, 1200, 2100, 2900, 4200, 9000],+ [19, 600, 1500, 2400, 3300, 3900, 12600],+ [21, 540, 1320, 2280, 3100, 4500, 10800],+ [14, 660, 1440, 2700, 4400, 5400, 21600],+ [3, 900, 1800, 3600, 6600, 7200, 14400],+ null,+ [17, 480, 1260, 2160, 2700, 3600, 8400],+ [13, 600, 1380, 2520, 3500, 4800, 11400],+]++const DORA: DoraOverviewApi = {+ deploy_data_available: true,+ environment_scope: 'production',+ environments: ['prod-us', 'prod-eu', 'dev'],+ has_membership_data: true,+ github_teams: ['team-devex', 'team-ingestion', 'team-replay'],+ deployment_count: 60,+ deployment_count_prev: 52,+ deployments_per_day: 8.6,+ deployments_per_day_prev: 7.4,+ median_merge_to_deploy_seconds: 2520,+ median_merge_to_deploy_seconds_prev: 3300,+ deployed_pr_count: 103,+ deployed_pr_count_prev: 88,+ failed_deployment_count: 2,+ failed_deployment_count_prev: 4,+ failed_deployment_share: 0.032,+ failed_deployment_share_prev: 0.071,+ median_failed_deploy_to_next_success_seconds: 2280,+ median_failed_deploy_to_next_success_seconds_prev: 3540,+ merged_pr_count: 112,+ unattributed_merged_pr_share: 0.045,+ latest_deploy_status_at: '2026-07-14T22:00:00Z',+ deployment_frequency_series: BUCKET_DAYS.map((day, i) => ({+ bucket_start: `2026-07-${day}T00:00:00Z`,+ deployment_count: FREQUENCY_COUNTS[i],+ })),+ merge_to_deploy_series: BUCKET_DAYS.map((day, i) => {+ const stats = LEAD_TIME_STATS[i]+ return {+ bucket_start: `2026-07-${day}T00:00:00Z`,+ deployed_pr_count: stats ? stats[0] : 0,+ min_seconds: stats ? stats[1] : null,+ p25_seconds: stats ? stats[2] : null,+ p50_seconds: stats ? stats[3] : null,+ mean_seconds: stats ? stats[4] : null,+ p75_seconds: stats ? stats[5] : null,+ max_seconds: stats ? stats[6] : null,+ }+ }),+ series_granularity: 'day',+}++const EMPTY_DORA: DoraOverviewApi = {+ ...DORA,+ deploy_data_available: false,+ environment_scope: 'persistent',+ environments: [],+ github_teams: [],+ has_membership_data: false,+ deployment_count: 0,+ deployment_count_prev: 0,+ deployments_per_day: null,+ deployments_per_day_prev: null,+ median_merge_to_deploy_seconds: null,+ median_merge_to_deploy_seconds_prev: null,+ deployed_pr_count: 0,+ deployed_pr_count_prev: 0,+ failed_deployment_count: 0,+ failed_deployment_count_prev: 0,+ failed_deployment_share: null,+ failed_deployment_share_prev: null,+ median_failed_deploy_to_next_success_seconds: null,+ median_failed_deploy_to_next_success_seconds_prev: null,+ merged_pr_count: 0,+ unattributed_merged_pr_share: null,+ latest_deploy_status_at: null,+ deployment_frequency_series: [],+ merge_to_deploy_series: [],+}++const meta: Meta = {+ component: App,+ title: 'Scenes-App/Engineering Analytics/Health',+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2026-07-15',+ featureFlags: [FEATURE_FLAGS.ENGINEERING_ANALYTICS],+ testOptions: {+ // Past the skeletons once the box-plot chart has rendered.+ waitForSelector: '[data-attr="engineering-analytics-dora-box-plot"] canvas',+ },+ },+ decorators: [+ mswDecorator({+ get: {+ 'api/projects/:team_id/engineering_analytics/sources/': SOURCES,+ 'api/projects/:team_id/engineering_analytics/dora/': DORA,+ // Loaded by the shared scene logic on mount, whichever tab is active.+ 'api/projects/:team_id/engineering_analytics/ci_cards/': {+ open_prs: 18,+ repos: 1,+ stuck: 3,+ failing_ci: 4,+ },+ 'api/projects/:team_id/engineering_analytics/pull_requests/': {+ items: [],+ truncated: false,+ limit: 1000,+ },+ 'api/projects/:team_id/engineering_analytics/workflow_health/': [],+ 'api/projects/:team_id/engineering_analytics/quarantine/': {+ available: false,+ entries: [],+ source_url: '',+ },+ 'api/projects/:team_id/engineering_analytics/flaky_tests/': {+ items: [],+ truncated: false,+ limit: 100,+ },+ },+ }),+ ],+}+export default meta++type Story = StoryObj<typeof meta>++export const Health: Story = {+ render: () => <App />,+ parameters: { pageUrl: urls.engineeringAnalyticsHealth() },+}++// The not-yet-synced state: the deploy endpoints aren't enabled on the GitHub source, so the tab+// explains what to enable instead of showing zeros.+export const HealthWithoutDeployData: Story = {+ render: () => <App />,+ parameters: {+ pageUrl: urls.engineeringAnalyticsHealth(),+ testOptions: {+ waitForSelector: '[data-attr="engineering-analytics-dora-no-deploy-data"]',+ },+ },+ decorators: [+ mswDecorator({+ get: {+ 'api/projects/:team_id/engineering_analytics/dora/': EMPTY_DORA,+ },+ }),+ ],+}diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsHealth.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsHealth.tsxnew file mode 100644index 000000000000..6eba5ed82ce4--- /dev/null+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsHealth.tsx@@ -0,0 +1,234 @@+import { useActions, useValues } from 'kea'+import { useMemo } from 'react'++import { LemonBanner, LemonSelect, LemonSkeleton } from '@posthog/lemon-ui'+import { TimeSeriesBarChart, useChartTheme, type TimeInterval } from '@posthog/quill-charts'++import { dayjs } from 'lib/dayjs'++import { CIAnalyticsLoadError } from '../components/CIAnalyticsLoadError'+import { ConnectGitHubSource } from '../components/ConnectGitHubSource'+import { MergeToDeployBoxPlot } from '../components/MergeToDeployBoxPlot'+import { MetricTile, percentChange, pointChange } from '../components/MetricTile'+import { ScopeBar, SourceScopeChip } from '../components/ScopeBar'+import { Section } from '../components/Section'+import { compactAgeLabel } from '../lib/format'+import { doraLogic } from './doraLogic'++export function EngineeringAnalyticsHealth(): JSX.Element {+ const {+ notConnected,+ dora,+ doraLoading,+ doraFailed,+ environment,+ githubTeam,+ boxPlotBuckets,+ frequencyCounts,+ frequencyIsoLabels,+ environmentScopeLabel,+ environmentOptions,+ githubTeamOptions,+ } = useValues(doraLogic)+ const { setEnvironment, setGithubTeam, loadDora } = useActions(doraLogic)+ const chartTheme = useChartTheme()+ const frequencySeries = useMemo(+ () => [{ key: 'deployments', label: 'Deployments', data: frequencyCounts }],+ [frequencyCounts]+ )++ if (notConnected) {+ return <ConnectGitHubSource />+ }+ if (doraFailed) {+ return <CIAnalyticsLoadError onRetry={loadDora} />+ }++ const firstLoad = doraLoading && !dora+ const deployDataMissing = !!dora && !dora.deploy_data_available++ return (+ <div className="flex flex-col gap-4">+ <ScopeBar repoSlot={<SourceScopeChip />} />+ {deployDataMissing ? (+ <div data-attr="engineering-analytics-dora-no-deploy-data">+ <LemonBanner type="info">+ Deploy data isn't synced yet. Enable the deployments and deployment statuses endpoints on your+ GitHub source to see DORA metrics.+ </LemonBanner>+ </div>+ ) : (+ <div className="flex flex-wrap items-center gap-2">+ <LemonSelect+ size="small"+ value={environment}+ onChange={setEnvironment}+ options={environmentOptions}+ data-attr="engineering-analytics-dora-environment-select"+ />+ {dora?.has_membership_data && (+ <LemonSelect+ size="small"+ value={githubTeam}+ onChange={setGithubTeam}+ options={githubTeamOptions}+ data-attr="engineering-analytics-dora-team-select"+ />+ )}+ {githubTeam && (+ <span className="text-xs text-tertiary">+ The team filter narrows the merge to deploy figures. Deploy counts stay repo-wide.+ </span>+ )}+ {dora?.latest_deploy_status_at && (+ <span+ className="ml-auto text-xs text-tertiary"+ data-attr="engineering-analytics-dora-freshness"+ >+ Latest deploy status synced {dayjs(dora.latest_deploy_status_at).fromNow()}.+ </span>+ )}+ </div>+ )}+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">+ <MetricTile+ label="Deployment frequency"+ tooltip={`Successful deployments per day in the ${environmentScopeLabel} scope: ${dora?.deployment_count ?? 0} in this window.`}+ value={dora?.deployments_per_day != null ? `${dora.deployments_per_day.toFixed(1)}/day` : '—'}+ delta={{ value: percentChange(dora?.deployments_per_day, dora?.deployments_per_day_prev) }}+ sub={+ dora && dora.deploy_data_available && dora.deployment_count === 0+ ? 'No successful deployments in this window.'+ : undefined+ }+ loading={firstLoad}+ />+ <MetricTile+ label="Merge to deploy"+ tooltip={`Median wait from a PR's merge to the first successful deployment containing it, over ${dora?.deployed_pr_count ?? 0} deployed PRs (bots and drafts excluded). Not full commit-to-deploy lead time: pre-merge time is on the Overview tab.`}+ value={+ dora?.median_merge_to_deploy_seconds != null+ ? compactAgeLabel(dora.median_merge_to_deploy_seconds)+ : '—'+ }+ delta={{+ value: percentChange(+ dora?.median_merge_to_deploy_seconds,+ dora?.median_merge_to_deploy_seconds_prev+ ),+ goodWhenDown: true,+ }}+ sub={+ dora && dora.median_merge_to_deploy_seconds == null+ ? 'No PRs were deployed in this window.'+ : undefined+ }+ loading={firstLoad}+ />+ <MetricTile+ label="Failed deployment share"+ tooltip={`Deployments with a failure or error status over deployments that reached an outcome (${dora?.failed_deployment_count ?? 0} failed here). A change failure proxy: deploys that succeeded but broke production aren't counted, because no incident data is linked.`}+ value={+ dora?.failed_deployment_share != null+ ? `${(dora.failed_deployment_share * 100).toFixed(1)}%`+ : '—'+ }+ delta={{+ value: pointChange(dora?.failed_deployment_share, dora?.failed_deployment_share_prev),+ unit: 'pt',+ goodWhenDown: true,+ }}+ sub={+ dora && dora.failed_deployment_share == null+ ? 'No deployments reached an outcome in this window.'+ : undefined+ }+ loading={firstLoad}+ />+ <MetricTile+ label="Failed deploy to next success"+ tooltip="Median wait from a deployment's first failure status to the next successful deployment in the same environment. A time to restore proxy: recovery by anything other than a deploy is invisible, and unrecovered failures are excluded."+ value={+ dora?.median_failed_deploy_to_next_success_seconds != null+ ? compactAgeLabel(dora.median_failed_deploy_to_next_success_seconds)+ : '—'+ }+ delta={{+ value: percentChange(+ dora?.median_failed_deploy_to_next_success_seconds,+ dora?.median_failed_deploy_to_next_success_seconds_prev+ ),+ goodWhenDown: true,+ }}+ sub={+ dora && dora.median_failed_deploy_to_next_success_seconds == null+ ? 'No failed deployment recovered in this window.'+ : undefined+ }+ loading={firstLoad}+ />+ </div>+ <Section+ id="merge-to-deploy"+ title="Merge to deploy distribution"+ note="Box per bucket: whisker min to max, box p25 to p75, line at the median, dot at the mean. Buckets key on deploy time."+ busy={doraLoading && !!dora}+ >+ {firstLoad ? (+ <LemonSkeleton className="h-40 w-full" />+ ) : boxPlotBuckets.length === 0 ? (+ <div className="py-8 text-center text-sm text-secondary">+ {githubTeam && dora && !dora.has_membership_data+ ? 'Team membership data is not synced, so the team filter cannot be applied.'+ : 'No deploy data for this window.'}+ </div>+ ) : (+ <>+ <div data-attr="engineering-analytics-dora-box-plot">+ <MergeToDeployBoxPlot buckets={boxPlotBuckets} formatSeconds={compactAgeLabel} />+ </div>+ {dora?.unattributed_merged_pr_share != null && dora.unattributed_merged_pr_share > 0 && (+ <div+ className="mt-2 text-xs text-tertiary"+ data-attr="engineering-analytics-dora-unattributed"+ >+ {(dora.unattributed_merged_pr_share * 100).toFixed(1)}% of the {dora.merged_pr_count}{' '}+ PRs merged in this window have no deploy attributed yet, usually because their deploy+ hasn't happened or synced.+ </div>+ )}+ </>+ )}+ </Section>+ <Section+ id="deployment-frequency"+ title="Deployments over time"+ note={`Successful deployments per bucket in the ${environmentScopeLabel} scope.`}+ busy={doraLoading && !!dora}+ >+ {firstLoad ? (+ <LemonSkeleton className="h-40 w-full" />+ ) : frequencyCounts.length === 0 ? (+ <div className="py-8 text-center text-sm text-secondary">No deploy data for this window.</div>+ ) : (+ // The chart's root is a `flex-1` child, so the sized wrapper must be a flex column.+ <div className="flex h-40 flex-col" data-attr="engineering-analytics-dora-frequency-chart">+ <TimeSeriesBarChart+ series={frequencySeries}+ labels={frequencyIsoLabels}+ theme={chartTheme}+ config={{+ xAxis: {+ timezone: 'UTC',+ interval: (dora?.series_granularity ?? 'day') as TimeInterval,+ },+ yAxis: { format: 'numeric', decimalPlaces: 0 },+ minBarSize: 2,+ }}+ />+ </div>+ )}+ </Section>+ </div>+ )+}diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsxindex 577caf909b09..d64d12c502c6 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsScene.tsx@@ -9,6 +9,8 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { doraLogic } from './doraLogic'+import { EngineeringAnalyticsHealth } from './EngineeringAnalyticsHealth'import { engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'import { EngineeringAnalyticsPullRequests } from './EngineeringAnalyticsPullRequests'import {@@ -26,12 +28,36 @@ export const scene: SceneExport = {logic: engineeringAnalyticsSceneLogic,}-export function EngineeringAnalyticsScene(): JSX.Element {- const { searchParams: linkParams } = useValues(router)- const { activeView } = useValues(engineeringAnalyticsSceneLogic)+function RefreshButton({ extraLoading = false }: { extraLoading?: boolean }): JSX.Element {const logic = engineeringAnalyticsLogic()const { anyLoading } = useValues(logic)const { refresh } = useActions(logic)+ const loading = anyLoading || extraLoading+ return (+ <LemonButton+ type="secondary"+ size="small"+ onClick={refresh}+ loading={loading}+ disabledReason={loading ? 'Loading…' : undefined}+ >+ Refresh+ </LemonButton>+ )+}++// Rendered only while the Health tab is active, where its content keeps doraLogic mounted —+// subscribing here adds no eager DORA load on the other tabs. The DORA loading state can't+// join anyLoading directly: doraLogic already connects from engineeringAnalyticsLogic, and a+// reverse connect would make the two logics circular.+function HealthRefreshButton(): JSX.Element {+ const { doraLoading } = useValues(doraLogic)+ return <RefreshButton extraLoading={doraLoading} />+}++export function EngineeringAnalyticsScene(): JSX.Element {+ const { searchParams: linkParams } = useValues(router)+ const { activeView } = useValues(engineeringAnalyticsSceneLogic)// The general areas of the product. Drill-down pages (workflow, run, PR) live below the Overview.const tabs: LemonTab<EngineeringAnalyticsView>[] = [@@ -70,6 +96,13 @@ export function EngineeringAnalyticsScene(): JSX.Element {link: combineUrl(urls.engineeringAnalyticsTestHealth(), linkParams).url,'data-attr': 'engineering-analytics-test-health-tab',},+ {+ key: 'health',+ label: 'Health',+ content: <EngineeringAnalyticsHealth />,+ link: combineUrl(urls.engineeringAnalyticsHealth(), linkParams).url,+ 'data-attr': 'engineering-analytics-health-tab',+ },]return (@@ -79,17 +112,7 @@ export function EngineeringAnalyticsScene(): JSX.Element {name="Engineering analytics"description={VIEW_DESCRIPTIONS[activeView]}resourceType={{ type: 'health' }}- actions={- <LemonButton- type="secondary"- size="small"- onClick={refresh}- loading={anyLoading}- disabledReason={anyLoading ? 'Loading…' : undefined}- >- Refresh- </LemonButton>- }+ actions={activeView === 'health' ? <HealthRefreshButton /> : <RefreshButton />}/><LemonBanner type="info" dismissKey="engineering-analytics-alpha">Engineering analytics is in alpha. Metrics are limited to CI events, and details may change.diff --git a/products/engineering_analytics/frontend/scenes/doraLogic.ts b/products/engineering_analytics/frontend/scenes/doraLogic.tsnew file mode 100644index 000000000000..fc8e2aa33aca--- /dev/null+++ b/products/engineering_analytics/frontend/scenes/doraLogic.ts@@ -0,0 +1,221 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { ApiConfig } from 'lib/api'++import type { BoxPlotBucket } from '../components/MergeToDeployBoxPlot'+import { engineeringAnalyticsDora } from '../generated/api'+import type { DoraOverviewApi } from '../generated/api.schemas'+import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'+import { engineeringAnalyticsLogic, formatBucket, type WorkflowGranularity } from './engineeringAnalyticsLogic'++const projectId = (): string => String(ApiConfig.getCurrentProjectId())++export interface DoraScopeOption {+ value: string | null+ label: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface doraLogicValues {+ dateFrom: string | null // engineeringAnalyticsFiltersLogic+ dateTo: string | null // engineeringAnalyticsFiltersLogic+ notConnected: boolean // engineeringAnalyticsLogic+ scopeRepo: string | null // engineeringAnalyticsLogic+ sourceId: string | null // engineeringAnalyticsLogic+ boxPlotBuckets: BoxPlotBucket[]+ dora: DoraOverviewApi | null+ doraFailed: boolean+ doraLoading: boolean+ environment: string | null+ environmentOptions: DoraScopeOption[]+ environmentScopeLabel: string+ frequencyCounts: number[]+ frequencyIsoLabels: string[]+ githubTeam: string | null+ githubTeamOptions: DoraScopeOption[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface doraLogicActions {+ loadDora: () => any+ loadDoraFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadDoraSuccess: (+ dora: DoraOverviewApi,+ payload?: any+ ) => {+ dora: DoraOverviewApi+ payload?: any+ }+ setEnvironment: (environment: string | null) => {+ environment: string | null+ }+ setGithubTeam: (githubTeam: string | null) => {+ githubTeam: string | null+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface doraLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ boxPlotBuckets: (dora: DoraOverviewApi | null) => BoxPlotBucket[]+ frequencyCounts: (dora: DoraOverviewApi | null) => number[]+ frequencyIsoLabels: (dora: DoraOverviewApi | null) => string[]+ environmentScopeLabel: (dora: DoraOverviewApi | null) => string+ environmentOptions: (dora: DoraOverviewApi | null, environment: string | null) => DoraScopeOption[]+ githubTeamOptions: (dora: DoraOverviewApi | null) => DoraScopeOption[]+ }+}++export type doraLogicType = MakeLogicType<doraLogicValues, doraLogicActions, Record<string, any>, doraLogicMeta>++export const doraLogic = kea<doraLogicType>([+ path(['products', 'engineering_analytics', 'frontend', 'scenes', 'doraLogic']),++ connect(() => ({+ values: [+ engineeringAnalyticsFiltersLogic,+ ['dateFrom', 'dateTo'],+ engineeringAnalyticsLogic,+ ['sourceId', 'scopeRepo', 'notConnected'],+ ],+ })),++ actions({+ setEnvironment: (environment: string | null) => ({ environment }),+ setGithubTeam: (githubTeam: string | null) => ({ githubTeam }),+ }),++ loaders(({ values }) => ({+ dora: [+ null as DoraOverviewApi | null,+ {+ loadDora: async (): Promise<DoraOverviewApi> =>+ await engineeringAnalyticsDora(projectId(), {+ date_from: values.dateFrom ?? undefined,+ date_to: values.dateTo ?? undefined,+ environment: values.environment ?? undefined,+ github_team: values.githubTeam ?? undefined,+ source_id: values.sourceId ?? undefined,+ repo: values.scopeRepo ?? undefined,+ }),+ },+ ],+ })),++ reducers(() => ({+ // Non-400 failure only; the shared 400 "not connected" state comes from engineeringAnalyticsLogic.+ doraFailed: [+ false,+ {+ loadDora: () => false,+ loadDoraSuccess: () => false,+ loadDoraFailure: () => true,+ },+ ],+ // null means the backend's default scope: production-marked deploys, falling back to all.+ // Reset on a source/repo scope change: an environment or team from the old repo may not+ // exist on the new one, and would otherwise be sent as a silently-empty exact filter.+ environment: [+ null as string | null,+ {+ setEnvironment: (_, { environment }) => environment,+ [engineeringAnalyticsLogic.actionTypes.setSourceId]: () => null,+ [engineeringAnalyticsLogic.actionTypes.setScope]: () => null,+ },+ ],+ githubTeam: [+ null as string | null,+ {+ setGithubTeam: (_, { githubTeam }) => githubTeam,+ [engineeringAnalyticsLogic.actionTypes.setSourceId]: () => null,+ [engineeringAnalyticsLogic.actionTypes.setScope]: () => null,+ },+ ],+ })),++ selectors({+ boxPlotBuckets: [+ (s) => [s.dora],+ (dora: DoraOverviewApi | null): BoxPlotBucket[] =>+ (dora?.merge_to_deploy_series ?? []).map((bucket) => ({+ label: formatBucket(+ bucket.bucket_start,+ (dora?.series_granularity ?? 'day') as WorkflowGranularity+ ),+ count: bucket.deployed_pr_count,+ minSeconds: bucket.min_seconds,+ p25Seconds: bucket.p25_seconds,+ p50Seconds: bucket.p50_seconds,+ meanSeconds: bucket.mean_seconds,+ p75Seconds: bucket.p75_seconds,+ maxSeconds: bucket.max_seconds,+ })),+ ],+ frequencyCounts: [+ (s) => [s.dora],+ (dora: DoraOverviewApi | null): number[] =>+ (dora?.deployment_frequency_series ?? []).map((bucket) => bucket.deployment_count),+ ],+ // ISO bucket starts for the time-series frequency chart — it formats its own axis and+ // tooltip labels from the granularity, so it needs the raw timestamps, not display strings.+ frequencyIsoLabels: [+ (s) => [s.dora],+ (dora: DoraOverviewApi | null): string[] =>+ (dora?.deployment_frequency_series ?? []).map((bucket) => bucket.bucket_start),+ ],+ environmentScopeLabel: [+ (s) => [s.dora],+ (dora: DoraOverviewApi | null): string =>+ !dora || dora.environment_scope === 'production'+ ? 'production'+ : dora.environment_scope === 'persistent'+ ? 'all persistent environments'+ : dora.environment_scope,+ ],+ environmentOptions: [+ (s) => [s.dora, s.environment],+ (dora: DoraOverviewApi | null, environment: string | null): DoraScopeOption[] => [+ {+ value: null,+ // With an explicit environment selected, environment_scope echoes that pick, so+ // it can no longer describe what the default would resolve to.+ label:+ environment !== null || !dora+ ? 'Default environment'+ : dora.environment_scope === 'production'+ ? 'Production'+ : dora.environment_scope === 'persistent'+ ? 'All persistent environments'+ : `${dora.environment_scope} (default)`,+ },+ ...(dora?.environments ?? []).map((name) => ({ value: name as string | null, label: name })),+ ],+ ],+ githubTeamOptions: [+ (s) => [s.dora],+ (dora: DoraOverviewApi | null): DoraScopeOption[] => [+ { value: null, label: 'All teams' },+ ...(dora?.github_teams ?? []).map((slug) => ({ value: slug as string | null, label: slug })),+ ],+ ],+ }),++ listeners(({ actions }) => ({+ setEnvironment: () => actions.loadDora(),+ setGithubTeam: () => actions.loadDora(),+ [engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => actions.loadDora(),+ [engineeringAnalyticsLogic.actionTypes.setSourceId]: () => actions.loadDora(),+ [engineeringAnalyticsLogic.actionTypes.refresh]: () => actions.loadDora(),+ })),++ afterMount(({ actions }) => {+ actions.loadDora()+ }),+])diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.tsindex 19787bfe52b0..7c349a80adf6 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts@@ -151,8 +151,11 @@ export interface WorkflowFailureSeries {labels: string[]}-function formatBucket(bucketStart: string, granularity: WorkflowGranularity): string {- const at = dayjs(bucketStart)+/** Bucket label per the shared series granularity, for chart tooltips. */+export function formatBucket(bucketStart: string, granularity: WorkflowGranularity): string {+ // Buckets are computed server-side on UTC boundaries, so the label must read them in UTC too —+ // parsing in the browser's local timezone can shift a midnight bucket to the wrong day.+ const at = dayjs.utc(bucketStart)if (granularity === 'hour') {return at.format('MMM D, HH:mm')}@@ -1628,6 +1631,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy[urls.engineeringAnalyticsPullRequestList()]: (_, s) => applyScope(s.source, s.repo),[urls.engineeringAnalyticsWorkflows()]: (_, s) => applyScope(s.source, s.repo),[urls.engineeringAnalyticsTestHealth()]: (_, s) => applyScope(s.source, s.repo),+ [urls.engineeringAnalyticsHealth()]: (_, s) => applyScope(s.source, s.repo),}}),diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.tsindex d818ad01f987..724aed02bcd0 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsSceneLogic.ts@@ -2,8 +2,8 @@ import { MakeLogicType, connect, kea, path, selectors } from 'kea'import { sceneLogic } from '~/scenes/sceneLogic'-/** The root scene's views: the repo hub landing, the PR list page, the workflow list page, test health, and teams. */-export type EngineeringAnalyticsView = 'hub' | 'pull-requests' | 'workflows' | 'test-health' | 'teams'+/** The root scene's views: the repo hub landing, the PR list page, the workflow list page, test health, teams, and engineering health (the DORA metric family). */+export type EngineeringAnalyticsView = 'hub' | 'pull-requests' | 'workflows' | 'test-health' | 'teams' | 'health'export const VIEW_DESCRIPTIONS: Record<EngineeringAnalyticsView, string> = {hub: 'CI health, pull requests, workflows, and cost for the connected repo.',@@ -11,6 +11,7 @@ export const VIEW_DESCRIPTIONS: Record<EngineeringAnalyticsView, string> = {workflows: 'Run volume, success rate, and duration per workflow over the selected window.','test-health': 'Flaky tests under quarantine: what is masked, who owns it, and when it expires.',teams: 'CI test surfaces rolled up by owning team: flaky signal and failures, with prior-window deltas.',+ health: 'DORA-style deploy metrics from the GitHub deployments data: frequency, merge to deploy lead time, and failure proxies.',}const SCENE_KEY_TO_VIEW: Record<string, EngineeringAnalyticsView> = {@@ -19,6 +20,7 @@ const SCENE_KEY_TO_VIEW: Record<string, EngineeringAnalyticsView> = {engineeringAnalyticsWorkflows: 'workflows',engineeringAnalyticsTestHealth: 'test-health',engineeringAnalyticsTeams: 'teams',+ engineeringAnalyticsHealth: 'health',}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.diff --git a/products/engineering_analytics/manifest.tsx b/products/engineering_analytics/manifest.tsxindex 308a8b7f87ee..018d8d19cf05 100644--- a/products/engineering_analytics/manifest.tsx+++ b/products/engineering_analytics/manifest.tsx@@ -68,6 +68,7 @@ export const manifest: ProductManifest = {'/engineering-analytics/workflows': ['EngineeringAnalytics', 'engineeringAnalyticsWorkflows'],'/engineering-analytics/test-health': ['EngineeringAnalytics', 'engineeringAnalyticsTestHealth'],'/engineering-analytics/teams': ['EngineeringAnalytics', 'engineeringAnalyticsTeams'],+ '/engineering-analytics/health': ['EngineeringAnalytics', 'engineeringAnalyticsHealth'],'/engineering-analytics/teams/:ownerTeam': ['EngineeringAnalyticsTeam', 'engineeringAnalyticsTeam'],'/engineering-analytics/repos/:repoOwner/:repoName/pull-requests/:number': ['EngineeringAnalyticsPullRequest',@@ -97,6 +98,7 @@ export const manifest: ProductManifest = {engineeringAnalyticsWorkflows: (): string => '/engineering-analytics/workflows',engineeringAnalyticsTestHealth: (): string => '/engineering-analytics/test-health',engineeringAnalyticsTeams: (): string => '/engineering-analytics/teams',+ engineeringAnalyticsHealth: (): string => '/engineering-analytics/health',engineeringAnalyticsTeam: (ownerTeam: string): string =>`/engineering-analytics/teams/${encodeURIComponent(ownerTeam)}`,engineeringAnalyticsPullRequest: (repoOwner: string, repoName: string, number: number | string): string =>diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yamlindex 5d15e8a0bbfb..1643cd801539 100644--- a/products/engineering_analytics/mcp/tools.yaml+++ b/products/engineering_analytics/mcp/tools.yaml@@ -71,6 +71,31 @@ tools:engineering-analytics-current-branch-health:operation: engineering_analytics_current_branch_healthenabled: false+ engineering-analytics-dora:+ operation: engineering_analytics_dora+ enabled: false+ scopes:+ - engineering_analytics:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: DORA deploy metrics+ description: >+ DORA-style deploy metrics over the GitHub deployments + deployment_statuses warehouse pair, each headline+ with its previous-window twin: deployment frequency (deploys whose first success status landed in the+ window, per-day normalized, with a bucketed series), merge-to-deploy lead time (median seconds from a PR's+ merge to the first successful deployment at or after it, bots/drafts excluded, with a per-bucket+ min/p25/p50/mean/p75/max box-plot series), and two honest proxies: failed_deployment_share (deployments with+ a failure/error status over deployments that reached an outcome — NOT true change failure rate, since no+ incident data is linked) and median_failed_deploy_to_next_success_seconds (first failure status to the next+ successful deploy in the same environment — NOT true time-to-restore, since recovery by anything other than+ a deploy is invisible). Environments default to production-marked deploys, falling back to every persistent+ (non-transient) environment — ephemeral per-PR preview environments never join a default scope; pass+ environment to scope exactly. Pass github_team (a slug from github_teams) to narrow the PR-scoped+ merge-to-deploy figures to that team's authors — deploy counts stay repo-wide. deploy_data_available is+ false when the deployments endpoints aren't synced on the GitHub source; the fix is enabling them, not+ re-querying.engineering-analytics-flaky-tests:operation: engineering_analytics_flaky_testsenabled: truediff --git a/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md b/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.mdindex b4759f34bdb9..3e5bfd700e73 100644--- a/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md+++ b/products/engineering_analytics/skills/diagnosing-ci-and-merge-bottlenecks/SKILL.md@@ -78,8 +78,11 @@ These are structural limits of today's snapshot data — state them, don't paperfailure; lead with status, not a verdict.- **CI for a PR is the head-SHA join, nothing else.** The `ci` rollup reflects only the latest commit's runs. Thereis no other link between a PR and its checks.-- **No reviews, approvals, per-check/job, or deploys yet.** Don't infer review behaviour or DORA metrics from their- absence; that data hasn't landed. `pr-lifecycle` is `partial` for the same reason.+- **Review reads are deferred by choice.** The GitHub `reviews` endpoint syncs review submissions with their timestamps, but reads stay deferred until a wedge tool needs them. Don't infer review behaviour from their absence.+ `pr-lifecycle` is `partial` for the same reason.+- **Deploy metrics live on `engineering-analytics-dora`**, from the GitHub deployments tables when synced+ (`deploy_data_available`). Its change-failure and time-to-restore fields are deploy-status proxies (no incident+ link) — report them under their honest field names, never as the true DORA definitions.- **Bots and drafts are present in `pull-requests` output, excluded by convention.** Filter out `author.is_bot`(nested under `author`, not a row-level field) and `is_draft` for throughput / merge-time questions; keep them infor bot-impact questions.@@ -124,7 +127,8 @@ CI before merging."- Don't call `open_to_merge_seconds` cycle time or review time — it's coarse open-to-merge;`ready_to_merge_seconds` is the cycle-time figure, and only where non-null.- Don't report a CI count as a settled failure when `pending > 0` — it may be unsettled or stale.-- Don't infer reviews, approvals, per-check counts, or deploys — that data isn't ingested yet.+- Don't infer reviews or approvals — review reads stay deferred until a wedge tool needs them. Don't infer per-check counts. Deploys come from+ `engineering-analytics-dora`, not from inference.- Don't turn per-author buckets into a leaderboard — they're for finding stuck work, not ranking people.- Don't reach for these tools to fetch raw PR contents or diffs — they surface pipeline signal, not the PR thread.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c4bd358c9671..9ac1e07f7f24 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -27073,6 +27073,13 @@ export namespace Schemas {name: string;}+ export interface DeploymentFrequencyBucket {+ /** Bucket start, aligned to series_granularity (top of hour, midnight, or Monday). */+ bucket_start: string;+ /** Deployments whose first success status landed in this bucket, within the environment scope. Zero-filled: 0 means nothing shipped. */+ deployment_count: number;+ }+export interface DeprovisionWarehouseResponse {/** Deprovisioning lifecycle message, e.g. 'deprovisioning started' */status: string;@@ -28857,6 +28864,126 @@ export namespace Schemas {Selected: 'selected',} as const;+ export interface MergeToDeployBucket {+ /** Bucket start, aligned to series_granularity (top of hour, midnight, or Monday). Keyed on deploy time: a PR lands in the bucket its first post-merge deploy succeeded in. */+ bucket_start: string;+ /** PRs whose first post-merge successful deployment landed in this bucket (bots and drafts excluded; narrowed by github_team when given). */+ deployed_pr_count: number;+ /**+ * Fastest merge-to-deploy in this bucket, in seconds. Null when nothing deployed.+ * @nullable+ */+ min_seconds: number | null;+ /**+ * 25th percentile merge-to-deploy seconds. Null when nothing deployed.+ * @nullable+ */+ p25_seconds: number | null;+ /**+ * Median merge-to-deploy seconds. Null when nothing deployed.+ * @nullable+ */+ p50_seconds: number | null;+ /**+ * Mean merge-to-deploy seconds. Null when nothing deployed.+ * @nullable+ */+ mean_seconds: number | null;+ /**+ * 75th percentile merge-to-deploy seconds. Null when nothing deployed.+ * @nullable+ */+ p75_seconds: number | null;+ /**+ * Slowest merge-to-deploy in this bucket, in seconds. Null when nothing deployed.+ * @nullable+ */+ max_seconds: number | null;+ }++ export interface DoraOverview {+ /** Successful deployments per bucket across the window, oldest first, zero-filled, bucketed by series_granularity. Empty when the deploy tables aren't synced. */+ deployment_frequency_series: DeploymentFrequencyBucket[];+ /** Merge-to-deploy distribution per bucket across the window, oldest first — the box-plot series (min/p25/p50/mean/p75/max seconds per bucket). Empty when the deploy tables aren't synced, or when github_team was passed without membership data synced. */+ merge_to_deploy_series: MergeToDeployBucket[];+ /** False when the deployments/deployment_statuses tables aren't synced for the selected repo; every other field is then empty or null, never a fake zero. */+ deploy_data_available: boolean;+ /** What the environment filter resolved to: 'production' (deployments GitHub marks production_environment), an exact environment name (the one passed, or the busiest persistent environment when nothing is marked production), or 'persistent' (no persistent environment deployed in the window, so every non-transient one counts). Transient environments (ephemeral per-PR previews) never join a default scope. The scope resolves from deployments in the scan window, so two different windows can resolve different scopes and are not always comparable. */+ environment_scope: string;+ /** Distinct persistent environments deployed to in the scan window, most-deployed first — the environment picker's options. Transient environments are omitted but stay reachable by exact name. */+ environments: string[];+ /** True when the optional team-membership snapshot is synced. When false, a github_team filter cannot be honored and the merge-to-deploy figures go empty rather than silently unfiltered. */+ has_membership_data: boolean;+ /** Distinct GitHub team slugs from the membership snapshot, sorted — the team picker's options. Empty when membership isn't synced. */+ github_teams: string[];+ /** Deployments whose first success status landed in the window, within the environment scope. */+ deployment_count: number;+ /** Same count over the equal-length window before date_from. */+ deployment_count_prev: number;+ /**+ * deployment_count normalized by the window length in days. Null only when the deploy tables aren't synced.+ * @nullable+ */+ deployments_per_day: number | null;+ /**+ * Previous-window twin of deployments_per_day. Null only when the deploy tables aren't synced.+ * @nullable+ */+ deployments_per_day_prev: number | null;+ /**+ * Median seconds from a PR's merge to the first successful deployment containing it (bots/drafts excluded; narrowed by github_team when given). Containment is resolved through the deploy's head commit, not the deploy's success time. Keyed on deploy time. This is merge-to-deploy, not full commit-to-deploy DORA lead time. Null when nothing deployed in the window.+ * @nullable+ */+ median_merge_to_deploy_seconds: number | null;+ /**+ * Previous-window twin of median_merge_to_deploy_seconds.+ * @nullable+ */+ median_merge_to_deploy_seconds_prev: number | null;+ /** PRs first deployed in the window — the population behind the merge-to-deploy median and box plot. */+ deployed_pr_count: number;+ /** Previous-window twin of deployed_pr_count. */+ deployed_pr_count_prev: number;+ /** Deployments with at least one failure/error status, keyed on the first failure time. */+ failed_deployment_count: number;+ /** Previous-window twin of failed_deployment_count. */+ failed_deployment_count_prev: number;+ /**+ * Failed deployments over deployments that reached any outcome (success or failure). A change-failure proxy: no incident data is linked, so a deploy that succeeded but broke production is not counted. Null when nothing reached an outcome.+ * @nullable+ */+ failed_deployment_share: number | null;+ /**+ * Previous-window twin of failed_deployment_share.+ * @nullable+ */+ failed_deployment_share_prev: number | null;+ /**+ * Median seconds from a deployment's first failure status to the next successful deployment in the same environment. A time-to-restore proxy: recovery by anything other than a deploy is invisible, and failures not yet recovered are excluded. Null when no failed deploy recovered in the window.+ * @nullable+ */+ median_failed_deploy_to_next_success_seconds: number | null;+ /**+ * Previous-window twin of median_failed_deploy_to_next_success_seconds.+ * @nullable+ */+ median_failed_deploy_to_next_success_seconds_prev: number | null;+ /** PRs merged in the window (bots and drafts excluded; narrowed by github_team when given) — the denominator behind unattributed_merged_pr_share. */+ merged_pr_count: number;+ /**+ * Share of merged_pr_count no successful in-scope deployment attributed: recent merges still waiting for their deploy, plus merges whose deploy the scope or scan bounds miss. Null when nothing merged in the window.+ * @nullable+ */+ unattributed_merged_pr_share: number | null;+ /**+ * The newest deployment status row synced, any environment — how fresh the deploy data is. Windows ending after this instant undercount. Null when the deploy tables are empty.+ * @nullable+ */+ latest_deploy_status_at: string | null;+ /** Bucket width of both series, chosen to fit the window: 'hour', 'day', or 'week'. */+ series_granularity: string;+ }+export interface DraftCustomManifestRequest {/** Optional human name of the API being connected (e.g. 'Acme CRM'). Used only to orient the model. */source_name?: string;@@ -91351,6 +91478,33 @@ export namespace Schemas {source_id?: string;};+ export type EngineeringAnalyticsDoraParams = {+ /**+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.+ */+ date_from?: string;+ /**+ * Window end: relative or ISO8601. Defaults to now.+ */+ date_to?: string;+ /**+ * Exact deploy environment to scope to (from the response's `environments` list). Omit to scope to production-marked deployments, falling back to every persistent (non-transient) environment when none are marked production.+ */+ environment?: string;+ /**+ * GitHub team slug (from the response's `github_teams` list) to narrow the PR-scoped merge-to-deploy figures to that team's authors. Deploy counts stay repo-wide. Needs the team-membership snapshot synced; without it the merge-to-deploy figures return empty rather than silently unfiltered.+ */+ github_team?: string;+ /**+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.+ */+ 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 EngineeringAnalyticsFlakyTestsParams = {/*** Window start: relative ('-7d', '-30d') or ISO8601. Defaults to -7d; the window may span at most 30 days.diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.jsonindex e456a9093eea..99d7eb298158 100644--- a/services/mcp/src/tools/links/app-url-manifest.json+++ b/services/mcp/src/tools/links/app-url-manifest.json@@ -574,6 +574,11 @@"params": ["handle"],"scope": "project"},+ "engineeringAnalyticsHealth": {+ "template": "/engineering-analytics/health",+ "params": [],+ "scope": "project"+ },"engineeringAnalyticsPullRequest": {"template": "/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}","params": ["repoOwner", "repoName", "number"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.jsonindex e5d43b055fac..4a9126829a9a 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json@@ -13,7 +13,7 @@"type": "object"},"url": {- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/button-tiles/{buttonTileId}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/text-tiles/{textTileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/comments\n/data-management/comments/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/actions/{actionId}\n/replay-vision/actions/{actionId}/edit\n/replay-vision/actions/{actionId}/runs/{runId}\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay-vision/{scannerId}/actions/new\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/button-tiles/{buttonTileId}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/text-tiles/{textTileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/comments\n/data-management/comments/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/actions/{actionId}\n/replay-vision/actions/{actionId}/edit\n/replay-vision/actions/{actionId}/runs/{runId}\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay-vision/{scannerId}/actions/new\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}","type": "string"}},