Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(ci): fix flake overseer rerun outcomes (#65573)

Raúl Negrón-Otero04a918a4fef6
diff --git a/.github/scripts/ci_flake_overseer.py b/.github/scripts/ci_flake_overseer.py
index a858a56a2000..eee592f24c8a 100644
--- a/.github/scripts/ci_flake_overseer.py
+++ b/.github/scripts/ci_flake_overseer.py
@@ -12,6 +12,7 @@ import subprocess
import urllib.error
import urllib.request
from dataclasses import dataclass
+from datetime import datetime
from pathlib import Path
from typing import Literal, cast
@@ -91,6 +92,9 @@ class Job:
conclusion: str | None
run_attempt: int
html_url: str
+ # A genuine re-run advances started_at; a carried-over job keeps the prior attempt's value byte-for-byte
+ # (run_attempt reports the latest attempt for every job either way), so started_at is the re-run signal.
+ started_at: str | None = None
steps: tuple[Step, ...] = ()
def failed_step_names(self) -> tuple[str, ...]:
@@ -106,6 +110,8 @@ class WorkflowRun:
head_sha: str
run_attempt: int
html_url: str
+ head_branch: str = ""
+ event: str = ""
@dataclass(frozen=True)
@@ -113,6 +119,8 @@ class Decision:
action: DecisionAction
reason: str
job: Job
+ # Which signal classified an `observe`: the job name or a failed step. Surfaces silent allowlist drift.
+ classified_via: str | None = None
def as_str(value: object) -> str | None:
@@ -167,6 +175,8 @@ def workflow_run_from_object(raw: JsonObject) -> WorkflowRun:
head_sha=as_str(raw.get("head_sha")) or "",
run_attempt=as_int(raw.get("run_attempt")) or 1,
html_url=as_str(raw.get("html_url")) or "",
+ head_branch=as_str(raw.get("head_branch")) or "",
+ event=as_str(raw.get("event")) or "",
)
@@ -189,6 +199,7 @@ def job_from_object(raw: JsonObject, run_attempt: int) -> Job:
# Trust the job's own attempt over the requested one — the fallback endpoint returns the latest attempt.
run_attempt=as_int(raw.get("run_attempt")) or run_attempt,
html_url=as_str(raw.get("html_url")) or "",
+ started_at=as_str(raw.get("started_at")),
steps=tuple(
Step(name=as_str(step.get("name")) or "", conclusion=as_str(step.get("conclusion")))
for step in as_object_list(raw.get("steps"))
@@ -196,13 +207,18 @@ def job_from_object(raw: JsonObject, run_attempt: int) -> Job:
)
-def fetch_jobs(repo: str, run_id: int, run_attempt: int) -> tuple[Job, ...]:
+def fetch_jobs(repo: str, run_id: int, run_attempt: int, *, strict: bool = False) -> tuple[Job, ...]:
jobs: list[Job] = []
page = 1
while True:
try:
raw = gh_json(repo, f"actions/runs/{run_id}/attempts/{run_attempt}/jobs?per_page=100&page={page}")
except ExternalCommandError:
+ # The non-attempt endpoint returns the LATEST attempt, so it can't stand in for an arbitrary
+ # prior attempt. Strict callers need exact rows, so fail closed (drop any partial pages) rather
+ # than return a truncated set or a masquerading attempt.
+ if strict:
+ return ()
raw = gh_json(repo, f"actions/runs/{run_id}/jobs?per_page=100&page={page}")
page_jobs = as_object_list(raw.get("jobs"))
jobs.extend(job_from_object(job, run_attempt) for job in page_jobs)
@@ -222,19 +238,28 @@ def deterministic_reason(job: Job) -> str | None:
return None
-def is_test_job_failure(job: Job) -> bool:
+def test_failure_source(job: Job) -> str | None:
if any(pattern.search(job.name) for pattern in TEST_JOB_PATTERNS):
- return True
- return any(pattern.search(step_name) for step_name in job.failed_step_names() for pattern in TEST_STEP_PATTERNS)
+ return "job_name"
+ if any(pattern.search(step_name) for step_name in job.failed_step_names() for pattern in TEST_STEP_PATTERNS):
+ return "step"
+ return None
+
+
+def is_test_job_failure(job: Job) -> bool:
+ return test_failure_source(job) is not None
def classify_job(job: Job) -> Decision:
deterministic = deterministic_reason(job)
if deterministic is not None:
return Decision(action="skip deterministic", reason=deterministic, job=job)
- if not is_test_job_failure(job):
+ source = test_failure_source(job)
+ if source is None:
return Decision(action="skip non-test", reason="failed job or step is not an allowlisted test runner", job=job)
- return Decision(action="observe", reason="test job failure tracked for rerun outcome", job=job)
+ return Decision(
+ action="observe", reason="test job failure tracked for rerun outcome", job=job, classified_via=source
+ )
def classify_failed_jobs(repo: str, run_id: int, run_attempt: int) -> tuple[Decision, ...]:
@@ -250,6 +275,10 @@ def base_event_properties(repo: str, workflow_run: WorkflowRun) -> JsonObject:
"run_id": workflow_run.id,
"run_url": workflow_run.html_url,
"head_sha": workflow_run.head_sha,
+ "head_branch": workflow_run.head_branch,
+ # Master failures block the deploy gate; PR failures only annoy the author — keep them separable.
+ "is_master": workflow_run.head_branch in {"master", "main"},
+ "trigger_event": workflow_run.event,
# Reuse the project's existing workflow_run group so events roll up per CI run.
"$groups": {"workflow_run": str(workflow_run.id)},
}
@@ -264,10 +293,15 @@ def build_decision_events(repo: str, workflow_run: WorkflowRun, decisions: tuple
{
"action": decision.action,
"reason": decision.reason,
+ "classified_via": decision.classified_via,
"job_name": job.name,
"job_id": job.id,
"job_url": job.html_url,
+ "job_conclusion": job.conclusion,
+ "failed_steps": list(job.failed_step_names()),
"run_attempt": job.run_attempt,
+ # Dedupe duplicate workflow_run deliveries so the count panels stay accurate.
+ "$insert_id": f"decision:{workflow_run.id}:{workflow_run.run_attempt}:{job.id}",
}
)
events.append({"event": DECISION_EVENT, "distinct_id": repo, "properties": properties})
@@ -282,33 +316,85 @@ def rerun_outcome_label(conclusion: str | None) -> str:
return "unknown"
+def parse_timestamp(value: str | None) -> datetime | None:
+ if not value:
+ return None
+ try:
+ # Normalize a trailing `Z` for parsers that don't accept the military-zulu suffix.
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+
+
+def job_was_reexecuted(prior_job: Job, current_job: Job) -> bool:
+ # A real re-run advances started_at; a carried-over job keeps the prior attempt's value. Compare parsed
+ # instants, not raw strings, so a `+00:00` vs `Z` form can't misorder. Missing/unparseable timestamps
+ # can't prove re-execution, so treat them as not re-run rather than guess.
+ prior = parse_timestamp(prior_job.started_at)
+ current = parse_timestamp(current_job.started_at)
+ if prior is None or current is None:
+ return False
+ return current > prior
+
+
+def rerun_outcome(prior_job: Job, current_job: Job | None) -> str:
+ # `current_job is None` covers a job missing from the current attempt or an ambiguous (duplicated) name.
+ if current_job is None:
+ return "unknown"
+ if not job_was_reexecuted(prior_job, current_job):
+ return "not_rerun"
+ return rerun_outcome_label(current_job.conclusion)
+
+
+def index_unique_jobs_by_name(jobs: tuple[Job, ...]) -> dict[str, Job]:
+ # Job names are unique within an attempt; if one ever repeats, drop it so an ambiguous match becomes
+ # `unknown` instead of silently picking the wrong row.
+ by_name: dict[str, Job] = {}
+ ambiguous: set[str] = set()
+ for job in jobs:
+ if job.name in by_name:
+ ambiguous.add(job.name)
+ by_name[job.name] = job
+ for name in ambiguous:
+ by_name.pop(name, None)
+ return by_name
+
+
def report_rerun_outcomes(repo: str, workflow_run: WorkflowRun) -> list[JsonObject]:
# Outcomes only exist once a re-run attempt has completed. Find the test-job failures from the prior
# attempt, then read how they concluded this attempt — the base-rate signal: do reruns clear flakes?
if workflow_run.run_attempt <= 1:
return []
prior_attempt = workflow_run.run_attempt - 1
- observed = {
- decision.job.name
- for decision in classify_failed_jobs(repo, workflow_run.id, prior_attempt)
- if decision.action == "observe"
+ # Fetch the prior attempt strict: the non-attempt fallback returns the LATEST attempt, which would alias
+ # as "prior" and collapse the started_at re-execution check. The current attempt IS the latest, so it
+ # keeps the fallback (the non-attempt endpoint returns it correctly). Both sides dedupe ambiguous names.
+ prior_observed = {
+ name: job
+ for name, job in index_unique_jobs_by_name(
+ fetch_jobs(repo, workflow_run.id, prior_attempt, strict=True)
+ ).items()
+ if job.conclusion in {"failure", "timed_out"} and classify_job(job).action == "observe"
}
- if not observed:
+ if not prior_observed:
return []
- current_conclusions = {
- job.name: job.conclusion for job in fetch_jobs(repo, workflow_run.id, workflow_run.run_attempt)
- }
+ current_by_name = index_unique_jobs_by_name(fetch_jobs(repo, workflow_run.id, workflow_run.run_attempt))
events: list[JsonObject] = []
- for job_name in sorted(observed):
- conclusion = current_conclusions.get(job_name)
+ for job_name in sorted(prior_observed):
+ prior_job = prior_observed[job_name]
+ current_job = current_by_name.get(job_name)
properties = base_event_properties(repo, workflow_run)
properties.update(
{
- "outcome": rerun_outcome_label(conclusion),
- "current_conclusion": conclusion,
+ "outcome": rerun_outcome(prior_job, current_job),
+ "current_conclusion": current_job.conclusion if current_job else None,
+ "prior_conclusion": prior_job.conclusion,
"job_name": job_name,
+ "failed_steps": list(prior_job.failed_step_names()),
"prior_attempt": prior_attempt,
"attempt": workflow_run.run_attempt,
+ # Dedupe duplicate workflow_run deliveries so the base-rate counts stay accurate.
+ "$insert_id": f"outcome:{workflow_run.id}:{workflow_run.run_attempt}:{job_name}",
}
)
events.append({"event": OUTCOME_EVENT, "distinct_id": repo, "properties": properties})
diff --git a/.github/scripts/test_ci_flake_overseer.py b/.github/scripts/test_ci_flake_overseer.py
index 85c5a715d719..26b7cdd57628 100644
--- a/.github/scripts/test_ci_flake_overseer.py
+++ b/.github/scripts/test_ci_flake_overseer.py
@@ -27,6 +27,7 @@ def make_job(
run_attempt: int = 1,
conclusion: str = "failure",
failed_step: str = "Run Core tests",
+ started_at: str = "2026-06-05T21:00:00Z",
) -> Job:
return Job(
id=123,
@@ -34,11 +35,12 @@ def make_job(
conclusion=conclusion,
run_attempt=run_attempt,
html_url="https://github.com/PostHog/posthog/actions/runs/1/job/123",
+ started_at=started_at,
steps=(Step(name=failed_step, conclusion="failure"),),
)
-def make_workflow_run(run_attempt: int = 1) -> WorkflowRun:
+def make_workflow_run(run_attempt: int = 1, *, head_branch: str = "", event: str = "pull_request") -> WorkflowRun:
return WorkflowRun(
id=999,
workflow_id=42,
@@ -47,6 +49,8 @@ def make_workflow_run(run_attempt: int = 1) -> WorkflowRun:
head_sha="abc123",
run_attempt=run_attempt,
html_url="https://github.com/PostHog/posthog/actions/runs/999",
+ head_branch=head_branch,
+ event=event,
)
@@ -128,7 +132,12 @@ def test_build_decision_events_one_event_per_decision() -> None:
assert first["workflow_name"] == "Backend CI"
assert first["job_name"] == "Django tests - Temporal (1/1)"
assert first["$groups"] == {"workflow_run": "999"}
+ assert first["classified_via"] == "job_name"
+ assert first["job_conclusion"] == "failure"
+ assert first["failed_steps"] == ["Run Core tests"]
+ assert first["$insert_id"] == "decision:999:1:123"
assert events[1]["properties"]["action"] == "skip non-test"
+ assert events[1]["properties"]["classified_via"] is None
@pytest.mark.parametrize(
@@ -162,10 +171,11 @@ def test_report_rerun_outcomes_attributes_prior_test_failure(
) -> None:
job_name = "Django tests - Temporal (1/1)"
- def fake_fetch_jobs(repo: str, run_id: int, attempt: int) -> tuple[Job, ...]:
+ def fake_fetch_jobs(repo: str, run_id: int, attempt: int, *, strict: bool = False) -> tuple[Job, ...]:
if attempt == 1:
- return (make_job(job_name, conclusion="failure"),)
- return (make_job(job_name, conclusion=current_conclusion),)
+ return (make_job(job_name, conclusion="failure", started_at="2026-06-05T21:00:00Z"),)
+ # Advanced started_at: this attempt genuinely re-executed the job.
+ return (make_job(job_name, conclusion=current_conclusion, started_at="2026-06-05T22:00:00Z"),)
monkeypatch.setattr(ci_flake_overseer, "fetch_jobs", fake_fetch_jobs)
@@ -176,12 +186,86 @@ def test_report_rerun_outcomes_attributes_prior_test_failure(
props = events[0]["properties"]
assert props["outcome"] == expected_outcome
assert props["job_name"] == job_name
+ assert props["prior_conclusion"] == "failure"
assert props["prior_attempt"] == 1
assert props["attempt"] == 2
+ assert props["$insert_id"] == f"outcome:999:2:{job_name}"
+
+
+def test_report_rerun_outcomes_not_rerun_when_started_at_unchanged(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The regression this fix targets: a failed job carried over (never re-executed) keeps its prior
+ # started_at and conclusion. It must read as `not_rerun`, never `still_failing`.
+ job_name = "Django tests - Temporal (1/1)"
+
+ def fake_fetch_jobs(repo: str, run_id: int, attempt: int, *, strict: bool = False) -> tuple[Job, ...]:
+ return (make_job(job_name, conclusion="failure", started_at="2026-06-05T21:00:00Z"),)
+
+ monkeypatch.setattr(ci_flake_overseer, "fetch_jobs", fake_fetch_jobs)
+
+ events = report_rerun_outcomes("PostHog/posthog", make_workflow_run(run_attempt=2))
+
+ assert len(events) == 1
+ assert events[0]["properties"]["outcome"] == "not_rerun"
+
+
+def test_report_rerun_outcomes_unknown_when_job_absent(monkeypatch: pytest.MonkeyPatch) -> None:
+ job_name = "Django tests - Temporal (1/1)"
+
+ def fake_fetch_jobs(repo: str, run_id: int, attempt: int, *, strict: bool = False) -> tuple[Job, ...]:
+ if attempt == 1:
+ return (make_job(job_name, conclusion="failure"),)
+ return () # job missing from the re-run attempt
+
+ monkeypatch.setattr(ci_flake_overseer, "fetch_jobs", fake_fetch_jobs)
+
+ events = report_rerun_outcomes("PostHog/posthog", make_workflow_run(run_attempt=2))
+
+ assert len(events) == 1
+ assert events[0]["properties"]["outcome"] == "unknown"
+
+
+def test_report_rerun_outcomes_unknown_when_current_name_ambiguous(monkeypatch: pytest.MonkeyPatch) -> None:
+ job_name = "Django tests - Temporal (1/1)"
+
+ def fake_fetch_jobs(repo: str, run_id: int, attempt: int, *, strict: bool = False) -> tuple[Job, ...]:
+ if attempt == 1:
+ return (make_job(job_name, conclusion="failure"),)
+ # Two current jobs share a name: ambiguous, so it can't be paired and must read as unknown.
+ return (
+ make_job(job_name, conclusion="success", started_at="2026-06-05T22:00:00Z"),
+ make_job(job_name, conclusion="failure", started_at="2026-06-05T22:00:00Z"),
+ )
+
+ monkeypatch.setattr(ci_flake_overseer, "fetch_jobs", fake_fetch_jobs)
+
+ events = report_rerun_outcomes("PostHog/posthog", make_workflow_run(run_attempt=2))
+
+ assert len(events) == 1
+ assert events[0]["properties"]["outcome"] == "unknown"
+
+
+ ("head_branch", "event", "expected_is_master"),
+ [
+ pytest.param("master", "push", True, id="master-is-master"),
+ pytest.param("main", "push", True, id="main-is-master"),
+ pytest.param("some-feature", "pull_request", False, id="pr-branch-not-master"),
+ ],
+)
+def test_build_decision_events_is_master(head_branch: str, event: str, expected_is_master: bool) -> None:
+ decisions = (classify_job(make_job("Django tests - Temporal (1/1)")),)
+
+ events = build_decision_events(
+ "PostHog/posthog", make_workflow_run(head_branch=head_branch, event=event), decisions
+ )
+
+ props = events[0]["properties"]
+ assert props["is_master"] is expected_is_master
+ assert props["trigger_event"] == event
def test_report_rerun_outcomes_ignores_non_test_jobs(monkeypatch: pytest.MonkeyPatch) -> None:
- def fake_fetch_jobs(repo: str, run_id: int, attempt: int) -> tuple[Job, ...]:
+ def fake_fetch_jobs(repo: str, run_id: int, attempt: int, *, strict: bool = False) -> tuple[Job, ...]:
return (make_job("Build and deploy", conclusion="failure", failed_step="Compile assets"),)
monkeypatch.setattr(ci_flake_overseer, "fetch_jobs", fake_fetch_jobs)