: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): one CI signal per sharded job (#78417)
Raúl Negrón-Otero6e361009b12f
diff --git a/products/engineering_analytics/backend/logic/signals/detectors.py b/products/engineering_analytics/backend/logic/signals/detectors.pyindex b518df76dd65..94131ffa539f 100644--- a/products/engineering_analytics/backend/logic/signals/detectors.py+++ b/products/engineering_analytics/backend/logic/signals/detectors.py@@ -4,6 +4,7 @@ They compose the ``logic/queries/`` read modules instead of authoring SQL, so deMCP read surface can never disagree (SPEC §7). Thresholds are overridable arguments."""+import reimport hashlibfrom collections import defaultdictfrom datetime import UTC, datetime, timedelta@@ -59,8 +60,24 @@ DURATION_MIN_PCT_INCREASE = 0.2DURATION_MIN_ABS_INCREASE_SECONDS = 60.0+# A sharded job reports one GitHub job per shard, labeled `(i/N)`. turbo-discover.js builds the+# label into the matrix group and ci-backend.yml wraps the group mid-name for product tests, so+# the match cannot be anchored to the end of the string.+SHARD_LABEL_RE = re.compile(r"\s*\((\d+)/\d+\)")+++def _base_job_name(job_name: str) -> str:+ """The job name with its shard label removed.++ The flaky thing is the job, not the shard, and the shard count moves between runs, so a+ raw-name key splits one flaky job into a signal per shard, each gated separately by+ min_flaky_runs. Falls back to the raw name if stripping would leave nothing.+ """+ return SHARD_LABEL_RE.sub("", job_name) or job_name++def _job_key(row: FlakyJobRun) -> tuple[str, str, str, str]:- return (row.repo_owner, row.repo_name, row.workflow_name, row.job_name)+ return (row.repo_owner, row.repo_name, row.workflow_name, _base_job_name(row.job_name))def _observation_week(now: datetime) -> str:@@ -107,12 +124,20 @@ def detect_flaky_checks(findings: list[CISignalFinding] = []for (repo_owner, repo_name, workflow_name, job_name), rows in sorted(by_job.items()):- flaky_count = len(rows)+ # One run recovering on several shards is one flaky run: counting rows would let a single+ # bad run clear min_flaky_runs on its own.+ flaky_count = len({row.run_id for row in rows})if flaky_count < min_flaky_runs:continuerepo = f"{repo_owner}/{repo_name}"# The flaky thing is the job, not any one rerun: one worked example plus a count.latest = max(rows, key=lambda row: row.run_id)+ # Which shard holds the offending test is still evidence, so keep it on the worked example+ # even though it's out of the key. Distinct indices, not names: `(1/4)` and `(1/6)` are the+ # same shard slot under a drifted count.+ shard_indices = {match.group(1) for row in rows if (match := SHARD_LABEL_RE.search(row.job_name))}+ shard_note = f", spread over {len(shard_indices)} shards of the job" if len(shard_indices) > 1 else ""+ latest_shard = f" (shard '{latest.job_name}')" if latest.job_name != job_name else ""findings.append(CISignalFinding(source_type=SOURCE_TYPE_FLAKY_CHECK,@@ -123,15 +148,18 @@ def detect_flaky_checks(# Grouping titles a split report from the first line, so keep ids out of it.f"CI job '{job_name}' in workflow '{workflow_name}' is flaky on {repo}\n"f"It failed and then passed on a rerun of the same commit {flaky_count} time(s) in the "- f"last {window_days}d. Most recent: run {latest.run_id} for commit {latest.head_sha} "- f"failed on attempt {latest.failed_attempt} and passed on attempt {latest.passed_attempt}."+ f"last {window_days}d{shard_note}. Most recent: run {latest.run_id} for commit "+ f"{latest.head_sha}{latest_shard} failed on attempt {latest.failed_attempt} and passed on "+ f"attempt {latest.passed_attempt}."),weight=SIGNAL_WEIGHT,extra=EngineeringAnalyticsCIFlakyCheckSignalExtra(repo_owner=repo_owner,repo_name=repo_name,workflow_name=workflow_name,- job_name=job_name,+ # The worked example's real job name, not the shard-stripped key: downstream+ # investigation queries filter warehouse rows on the rendered name.+ job_name=latest.job_name,run_id=latest.run_id,head_sha=latest.head_sha,failed_attempt=latest.failed_attempt,diff --git a/products/engineering_analytics/backend/tests/test_ci_signals.py b/products/engineering_analytics/backend/tests/test_ci_signals.pyindex 68c614d38bf8..2f8a8ee7c273 100644--- a/products/engineering_analytics/backend/tests/test_ci_signals.py+++ b/products/engineering_analytics/backend/tests/test_ci_signals.py@@ -683,6 +683,62 @@ class TestCISignalDetectors(ClickhouseTestMixin, BaseTest):assert findings[0].extra["run_id"] == 3_assert_emittable(findings[0])+ def test_flaky_check_groups_a_sharded_job_under_one_signal(self) -> None:+ # Real rendered names with the shard label mid-name: an end-anchored match still splits+ # this job, and per-shard keys each miss min_flaky_runs, so 3 recoveries report nothing.+ now = datetime.now(UTC).replace(tzinfo=None)+ shards = [+ "Product tests (warehouse-sources (1/4), events schema legacy)",+ "Product tests (warehouse-sources (1/5), events schema legacy)",+ "Product tests (warehouse-sources (1/6), events schema legacy)",+ ]+ rows = []+ jobs = []+ for run_id, shard in enumerate(shards, start=1):+ rows.append(+ _run_row(run_id, "CI", f"shaS{run_id}", "success", now - timedelta(hours=run_id), 60, run_attempt=2)+ )+ jobs.append(+ _job_row(+ run_id * 10, run_id, shard, f"shaS{run_id}", "failure", now - timedelta(hours=run_id), run_attempt=1+ )+ )+ jobs.append(+ _job_row(+ run_id * 10 + 1,+ run_id,+ shard,+ f"shaS{run_id}",+ "success",+ now - timedelta(hours=run_id),+ run_attempt=2,+ )+ )+ findings = detect_flaky_checks(self._curated_over_runs(rows, jobs), min_flaky_runs=3)+ assert len(findings) == 1+ # The key and description group on the base name; extra keeps the worked example's real+ # job name so investigation queries on the warehouse still match.+ assert "CI job 'Product tests (warehouse-sources, events schema legacy)'" in findings[0].description+ assert findings[0].extra["job_name"] == "Product tests (warehouse-sources (1/6), events schema legacy)"+ assert findings[0].extra["flaky_count"] == 3+ # The shard the worked example came from is evidence, so it survives outside the key.+ assert "Product tests (warehouse-sources (1/6), events schema legacy)" in findings[0].description+ # `(1/4)`..`(1/6)` are all shard slot 1, so no multi-shard spread is claimed.+ assert "spread over" not in findings[0].description+ _assert_emittable(findings[0])++ def test_flaky_check_counts_runs_not_shard_recoveries(self) -> None:+ # One run recovering on three shards is one flaky run: counting query rows would let a+ # single bad run clear min_flaky_runs on its own.+ now = datetime.now(UTC).replace(tzinfo=None)+ rows = [_run_row(1, "CI", "shaQ", "success", now - timedelta(hours=1), 60, run_attempt=2)]+ jobs = []+ for index in range(1, 4):+ shard = f"Product tests (warehouse-sources ({index}/6), events schema legacy)"+ jobs.append(_job_row(index * 10, 1, shard, "shaQ", "failure", now - timedelta(hours=1), run_attempt=1))+ jobs.append(_job_row(index * 10 + 1, 1, shard, "shaQ", "success", now - timedelta(hours=1), run_attempt=2))+ assert detect_flaky_checks(self._curated_over_runs(rows, jobs), min_flaky_runs=3) == []+@parameterized.expand([# A `* Pass` gate fails only because a job it gates failed, so counting it emits a second