: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
fix(engineering-analytics): reuse workflow deploy attribution (#95634)
Paul D'Ambraa2d89e82c7b7
diff --git a/products/engineering_analytics/README.md b/products/engineering_analytics/README.mdindex a574f96ab50f..a02670a4c0d4 100644--- a/products/engineering_analytics/README.md+++ b/products/engineering_analytics/README.md@@ -104,6 +104,10 @@ Shortening ready-for-review-to-merge is the headline metric this serves.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.+When a deployment's merge SHA is absent from the PR snapshot, Health reuses workflow-run `commit_pr_number` attribution for the exact deployed commit on the same repository's default branch.+The candidate PR must have merged into that branch, and must carry no merge commit of its own — one that names some other commit is evidence the suffix is wrong, not evidence the deploy carries that PR.+That drops a cherry-pick: a commit forward-ported onto the default branch keeps the original subject line, so its `(#N)` suffix still names the PR it came from, which landed elsewhere.+This fallback depends on the merge-message PR suffix and synced workflow history; unresolved deployments remain unattributed.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/backend/logic/queries/dora.py b/products/engineering_analytics/backend/logic/queries/dora.pyindex 0226af8480b2..2fc67a294ae3 100644--- a/products/engineering_analytics/backend/logic/queries/dora.py+++ b/products/engineering_analytics/backend/logic/queries/dora.py@@ -6,8 +6,9 @@ Four quadrants, honestly named (SPEC §4):window, within the environment scope. Computed directly.- Lead time: ``merge_to_deploy_seconds`` — a merged PR's wait until the firstsuccessful 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+ the deploy's head commit: its SHA resolves to a merged PR through ``merge_commit_sha``+ or the workflow-run builder's ``commit_pr_number`` fallback. Every merge at or before+ that head merge is on board. Success time alonecannot decide this — deploys ship pre-built images, so a deploy routinelysucceeds *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).@@ -48,7 +49,10 @@ from products.engineering_analytics.backend.logic.queries._buckets import (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+from products.engineering_analytics.backend.logic.queries._workflow_filters import (+ run_started_floor_constant,+ 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@@ -81,6 +85,7 @@ _DEPLOYS_CTE = """d.id AS id,any(d.sha) AS sha,any(d.environment) AS environment,+ any(d.created_at) AS created_at,minOrNullIf(s.created_at, s.state = 'success') AS first_success_at,minOrNullIf(s.created_at, s.state IN ('failure', 'error')) AS first_failure_atFROM __DEPLOYMENTS_SOURCE__ AS d@@ -156,10 +161,19 @@ _FREQUENCY_SERIES_SELECT = """# 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.+# Missing merge SHAs can resolve through the shared workflow-run attribution, restricted to the+# same repo's default branch. Direct merge-SHA evidence wins over inferred commit-message evidence,+# so the candidate PR must carry no merge commit at all: one that names a commit other than the+# deployed SHA is evidence the suffix is lying, not evidence the deploy carries that PR.+# The candidate PR must also merge INTO that branch: a cherry-pick keeps the original subject line,+# so a release-branch PR's (#N) suffix can ride a default-branch commit and hand the deploy an+# earlier head merge than the one it really contains.+# The merge is bounded by the deployment REQUEST, not its success: GitHub fixes the deployed SHA+# when it creates the record, so a PR merging while the deploy runs cannot have produced that+# commit. Crediting it would over-attribute — every merge at or before it reads as contained.# 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 (+ merge_heads AS (SELECTd.id AS id,any(d.first_success_at) AS first_success_at,@@ -171,6 +185,36 @@ _DEPLOY_HEADS_CTE = """AND hp.merged_at IS NOT NULLAND hp.merged_at >= {merge_scan_floor}GROUP BY d.id+ ),+ workflow_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 __RUNS_SOURCE__ AS r ON r.head_sha = d.sha+ INNER JOIN __PR_SOURCE__ AS hp ON hp.number = r.commit_pr_number+ WHERE d.first_success_at IS NOT NULL+ AND d.sha != ''+ AND d.id NOT IN (SELECT id FROM merge_heads)+ AND hp.merge_commit_sha = ''+ AND r.run_started_at >= {merge_scan_floor}+ AND NOT r.is_merge_queue+ AND hp.default_branch != ''+ AND r.head_branch = hp.default_branch+ AND hp.base_branch = r.head_branch+ AND r.repo_owner = hp.repo_owner AND r.repo_name = hp.repo_name+ AND hp.merged_at IS NOT NULL+ AND hp.merged_at >= {merge_scan_floor}+ AND hp.merged_at <= r.created_at+ AND hp.merged_at <= d.created_at+ GROUP BY d.id+ HAVING uniqExact(r.commit_pr_number) = 1+ ),+ deploy_heads AS (+ SELECT id, first_success_at, head_merged_at FROM merge_heads+ UNION ALL+ SELECT id, first_success_at, head_merged_at FROM workflow_heads)"""@@ -550,9 +594,11 @@ def _query_lead_time(scan: _DoraScan, *, github_team: str | None, members_sourcescan.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)+ attribution_ctes = (+ f"{scan.deploys_cte}, {_DEPLOY_HEADS_CTE}, {_DEPLOYED_PRS_CTE}".replace("__PR_SOURCE__", pr_source)+ .replace("__RUNS_SOURCE__", scan.curated.run_source(started_floor=True))+ .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)@@ -640,6 +686,7 @@ def query_dora_overview("environment_scan_floor": ast.Constant(value=_environment_scan_floor(date_from, end)),"deploy_scan_floor": ast.Constant(value=prev_from - _DEPLOY_SCAN_SLACK),"merge_scan_floor": ast.Constant(value=prev_from - _MERGE_SCAN_LOOKBACK),+ "run_started_floor": run_started_floor_constant(prev_from - _MERGE_SCAN_LOOKBACK),}if date_to is not None:placeholders["date_to"] = ast.Constant(value=date_to)diff --git a/products/engineering_analytics/backend/tests/test_dora.py b/products/engineering_analytics/backend/tests/test_dora.pyindex ec785c82db64..8c45db03f5e9 100644--- a/products/engineering_analytics/backend/tests/test_dora.py+++ b/products/engineering_analytics/backend/tests/test_dora.py@@ -22,10 +22,12 @@ from products.engineering_analytics.backend.logic.views.source_schema import (DEPLOYMENTS_COLUMNS,PULL_REQUESTS_COLUMNS,TEAM_MEMBERS_COLUMNS,+ WORKFLOW_RUNS_COLUMNS,)from products.engineering_analytics.backend.presentation.serializers.dora import DoraEnvironmentQuerySerializerfrom products.engineering_analytics.backend.tests._github_fixtures import (_pr_row,+ _run_row,connect_github_source_without_data,create_github_warehouse_table,)@@ -134,6 +136,7 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):deployment_rows: list[dict[str, Any]],status_rows: list[dict[str, Any]],pr_rows: list[dict[str, Any]],+ run_rows: list[dict[str, Any]] | None = None,member_rows: list[dict[str, Any]] | None = None,nullable_status_timestamps: bool = True,) -> CuratedGitHubSource:@@ -149,6 +152,7 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):}statuses_table = create_github_warehouse_table(self, "github_deployment_statuses", status_columns, status_rows)pr_table = create_github_warehouse_table(self, "github_pull_requests", PULL_REQUESTS_COLUMNS, pr_rows)+ runs_table = create_github_warehouse_table(self, "github_workflow_runs", WORKFLOW_RUNS_COLUMNS, run_rows or [])members_table = (create_github_warehouse_table(self, "github_team_members", TEAM_MEMBERS_COLUMNS, member_rows)if member_rows is not None@@ -158,14 +162,16 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):team=team,tables=GitHubTables(pull_requests=pr_table,- workflow_runs="unused",+ workflow_runs=runs_table,team_members=members_table,deployments=deployments_table,deployment_statuses=statuses_table,),)- def _seeded_curated(self, member_rows: list[dict[str, Any]] | None) -> CuratedGitHubSource:+ def _seeded_curated(+ self, member_rows: list[dict[str, Any]] | None, *, merge_shas_available: bool = True+ ) -> 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).@@ -202,7 +208,9 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):0,"2026-01-11 08:00:00",merged_at="2026-01-12 08:00:00",- merge_commit_sha="sha-a",+ merge_commit_sha="sha-a" if merge_shas_available else None,+ base_ref="main",+ default_branch="main",),_pr_row(2,@@ -211,7 +219,9 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):0,"2026-01-12 08:00:00",merged_at="2026-01-13 09:30:00",- merge_commit_sha="sha-c",+ merge_commit_sha="sha-c" if merge_shas_available else None,+ base_ref="main",+ default_branch="main",),# 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"),@@ -225,20 +235,42 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):0,"2026-01-05 06:00:00",merged_at="2026-01-05 08:00:00",- merge_commit_sha="sha-e",+ merge_commit_sha="sha-e" if merge_shas_available else None,+ base_ref="main",+ default_branch="main",),# 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"),],+ run_rows=[+ _run_row(+ run_id,+ "build",+ sha,+ "completed",+ "success",+ started_at,+ started_at,+ commit_message=f"Update component (#{number})",+ pr_number=4,+ )+ for run_id, sha, number, started_at in [+ (101, "sha-a", 2 if merge_shas_available else 1, "2026-01-12 08:01:00"),+ (102, "sha-a", 2 if merge_shas_available else 1, "2026-01-12 08:02:00"),+ (103, "sha-c", 2, "2026-01-13 09:31:00"),+ (104, "sha-e", 5, "2026-01-05 08:01:00"),+ ]+ ],member_rows=member_rows,)- def test_dora_over_seeded_deploys(self):+ @parameterized.expand([(True,), (False,)])+ def test_dora_over_seeded_deploys(self, merge_shas_available: bool) -> None:# 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)+ curated = self._seeded_curated(member_rows=None, merge_shas_available=merge_shas_available)result = query_dora_overview(curated=curated,date_from=datetime(2026, 1, 10, tzinfo=UTC),@@ -311,6 +343,117 @@ class TestDoraQuery(ClickhouseTestMixin, BaseTest):assert otm[datetime(2026, 1, 15)].deployed_pr_count == 0assert otd[datetime(2026, 1, 15)].p50_seconds is None+ def test_workflow_fallback_rejects_unrelated_or_ambiguous_commit_evidence(self) -> None:+ shas = [+ "feature-sha",+ "foreign-sha",+ "conflict-sha",+ "open-sha",+ "future-sha",+ "backport-sha",+ "inflight-sha",+ "reland-sha",+ "workflow-before-merge-sha",+ "missing-sha",+ ]+ started_at = "2026-01-12 08:01:00"+ curated = self._curated(+ self.team,+ deployment_rows=[+ _deployment_row(index, sha, "prod", "2026-01-12 09:00:00", production=True)+ for index, sha in enumerate(shas, start=1)+ ],+ status_rows=[+ _status_row(index + 10, index, "success", "prod", "2026-01-12 10:00:00")+ for index in range(1, len(shas) + 1)+ ],+ pr_rows=[+ _pr_row(+ number,+ "alice",+ "closed",+ 0,+ "2026-01-11 08:00:00",+ merged_at=merged_at,+ merge_commit_sha=merge_commit_sha,+ base_ref=base_ref,+ default_branch="main",+ )+ for number, merged_at, base_ref, merge_commit_sha in [+ (1, "2026-01-12 08:00:00", "main", None),+ (2, "2026-01-12 08:00:00", "main", None),+ (3, None, "main", None),+ (4, "2026-01-19 08:00:00", "main", None),+ # Merged into a release branch, then cherry-picked onto main: the forward-ported+ # commit keeps the (#5) subject, so only the base ref separates it from a real+ # default-branch merge.+ (5, "2026-01-12 08:00:00", "release-1.2", None),+ # Merged while the deployment was already running: every deployment here was+ # created 09:00 and succeeded 10:00, so this SHA was fixed before the merge and+ # the artifact cannot carry it.+ (6, "2026-01-12 09:30:00", "main", None),+ # Landed its own merge commit, so the (#7) subject on a DIFFERENT default-branch+ # commit cannot be its merge: the snapshot already says where PR 7 landed, and+ # it is not the deployed SHA.+ (7, "2026-01-12 08:00:00", "main", "pr-7-merge-sha"),+ (8, "2026-01-12 08:30:00", "main", None),+ ]+ ],+ run_rows=[+ _run_row(+ index,+ "build",+ sha,+ "completed",+ "success",+ started_at,+ started_at,+ commit_message=f"Update component (#{number})",+ head_branch=branch,+ full_name=repo,+ )+ for index, (sha, number, branch, repo) in enumerate(+ [+ ("feature-sha", 1, "feature", "PostHog/posthog"),+ ("foreign-sha", 1, "main", "example/other"),+ ("conflict-sha", 1, "main", "PostHog/posthog"),+ ("conflict-sha", 2, "main", "PostHog/posthog"),+ ("open-sha", 3, "main", "PostHog/posthog"),+ ("future-sha", 4, "main", "PostHog/posthog"),+ ("backport-sha", 5, "main", "PostHog/posthog"),+ ("inflight-sha", 6, "main", "PostHog/posthog"),+ ("reland-sha", 7, "main", "PostHog/posthog"),+ ],+ start=1,+ )+ ]+ + [+ _run_row(+ 10,+ "build",+ "workflow-before-merge-sha",+ "completed",+ "success",+ "2026-01-12 09:45:00",+ "2026-01-12 09:45:00",+ commit_message="Update component (#8)",+ )+ | {"created_at": "2026-01-12 08:01: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 == len(shas)+ assert result.deployed_pr_count == 0+ assert result.median_open_to_deploy_seconds is None+ for series in [result.open_to_deploy_series, result.open_to_merge_series, result.merge_to_deploy_series]:+ assert all(bucket.deployed_pr_count == 0 for bucket in series)+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