: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(eng-analytics): improve flaky test leaderboard (#70464)
Raúl Negrón-Otero43d892c66f6a
diff --git a/.github/scripts/test_report_test_timings.py b/.github/scripts/test_report_test_timings.pyindex 4c117bedd9f9..c3061d066f6f 100644--- a/.github/scripts/test_report_test_timings.py+++ b/.github/scripts/test_report_test_timings.py@@ -441,6 +441,7 @@ def test_workflow_resource_attributes_includes_query_and_drilldown_fields(assert attrs["ci.base_ref"] == "master"assert attrs["ci.branch"] == "worktree-per-test-telemetry-junit"assert attrs["ci.pr_number"] == 57216+ assert attrs["ci.repository"] == "PostHog/posthog"assert attrs["ci.run_url"] == "https://github.com/PostHog/posthog/actions/runs/25218527467"diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d43022998558..25e19d114583 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5635,9 +5635,9 @@ snapshots:scenes-app-engineering-analytics-repo-overview--repo-overview--light:hash: v1.k794b7964.10713695bfff7d1fe091a19db8a951832946f61cc5711f41edf479cdc443e071.j1YL510Wvt_XUK4isWUN7pSluY0kL7yvzokjkR1P1esscenes-app-engineering-analytics-test-health--flaky-test-leaderboard--dark:- hash: v1.k794b7964.b80842e3c1fcc9321fbd781d1c7aa06bdd243479eff1b407ad94466b48625e7f.vSCnKb5GwJzPTNMCRmvYw6f3fYfPbJcDlNia1tEc22E+ hash: v1.k794b7964.8e887d3516448ca8544b66f54ec2b15c348c795f5eeb38121d8822614ab6895a.FSJv5vBtsNGzICpMzsq58FRQDj-CMLwqFPl9IVKY4A4scenes-app-engineering-analytics-test-health--flaky-test-leaderboard--light:- hash: v1.k794b7964.fcab5b35c3e2147beaf8445febe839a6a30952a8bcba3fa634d7a3d073d561a3.-OVkVjtyzLUrkMi_4lDd7F39UmQPWKEvPhnf47_BxoA+ hash: v1.k794b7964.10a6793cc79056bee67f5785d2bf58cc936de9db6ccc526f85b44f051d658f94.EgZzEPDMHkx6x4Jw2IlGMf1wP1CBqkfy0jWdAsdSqAIscenes-app-error-project-unavailable--access-revoked--dark:hash: v1.k794b7964.30ace8f015100159e1dedbed07ff9f0b0b770535870d5c98ea764b10ff1f7621.dTVw9qLa7D_e7ZNme4tVuPZov-0Gg1o84aiDl5zihF0scenes-app-error-project-unavailable--access-revoked--light:diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex 5571ad3f71c2..4e2a1ef517d7 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -144,7 +144,7 @@ A PR's current CI status is the head-SHA join between the two (the `ci_rollup` C- `workflow_health` — per-workflow run count, success rate, p50/p95 duration, last failure over a `date_from`/`date_to` window, optionally scoped to a single git `branch` (`head_branch`) or PR-attributed runs excluding the default branch (`run_scope=pull_request`; master/main, same-repo PRs only). p50/p95 are over successful runs only — there is no knob, because cancelled (superseded) and failed runs end early and would bias any duration percentile low.- `pr_lifecycle` — PR header + ordered CI-run timeline (a genuine assembly; `metric_quality = "partial"` until reviews/deploys land).- `ci_failure_logs` — the thinned failure log lines for a PR's CI, grouped by job. Resolves the PR to its run_ids via the same `pull_requests` attribution as `pr_runs`, then reads the Logs product (`service.name = github-ci-logs`) joined on `run_id`. Reads from Logs, not the warehouse.-- `flaky_tests` — the flaky-test leaderboard: per-test CI spans from the Traces product (`trace_spans`, emitted by Backend CI's report-test-timings job) grouped by pytest nodeid over a window (default `-7d`, max 30 days), ranked by flakiness signal. A test qualifies by passing on retry (`rerun_passed`) at least `min_rerun_passes` times (default 1) OR failing on at least `min_failed_prs` distinct PRs (default 3). Absolute counts only, never rates — sub-threshold passing runs aren't emitted, so denominators are biased. Reads from Traces, not the warehouse.+- `flaky_tests` — the flaky-test leaderboard: per-test CI spans from the Traces product (`trace_spans`, emitted by Backend CI's report-test-timings job) grouped by pytest nodeid over a window (default `-7d`, max 30 days), scoped to the selected GitHub source via the emitted `ci.repository`, and ranked by flakiness signal. A test qualifies by passing on retry (`rerun_passed`) at least `min_rerun_passes` times (default 1) OR failing on at least `min_failed_prs` distinct PRs (default 3). Absolute counts only, never rates — sub-threshold passing runs aren't emitted, so denominators are biased. Reads from Traces, not the warehouse.**UI:** a read-only scene on the same endpoints via the generated API client — a PR list (CI status, CI duration, age), the count cards (open / stuck >7d / failing CI), and a workflow-health view. Read-only; **no saved views or stateful filters in this phase** (persisted/stateful surfaces are a later, separate decision). Columns that need deferred data — time-in-review, reviewers/approvals, per-check counts, DORA — are out until the event substrate lands (§9).diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.pyindex 621c0625bd38..94f4cc5da343 100644--- a/products/engineering_analytics/backend/logic/queries/_curated.py+++ b/products/engineering_analytics/backend/logic/queries/_curated.py@@ -54,6 +54,11 @@ class CuratedGitHubSource:"""The team this handle reads for — query builders need it for timezone-aware date parsing."""return self._team+ @property+ def repository(self) -> str:+ """The selected source's ``owner/name`` identity for reads outside the warehouse."""+ return self._tables.repository+@classmethoddef for_team(cls, team: Team, *, source_id: str | None = None, user_access_control: "UserAccessControl | None" = Nonediff --git a/products/engineering_analytics/backend/logic/queries/flaky_tests.py b/products/engineering_analytics/backend/logic/queries/flaky_tests.pyindex 7fef39d5d335..f8e3482958be 100644--- a/products/engineering_analytics/backend/logic/queries/flaky_tests.py+++ b/products/engineering_analytics/backend/logic/queries/flaky_tests.py@@ -16,7 +16,8 @@ Two data caveats shape the query:Ranking is ``rerun_passed_count + failed_pr_count``: reruns catch the rerun-enabled lanes,distinct-PRs-hit catches the rest, and neither is inflated by one broken PR failing the same-test on every push (that raises only ``failed_count``, the tiebreaker).+test on every push (that raises only ``failed_count``, the tiebreaker). Spans are scoped by+``ci.repository`` so the selected GitHub source cannot mix signals from another repository.Reads the ``posthog.trace_spans`` table on the LOGS ClickHouse cluster, not the warehouse."""@@ -59,6 +60,7 @@ _SELECT = """FROM posthog.trace_spansWHERE service_name = {service_name}AND attributes['test.outcome'] IN {signal_outcomes}+ AND lower(resource_attributes['ci.repository']) = lower({repository})AND timestamp >= {date_from} __DATE_TO__)GROUP BY nodeid@@ -97,10 +99,18 @@ def query_flaky_tests(min_failed_prs: int,limit: int,) -> FlakyTestList:+ repository = curated.repository+ # Fail closed: the spans are scoped to the source's repository. Without a repository identity we+ # cannot tell one connected repo's spans from another, so return nothing rather than leak every+ # repository's flaky signals into the selected source's leaderboard.+ if not repository:+ return FlakyTestList(items=[], truncated=False, limit=limit)+date_to_clause = "AND timestamp <= {date_to}" if date_to is not None else ""placeholders: dict[str, ast.Expr] = {"service_name": ast.Constant(value=_CI_SERVICE_NAME),"signal_outcomes": ast.Constant(value=_SIGNAL_OUTCOMES),+ "repository": ast.Constant(value=repository),"date_from": ast.Constant(value=date_from),"min_rerun_passes": ast.Constant(value=min_rerun_passes),"min_failed_prs": ast.Constant(value=min_failed_prs),diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.pyindex fb5a5fe3c2b7..8155058b1f4d 100644--- a/products/engineering_analytics/backend/logic/sources.py+++ b/products/engineering_analytics/backend/logic/sources.py@@ -49,12 +49,14 @@ _IDENTIFIER = re.compile(r"\A[A-Za-z_][A-Za-z0-9_]*\Z")@dataclass(frozen=True)class GitHubTables:- """The per-team warehouse table names the curated builders read from."""+ """The selected GitHub source identity and warehouse tables the curated layer reads."""pull_requests: strworkflow_runs: str# Optional: present only once the job-level source is synced; None means "no jobs data".workflow_jobs: str | None = None+ # Used to scope cross-store reads such as CI traces to the selected source's repository.+ repository: str = ""def resolve_github_tables(@@ -94,6 +96,7 @@ def resolve_github_tables(pull_requests=pull_requests,workflow_runs=workflow_runs,workflow_jobs=tables.get(WORKFLOW_JOBS_SCHEMA),+ repository=_source_repository(source),)if source_id is not None:raise GitHubSourceNotConnectedError(_NO_SELECTED_SOURCE)@@ -131,7 +134,7 @@ def list_github_sources(*, team: Team, user_access_control: "UserAccessControl |return [GitHubSource(id=str(source.id),- repo=str((source.job_inputs or {}).get("repository") or ""),+ repo=_source_repository(source),prefix=source.prefix or "",)for source in _github_sources(team, user_access_control)@@ -161,6 +164,19 @@ def _github_sources(team: Team, user_access_control: "UserAccessControl | None"_NO_SELECTED_SOURCE = "The selected GitHub source isn't connected or has no synced pull_requests/workflow_runs tables."+def _source_repository(source: ExternalDataSource) -> str:+ """The source's configured ``owner/repo`` identity, or '' when unset.++ ``job_inputs`` is an ``EncryptedJSONField`` that can hold any JSON value, so a non-dict+ (list/str) would crash the ``.get`` below — guard it the same way ``job_logs.coordinator``+ does, since this resolves for every engineering_analytics endpoint.+ """+ job_inputs = source.job_inputs+ if not isinstance(job_inputs, dict):+ return ""+ return str(job_inputs.get("repository") or "").strip()++def _as_source_uuid(source_id: str) -> UUID:try:return UUID(source_id)diff --git a/products/engineering_analytics/backend/tests/test_flaky_tests.py b/products/engineering_analytics/backend/tests/test_flaky_tests.pyindex 5f9dfb36551c..c8c5e800ed41 100644--- a/products/engineering_analytics/backend/tests/test_flaky_tests.py+++ b/products/engineering_analytics/backend/tests/test_flaky_tests.py@@ -11,6 +11,7 @@ from posthog.clickhouse.traces.spans import TRACE_SPANS_DISTRIBUTED_TABLE_SQL, Tfrom products.engineering_analytics.backend.logic.queries.flaky_tests import _selector_from_nodeidfrom products.engineering_analytics.backend.tests.test_views import connect_github_source_without_data+from products.warehouse_sources.backend.facade.models import ExternalDataSourceT_PRS = "posthog/api/test/test_prs/TestPRs::test_flaky_on_prs"T_RERUN = "posthog/api/test/test_rerun/TestRerun::test_pass_on_retry"@@ -19,6 +20,7 @@ T_TWO_PRS = "posthog/api/test/test_two/TestTwo::test_two_prs"T_XFAIL_ONLY = "posthog/api/test/test_xf/TestXF::test_xfail_only"T_OLD = "posthog/api/test/test_old/TestOld::test_old_flake"T_FOREIGN = "posthog/api/test/test_foreign/TestForeign::test_other_service"+T_OTHER_REPO = "posthog/api/test/test_other_repo/TestOtherRepo::test_flaky"class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):@@ -35,7 +37,7 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):@classmethoddef setUpTestData(cls):super().setUpTestData()- connect_github_source_without_data(cls.team, prefix="flaky")+ connect_github_source_without_data(cls.team, prefix="flaky", repository="PostHog/posthog")sync_execute("DROP TABLE IF EXISTS trace_spans_distributed")sync_execute("DROP TABLE IF EXISTS trace_spans")sync_execute(TRACE_SPANS_TABLE_SQL())@@ -72,6 +74,10 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):cls._span(15, T_OLD, "rerun_passed", ts=old, pr="401", branch="old1"),# Would qualify on signal alone, but a non-CI service must never reach the leaderboard.cls._span(17, T_FOREIGN, "rerun_passed", ts=cls.recent, pr="501", branch="s1", service="other-service"),+ # Would qualify on signal alone, but belongs to another connected repository.+ cls._span(+ 18, T_OTHER_REPO, "rerun_passed", ts=cls.recent, pr="601", branch="r1", repo="PostHog/posthog.com"+ ),# A job-root span carries no test.outcome and must never become a leaderboard row.cls._span(16, "Backend CI / core (1)", None, ts=cls.recent, branch="master"),]@@ -101,6 +107,7 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):branch: str = "",selector: str = "",service: str = "ci-backend",+ repo: str = "PostHog/posthog",) -> str:# Physical attributes carry a type suffix ('test.outcome__str'); the `attributes` ALIAS# column strips it. Resource attributes are stored as-is.@@ -108,7 +115,11 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):[f"'test.selector__str', '{selector}'"] if selector else [])attrs = f"map({', '.join(attr_pairs)})" if attr_pairs else "map()"- resource_pairs = ([f"'ci.pr_number', '{pr}'"] if pr else []) + ([f"'ci.branch', '{branch}'"] if branch else [])+ resource_pairs = [+ f"'{key}', '{value}'"+ for key, value in (("ci.pr_number", pr), ("ci.branch", branch), ("ci.repository", repo))+ if value+ ]resource = f"map({', '.join(resource_pairs)})" if resource_pairs else "map()"stamp = ts.strftime("%Y-%m-%d %H:%M:%S")return (@@ -126,7 +137,7 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):# Only the qualifying tests, strongest signal first (T_PRS scores 3 distinct PRs vs# T_RERUN's 2 retries); the 2-PR test, the xfail-only test, the out-of-window test, the- # outcome-less job-root span, and the foreign-service row are all excluded.+ # outcome-less job-root span, foreign-service row, and other-repo row are all excluded.assert [item["nodeid"] for item in data["items"]] == [T_PRS, T_RERUN]assert data["truncated"] is Falseassert data["limit"] == 50@@ -160,6 +171,15 @@ class TestFlakyTestsAPI(ClickhouseTestMixin, APIBaseTest):data = self._get(date_from="-30d")assert T_OLD in [item["nodeid"] for item in data["items"]]+ def test_source_without_repository_fails_closed(self):+ # A source with no repository identity can't be scoped, so the leaderboard must be empty+ # rather than leak every connected repository's flaky spans (the qualifying rows are still+ # seeded, so a fail-open regression would return them).+ ExternalDataSource.objects.filter(team_id=self.team.id).update(job_inputs={})+ data = self._get()+ assert data["items"] == []+ assert data["truncated"] is False+def test_limit_caps_and_flags_truncation(self):data = self._get(limit="1")assert [item["nodeid"] for item in data["items"]] == [T_PRS]diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.pyindex 935ee99335b4..64130401fc58 100644--- a/products/engineering_analytics/backend/tests/test_logic.py+++ b/products/engineering_analytics/backend/tests/test_logic.py@@ -628,6 +628,13 @@ class TestListGitHubSources(BaseTest):source = self._source(prefix="noinputs")assert list_github_sources(team=self.team) == [GitHubSource(id=str(source.id), repo="", prefix="noinputs")]+ def test_repo_is_blank_when_job_inputs_is_not_a_dict(self) -> None:+ # job_inputs is an EncryptedJSONField that can hold any JSON value; a non-dict must not crash+ # the shared repository read (it backs every endpoint via resolve_github_tables), just yield "".+ source = self._source(prefix="weird")+ ExternalDataSource.objects.filter(pk=source.pk).update(job_inputs=["not", "a", "dict"])+ assert list_github_sources(team=self.team) == [GitHubSource(id=str(source.id), repo="", prefix="weird")]+def test_excludes_non_github_and_soft_deleted_sources(self) -> None:self._source(prefix="stripe", source_type=ExternalDataSourceType.STRIPE)deleted = self._source(prefix="gone", repository="PostHog/posthog")diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.pyindex b1e86d793bc4..89b40bb9e25e 100644--- a/products/engineering_analytics/backend/tests/test_views.py+++ b/products/engineering_analytics/backend/tests/test_views.py@@ -33,7 +33,7 @@ GITHUB_SOURCE_PREFIX = "myprefix"def create_github_source(- team: Team, *, prefix: str = GITHUB_SOURCE_PREFIX, source_id: str = "gh-source"+ team: Team, *, prefix: str = GITHUB_SOURCE_PREFIX, source_id: str = "gh-source", repository: str = "") -> ExternalDataSource:return ExternalDataSource.objects.create(team=team,@@ -42,6 +42,7 @@ def create_github_source(status=ExternalDataSource.Status.COMPLETED,source_type=ExternalDataSourceType.GITHUB,prefix=prefix,+ job_inputs={"repository": repository} if repository else {},)@@ -70,18 +71,20 @@ def create_warehouse_table_row()-def connect_github_source_without_data(team: Team, *, prefix: str = GITHUB_SOURCE_PREFIX) -> GitHubTables:+def connect_github_source_without_data(+ team: Team, *, prefix: str = GITHUB_SOURCE_PREFIX, repository: str = ""+) -> GitHubTables:"""A GitHub source with pull_requests/workflow_runs schemas over empty ORM tables.The resolver finds these without touching object storage; pair with a mocked querywhen only resolution (not real warehouse data) matters."""- source = create_github_source(team, prefix=prefix)+ source = create_github_source(team, prefix=prefix, repository=repository)pr_table = create_warehouse_table_row(team, name=f"{prefix}github_pull_requests", source=source)run_table = create_warehouse_table_row(team, name=f"{prefix}github_workflow_runs", source=source)link_schema(team, source, name=PULL_REQUESTS_SCHEMA, table=pr_table)link_schema(team, source, name=WORKFLOW_RUNS_SCHEMA, table=run_table)- return GitHubTables(pull_requests=pr_table.name, workflow_runs=run_table.name)+ return GitHubTables(pull_requests=pr_table.name, workflow_runs=run_table.name, repository=repository)def _user(login: str) -> str:diff --git a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsxindex 380f92494ac4..9c6ee79a015e 100644--- a/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx+++ b/products/engineering_analytics/frontend/scenes/EngineeringAnalyticsTestHealth.tsx@@ -88,8 +88,9 @@ function FlakyTestLeaderboard(): JSX.Element {{title: 'Test',key: 'nodeid',+ width: 360,render: (_, row) => (- <div className="flex max-w-[32rem] flex-col gap-0.5">+ <div className="flex max-w-[22rem] flex-col gap-0.5"><Tooltip title={row.nodeid}><span className="truncate font-mono text-xs">{row.nodeid}</span></Tooltip>@@ -137,15 +138,6 @@ function FlakyTestLeaderboard(): JSX.Element {sorter: (a, b) => a.failedPrCount - b.failedPrCount,render: (_, row) => <span className="tabular-nums">{humanFriendlyNumber(row.failedPrCount)}</span>,},- {- title: 'Branches',- key: 'branchCount',- width: 100,- align: 'right',- tooltip: 'Distinct git branches across the test’s flaky-signal runs in the window.',- sorter: (a, b) => a.branchCount - b.branchCount,- render: (_, row) => <span className="tabular-nums">{humanFriendlyNumber(row.branchCount)}</span>,- },{title: 'Last seen',key: 'lastSeenAt',@@ -161,11 +153,15 @@ function FlakyTestLeaderboard(): JSX.Element {{title: '',key: 'actions',- width: 120,+ width: 130,+ align: 'right',render: (_, row) => (<LemonButtonsize="small"- type="secondary"+ type="tertiary"+ icon={<IconShieldLock />}+ tooltip="Review the evidence and owner before opening a tracking issue and quarantine PR."+ aria-label={`Quarantine ${row.nodeid}`}onClick={() =>openQuarantineModal({action: 'quarantine',@@ -218,7 +214,7 @@ function FlakyTestLeaderboard(): JSX.Element {dataSource={flakyTests?.rows ?? []}rowKey={(row) => row.nodeid}loading={flakyTestsLoading}- pagination={{ pageSize: 25 }}+ pagination={{ pageSize: 10 }}useURLForSorting={false}emptyState="No flaky tests detected in this window."nouns={['flaky test', 'flaky tests']}diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.tsindex bf771524897b..a7468ba70889 100644--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts@@ -37,6 +37,9 @@ export const PR_TABLE_LIMIT = 1000// Mirrors `workflow_health.py` `_LIMIT` (top workflows by run count).export const WORKFLOW_HEALTH_LIMIT = 100+// Mirrors the endpoint's maximum so the UI can paginate every returned leaderboard row.+export const FLAKY_TEST_LIMIT = 200+const projectId = (): string => String(ApiConfig.getCurrentProjectId())export type PRState = 'open' | 'closed' | 'merged'@@ -439,8 +442,6 @@ export interface FlakyTestRow {failedCount: number/** Distinct PRs among the failures; master/branch failures carry no PR and don't count here. */failedPrCount: number- /** Distinct branches across the test's flaky-signal spans. */- branchCount: number/** Failed while quarantined (xfail) — already masked in CI, still flaky. */xfailedCount: numberlastSeenAt: string@@ -681,6 +682,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyloadFlakyTests: async (): Promise<FlakyTestsData> => {const data = await engineeringAnalyticsFlakyTests(projectId(), {date_from: values.flakyTestWindow,+ limit: FLAKY_TEST_LIMIT,source_id: values.sourceId ?? undefined,})return {@@ -691,7 +693,6 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTyrerunPassedCount: it.rerun_passed_count,failedCount: it.failed_count,failedPrCount: it.failed_pr_count,- branchCount: it.branch_count,xfailedCount: it.xfailed_count,lastSeenAt: it.last_seen_at,})