: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
chore(ci): add flake overseer (#64027)
Raúl Negrón-Oterof9f79a6b118d
diff --git a/.github/scripts/ci_flake_overseer.py b/.github/scripts/ci_flake_overseer.pynew file mode 100644index 000000000000..e94f801e6dd1--- /dev/null+++ b/.github/scripts/ci_flake_overseer.py@@ -0,0 +1,853 @@+#!/usr/bin/env python3+# ruff: noqa: T201 - CLI output is the contract for this script.++from __future__ import annotations++import os+import re+import sys+import json+import shlex+import argparse+import subprocess+import urllib.error+import urllib.request+from collections.abc import Callable+from dataclasses import dataclass+from pathlib import Path+from typing import Literal, Protocol, cast++JsonObject = dict[str, object]+DecisionAction = Literal["rerun", "skip deterministic", "skip unknown", "skip cap reached"]++# Insight lifecycle states worth acting on, mirroring hogli ci:insights' actionable set.+ACTIVE_INSIGHT_STATUSES = {"proposed", "in_progress", "in_review"}+DEFAULT_ALLOWED_WORKFLOWS = ("Backend CI", "Dagster CI", "E2E CI Playwright")+MAX_QUERY_COUNT = 8+MAX_INSIGHTS_PER_QUERY = 3++DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com"+DECISION_EVENT = "ci_flake_overseer_decision"+OUTCOME_EVENT = "ci_flake_overseer_rerun_outcome"+++def compile_patterns(*patterns: str) -> tuple[re.Pattern[str], ...]:+ return tuple(re.compile(pattern, re.IGNORECASE) for pattern in patterns)+++DETERMINISTIC_JOB_PATTERNS = compile_patterns(+ r"\brepo checks?\b",+ r"\bopenapi\b",+ r"\bmigrations?\b",+ r"\blint\b",+ r"\btype ?check\b",+ r"\btypescript\b",+ r"\bvisual\b",+ r"\bsnapshot\b",+ r"\bstorybook\b",+ r"\btach\b",+ r"\bimport-linter\b",+)++DETERMINISTIC_STEP_PATTERNS = compile_patterns(+ r"\bcheck module boundaries\b",+ r"\bproduct facade enforcement\b",+ r"\bopenapi\b",+ r"\bmigrations?\b",+ r"\blint\b",+ r"\btype ?check\b",+ r"\btypescript\b",+ r"\bvisual review\b",+ r"\bsnapshot\b",+ r"\bverify changed playwright tests are stable\b",+ r"\bverify new snapshots\b",+)++DETERMINISTIC_LOG_PATTERNS = compile_patterns(+ r"Repo checks failed deterministically",+ r"OpenAPI (?:type )?checks? failed deterministically",+ r"A retry cannot fix this failure",+ r"tach check --dependencies --interfaces",+ r"\blint-imports\b",+ r"OpenAPI types are out of date",+ r"hogli build:openapi",+ r"makemigrations --check",+ r"Snapshot commit job failed",+ r"does not match (?:the )?snapshot",+ r"__diff_output__",+ r"Visual Review did not complete successfully",+)++TEST_STEP_PATTERNS = compile_patterns(+ r"\brun core tests\b",+ r"\brun temporal tests\b",+ r"\brun product tests\b",+ r"\brun dagster tests\b",+ r"\brun playwright tests\b",+)++TEST_JOB_PATTERNS = compile_patterns(+ r"\bdjango tests\b",+ r"\bproduct tests\b",+ r"\bdagster tests\b",+ r"\bplaywright e2e tests\b",+)++# Case-sensitive: test identifiers and error codes are matched exactly as they appear in logs.+FAILURE_QUERY_PATTERNS = tuple(+ re.compile(pattern)+ for pattern in (+ r"FAILED\s+([A-Za-z0-9_./:-]+(?:::[A-Za-z0-9_./:-]+)*(?:\[[^\]\n]+\])?)",+ r"([A-Za-z0-9_./-]+\.py::[A-Za-z0-9_:\[\]./-]+)",+ r"\b(test_[A-Za-z0-9_]+)\b",+ r"([A-Za-z0-9_./-]+\.spec\.tsx?:\d+:\d+\s+›\s+[^\n]+)",+ r"\[[^\]\n]+\]\s+›\s+([^\n]{10,180})",+ r"\b([A-Z][A-Z0-9_]{8,})\b",+ )+)+++class ExternalCommandError(Exception):+ pass+++class InsightsUnavailable(Exception):+ pass+++@dataclass(frozen=True)+class Step:+ name: str+ conclusion: str | None+++@dataclass(frozen=True)+class Job:+ id: int+ name: str+ conclusion: str | None+ run_attempt: int+ html_url: str+ steps: tuple[Step, ...] = ()++ def failed_step_names(self) -> tuple[str, ...]:+ return tuple(step.name for step in self.steps if step.conclusion in {"failure", "timed_out"})+++@dataclass(frozen=True)+class WorkflowRun:+ id: int+ workflow_id: int+ name: str+ conclusion: str | None+ head_sha: str+ run_attempt: int+ html_url: str+++@dataclass(frozen=True)+class FlakeMatch:+ insight_id: str+ title: str+ confidence: int+ matched_query: str+ summary: str+++@dataclass(frozen=True)+class Decision:+ action: DecisionAction+ reason: str+ job: Job+ match: FlakeMatch | None = None+++class InsightsSource(Protocol):+ def find_flake(self, queries: tuple[str, ...], workflow_name: str, log: str) -> FlakeMatch | None: ...+++def as_str(value: object) -> str | None:+ return value if isinstance(value, str) else None+++def as_int(value: object) -> int | None:+ if isinstance(value, int):+ return value+ if isinstance(value, str) and value.isdigit():+ return int(value)+ return None+++def as_object(value: object) -> JsonObject:+ return cast(JsonObject, value) if isinstance(value, dict) else {}+++def as_object_list(value: object) -> list[JsonObject]:+ if not isinstance(value, list):+ return []+ return [cast(JsonObject, item) for item in value if isinstance(item, dict)]+++def as_bool_string(value: object) -> bool:+ return str(value).strip().lower() in {"1", "true", "yes", "on"}+++def env_int(name: str, default: int) -> int:+ raw = os.environ.get(name)+ if raw is None:+ return default+ try:+ return int(raw)+ except ValueError:+ return default+++def run_command(args: tuple[str, ...], timeout_seconds: int = 30) -> str:+ try:+ result = subprocess.run(args, capture_output=True, text=True, timeout=timeout_seconds)+ except (FileNotFoundError, subprocess.TimeoutExpired) as exc:+ raise ExternalCommandError(str(exc)) from exc+ if result.returncode != 0:+ message = (result.stderr or result.stdout).strip() or "command failed"+ raise ExternalCommandError(message)+ return result.stdout+++def gh_json(repo: str, path: str) -> JsonObject:+ raw = run_command(("gh", "api", f"repos/{repo}/{path}"), timeout_seconds=45)+ parsed = json.loads(raw)+ return parsed if isinstance(parsed, dict) else {}+++def gh_text(repo: str, path: str) -> str:+ return run_command(("gh", "api", f"repos/{repo}/{path}", "--method", "GET"), timeout_seconds=90)+++def gh_post(repo: str, path: str) -> None:+ run_command(("gh", "api", f"repos/{repo}/{path}", "--method", "POST", "--silent"), timeout_seconds=30)+++class CiInsightsSource:+ def __init__(self, command: tuple[str, ...], confidence_threshold: int, timeout_seconds: int) -> None:+ self.command = command+ self.confidence_threshold = confidence_threshold+ self.timeout_seconds = timeout_seconds++ def find_flake(self, queries: tuple[str, ...], workflow_name: str, log: str) -> FlakeMatch | None:+ for query in queries:+ for insight in self.search(query)[:MAX_INSIGHTS_PER_QUERY]:+ insight_id = as_str(insight.get("id"))+ if not insight_id:+ continue+ # The search payload omits confidence/status; only the detailed view can gate a rerun.+ detail = self.view(insight_id)+ if not detail:+ continue+ match = self.flake_match(detail, query, workflow_name, log)+ if match is not None:+ return match+ return None++ def search(self, query: str) -> list[JsonObject]:+ raw = self.run((*self.command, "search", query, "--json"))+ parsed = json.loads(raw)+ return as_object_list(parsed)++ def view(self, insight_id: str) -> JsonObject:+ raw = self.run((*self.command, "view", insight_id, "--json"))+ parsed = json.loads(raw)+ return parsed if isinstance(parsed, dict) else {}++ def run(self, args: tuple[str, ...]) -> str:+ try:+ return run_command(args, timeout_seconds=self.timeout_seconds)+ except ExternalCommandError as exc:+ raise InsightsUnavailable(str(exc)) from exc++ def flake_match(+ self,+ insight: JsonObject,+ query: str,+ workflow_name: str,+ log: str,+ ) -> FlakeMatch | None:+ confidence = as_int(insight.get("hypothesis_confidence")) or 0+ if confidence < self.confidence_threshold:+ return None+ status = (as_str(insight.get("status")) or "").lower()+ if status not in ACTIVE_INSIGHT_STATUSES:+ return None+ source_ref = as_object(insight.get("source_ref"))+ insight_workflow = as_str(source_ref.get("workflow_name"))+ if insight_workflow and insight_workflow != workflow_name:+ return None++ text = insight_text(insight)+ if re.search(r"\bflak(?:y|e|iness)\b|\bintermittent(?:ly)?\b", text, re.IGNORECASE) is None:+ return None+ # Require a concrete signature shared by the failure and the insight; matching on the+ # flakiness keyword alone would rerun unrelated failures.+ terms = significant_query_terms(query)+ if not terms:+ return None+ text_lower = text.lower()+ log_lower = log.lower()+ if not any(term.lower() in text_lower and term.lower() in log_lower for term in terms):+ return None++ return FlakeMatch(+ insight_id=as_str(insight.get("id")) or "ci-insight",+ title=as_str(insight.get("title")) or "CI insight",+ confidence=confidence,+ matched_query=query,+ summary=as_str(insight.get("summary")) or "",+ )+++def workflow_run_from_object(raw: JsonObject) -> WorkflowRun:+ return WorkflowRun(+ id=as_int(raw.get("id")) or 0,+ workflow_id=as_int(raw.get("workflow_id")) or 0,+ name=as_str(raw.get("name")) or as_str(raw.get("workflow_name")) or "",+ conclusion=as_str(raw.get("conclusion")),+ 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 "",+ )+++def workflow_run_from_event(path: Path) -> WorkflowRun | None:+ try:+ parsed = json.loads(path.read_text())+ except (FileNotFoundError, json.JSONDecodeError):+ return None+ if not isinstance(parsed, dict):+ return None+ workflow_run = as_object(parsed.get("workflow_run"))+ return workflow_run_from_object(workflow_run) if workflow_run else None+++def job_from_object(raw: JsonObject, run_attempt: int) -> Job:+ return Job(+ id=as_int(raw.get("id")) or 0,+ name=as_str(raw.get("name")) or "",+ conclusion=as_str(raw.get("conclusion")),+ # 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 "",+ 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"))+ ),+ )+++def fetch_jobs(repo: str, run_id: int, run_attempt: int) -> 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:+ 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)+ if len(page_jobs) < 100:+ return tuple(jobs)+ page += 1+++def fetch_runs_for_head_sha(repo: str, workflow_id: int, head_sha: str) -> tuple[WorkflowRun, ...]:+ if workflow_id == 0 or not head_sha:+ return ()+ runs: list[WorkflowRun] = []+ page = 1+ while True:+ raw = gh_json(repo, f"actions/workflows/{workflow_id}/runs?head_sha={head_sha}&per_page=100&page={page}")+ page_runs = as_object_list(raw.get("workflow_runs"))+ runs.extend(workflow_run_from_object(run) for run in page_runs)+ if len(page_runs) < 100:+ return tuple(runs)+ page += 1+++def prior_rerun_cap_reason(repo: str, workflow_run: WorkflowRun, job: Job, max_reruns_per_job: int) -> str | None:+ try:+ prior_runs = fetch_runs_for_head_sha(repo, workflow_run.workflow_id, workflow_run.head_sha)+ except ExternalCommandError:+ return None+ for prior_run in prior_runs:+ if prior_run.id == workflow_run.id or prior_run.run_attempt <= max_reruns_per_job:+ continue+ try:+ prior_jobs = fetch_jobs(repo, prior_run.id, prior_run.run_attempt)+ except ExternalCommandError:+ continue+ if any(prior_job.name == job.name for prior_job in prior_jobs):+ return (+ f"matching job already reached attempt {prior_run.run_attempt} for head SHA "+ f"{workflow_run.head_sha} in run {prior_run.id}"+ )+ return None+++def deterministic_metadata_reason(job: Job) -> str | None:+ for pattern in DETERMINISTIC_JOB_PATTERNS:+ if pattern.search(job.name):+ return f"job name matches deterministic rule `{pattern.pattern}`"+ for step_name in job.failed_step_names():+ for pattern in DETERMINISTIC_STEP_PATTERNS:+ if pattern.search(step_name):+ return f"failed step `{step_name}` matches deterministic rule `{pattern.pattern}`"+ return None+++def deterministic_log_reason(log: str) -> str | None:+ for pattern in DETERMINISTIC_LOG_PATTERNS:+ if pattern.search(log):+ return f"log matches deterministic rule `{pattern.pattern}`"+ return None+++def is_test_job_failure(job: Job) -> bool:+ 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)+++def extract_failure_queries(log: str) -> tuple[str, ...]:+ queries: list[str] = []+ for pattern in FAILURE_QUERY_PATTERNS:+ for match in pattern.finditer(log):+ query = " ".join(match.group(1).strip().split())+ if query and query not in queries:+ queries.append(query[:220])+ if len(queries) >= MAX_QUERY_COUNT:+ return tuple(queries)+ return tuple(queries)+++def significant_query_terms(query: str) -> tuple[str, ...]:+ terms: list[str] = []+ for pattern in (r"\b(test_[A-Za-z0-9_]+)\b", r"\b([A-Z][A-Z0-9_]{8,})\b"):+ terms.extend(match.group(1) for match in re.finditer(pattern, query))+ if not terms and len(query) >= 12:+ terms.append(query)+ return tuple(dict.fromkeys(terms))+++def insight_text(insight: JsonObject) -> str:+ parts = [+ as_str(insight.get("title")) or "",+ as_str(insight.get("summary")) or "",+ as_str(insight.get("hypothesis_content")) or "",+ ]+ for finding in as_object_list(insight.get("findings")):+ parts.append(as_str(finding.get("content")) or "")+ return "\n".join(parts)+++def classify_job(+ job: Job,+ get_log: Callable[[], str],+ insights: InsightsSource,+ workflow_name: str,+ max_reruns_per_job: int,+ get_cap_reached_reason: Callable[[], str | None] | None = None,+) -> Decision:+ # Resolve every cheap, metadata-only outcome before downloading the (potentially large) job log.+ metadata_deterministic = deterministic_metadata_reason(job)+ if metadata_deterministic is not None:+ return Decision(action="skip deterministic", reason=metadata_deterministic, job=job)+ # Gate on test-type before the rerun cap so a non-test job never reports "skip cap reached"+ # (which would imply raising the cap could help); the cap only ever applies to test jobs.+ if not is_test_job_failure(job):+ return Decision(action="skip unknown", reason="failed job or step is not an allowlisted test runner", job=job)+ if job.run_attempt > max_reruns_per_job:+ return Decision(+ action="skip cap reached",+ reason=f"run attempt {job.run_attempt} is above the automatic rerun cap {max_reruns_per_job}",+ job=job,+ )+ cap_reached_reason = get_cap_reached_reason() if get_cap_reached_reason is not None else None+ if cap_reached_reason is not None:+ return Decision(action="skip cap reached", reason=cap_reached_reason, job=job)++ try:+ log = get_log()+ except ExternalCommandError as exc:+ return Decision(action="skip unknown", reason=f"could not fetch job log: {exc}", job=job)++ log_deterministic = deterministic_log_reason(log)+ if log_deterministic is not None:+ return Decision(action="skip deterministic", reason=log_deterministic, job=job)++ queries = extract_failure_queries(log)+ if not queries:+ return Decision(action="skip unknown", reason="no failed test or error signature found in logs", job=job)+ try:+ match = insights.find_flake(queries, workflow_name, log)+ except InsightsUnavailable as exc:+ return Decision(action="skip unknown", reason=f"CI insights unavailable: {exc}", job=job)+ if match is None:+ return Decision(+ action="skip unknown",+ reason=f"no high-confidence known flaky signature matched: {', '.join(queries[:3])}",+ job=job,+ )+ return Decision(action="rerun", reason="matched high-confidence known flaky signature", job=job, match=match)+++def job_log_getter(repo: str, job: Job) -> Callable[[], str]:+ return lambda: gh_text(repo, f"actions/jobs/{job.id}/logs")+++def inspect_failed_jobs(+ repo: str,+ workflow_run: WorkflowRun,+ insights: InsightsSource,+ max_reruns_per_job: int,+) -> tuple[Decision, ...]:+ decisions: list[Decision] = []+ for job in fetch_jobs(repo, workflow_run.id, workflow_run.run_attempt):+ if job.conclusion not in {"failure", "timed_out"}:+ continue+ decisions.append(+ classify_job(+ job,+ job_log_getter(repo, job),+ insights,+ workflow_run.name,+ max_reruns_per_job,+ lambda job=job: prior_rerun_cap_reason(repo, workflow_run, job, max_reruns_per_job),+ )+ )+ return tuple(decisions)+++def rerun_eligible_decisions(+ repo: str,+ run_id: int,+ run_attempt: int,+ insights: InsightsSource,+ workflow_name: str,+ max_reruns_per_job: int,+) -> dict[str, Decision]:+ # Historical view used for outcome attribution: which jobs of a given attempt the overseer would+ # have reran (failed and matched a known flake). No cap closure — we want the merit-only verdict.+ eligible: dict[str, Decision] = {}+ for job in fetch_jobs(repo, run_id, run_attempt):+ if job.conclusion not in {"failure", "timed_out"}:+ continue+ decision = classify_job(+ job,+ job_log_getter(repo, job),+ insights,+ workflow_name,+ max_reruns_per_job,+ )+ if decision.action == "rerun":+ eligible[job.name] = decision+ return eligible+++def rerun_eligible_jobs(repo: str, decisions: tuple[Decision, ...], dry_run: bool) -> set[int]:+ reran_job_ids: set[int] = set()+ for decision in decisions:+ print(format_annotation(decision))+ if decision.action != "rerun":+ continue+ if dry_run:+ print(f"dry-run: would rerun job {decision.job.id} ({decision.job.name})")+ continue+ try:+ gh_post(repo, f"actions/jobs/{decision.job.id}/rerun")+ reran_job_ids.add(decision.job.id)+ print(f"reran job {decision.job.id} ({decision.job.name})")+ except ExternalCommandError as exc:+ print(f"::warning title=CI flake overseer rerun failed::{escape_annotation(f'{decision.job.name}: {exc}')}")+ return reran_job_ids+++def base_event_properties(repo: str, workflow_run: WorkflowRun, dry_run: bool, enabled: bool) -> JsonObject:+ return {+ "repo": repo,+ "workflow_name": workflow_run.name,+ "run_id": workflow_run.id,+ "run_url": workflow_run.html_url,+ "head_sha": workflow_run.head_sha,+ "dry_run": dry_run,+ "enabled": enabled,+ # Reuse the project's existing workflow_run group so events roll up per CI run.+ "$groups": {"workflow_run": str(workflow_run.id)},+ }+++def match_properties(match: FlakeMatch | None) -> JsonObject:+ if match is None:+ return {}+ return {+ "insight_id": match.insight_id,+ "insight_title": match.title,+ "insight_confidence": match.confidence,+ "matched_query": match.matched_query,+ }+++def build_decision_events(+ repo: str,+ workflow_run: WorkflowRun,+ decisions: tuple[Decision, ...],+ dry_run: bool,+ enabled: bool,+ reran_job_ids: set[int],+) -> list[JsonObject]:+ events: list[JsonObject] = []+ for decision in decisions:+ job = decision.job+ properties = base_event_properties(repo, workflow_run, dry_run, enabled)+ properties.update(+ {+ "action": decision.action,+ "reason": decision.reason,+ "job_name": job.name,+ "job_id": job.id,+ "job_url": job.html_url,+ "run_attempt": job.run_attempt,+ "reran": job.id in reran_job_ids,+ }+ )+ properties.update(match_properties(decision.match))+ events.append({"event": DECISION_EVENT, "distinct_id": repo, "properties": properties})+ return events+++def rerun_outcome_label(conclusion: str | None) -> str:+ if conclusion == "success":+ return "cleared"+ if conclusion in {"failure", "timed_out"}:+ return "still_failing"+ return "unknown"+++def report_rerun_outcomes(+ repo: str,+ workflow_run: WorkflowRun,+ insights: InsightsSource,+ max_reruns_per_job: int,+ dry_run: bool,+ enabled: bool,+) -> list[JsonObject]:+ # Outcomes only exist once a re-run attempt has completed. Re-derive which jobs the prior attempt+ # would have reran, then read how they concluded this attempt — the overseer's value/safety signal.+ if workflow_run.run_attempt <= 1:+ return []+ prior_attempt = workflow_run.run_attempt - 1+ eligible = rerun_eligible_decisions(+ repo, workflow_run.id, prior_attempt, insights, workflow_run.name, max_reruns_per_job+ )+ if not eligible:+ return []+ current_conclusions = {+ job.name: job.conclusion for job in fetch_jobs(repo, workflow_run.id, workflow_run.run_attempt)+ }+ events: list[JsonObject] = []+ for job_name, decision in eligible.items():+ conclusion = current_conclusions.get(job_name)+ properties = base_event_properties(repo, workflow_run, dry_run, enabled)+ properties.update(+ {+ "outcome": rerun_outcome_label(conclusion),+ "current_conclusion": conclusion,+ "job_name": job_name,+ "prior_attempt": prior_attempt,+ "attempt": workflow_run.run_attempt,+ }+ )+ properties.update(match_properties(decision.match))+ events.append({"event": OUTCOME_EVENT, "distinct_id": repo, "properties": properties})+ return events+++def capture_events(api_key: str, host: str, events: list[JsonObject], timeout_seconds: int = 10) -> None:+ if not api_key or not events:+ return+ payload = json.dumps({"api_key": api_key, "batch": events}).encode()+ request = urllib.request.Request(+ f"{host.rstrip('/')}/batch/",+ data=payload,+ headers={"Content-Type": "application/json"},+ method="POST",+ )+ try:+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected -- host is CI config, not request input+ with urllib.request.urlopen(request, timeout=timeout_seconds):+ pass+ except (urllib.error.URLError, TimeoutError, OSError) as exc:+ print(f"::warning title=CI flake overseer telemetry failed::{escape_annotation(str(exc))}")+++def format_annotation(decision: Decision) -> str:+ title = f"CI flake overseer: {decision.action}"+ detail = f"{decision.job.name}: {decision.reason}"+ if decision.match is not None:+ detail = (+ f"{detail}; {decision.match.title} "+ f"({decision.match.insight_id}, confidence {decision.match.confidence}, matched `{decision.match.matched_query}`)"+ )+ return f"::notice title={title}::{escape_annotation(detail)}"+++def escape_annotation(value: str) -> str:+ return value.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")+++def escape_table(value: str) -> str:+ return value.replace("|", "\\|").replace("\n", " ")+++def markdown_link(label: str, url: str) -> str:+ safe_label = escape_table(label)+ return f"[{safe_label}]({url})" if url else safe_label+++def write_summary(+ path: Path | None,+ workflow_run: WorkflowRun,+ decisions: tuple[Decision, ...],+ dry_run: bool,+ max_reruns_per_job: int,+) -> None:+ if path is None:+ return+ lines = [+ "### CI flake overseer",+ "",+ f"- Run: {markdown_link(workflow_run.name or str(workflow_run.id), workflow_run.html_url)}",+ f"- Head SHA: `{workflow_run.head_sha}`",+ f"- Attempt: `{workflow_run.run_attempt}`",+ f"- Mode: `{'dry-run' if dry_run else 'active'}`",+ f"- Max automatic reruns per job/head SHA: `{max_reruns_per_job}`",+ "",+ "| Job | Decision | Reason | Matched flake |",+ "| --- | --- | --- | --- |",+ ]+ for decision in decisions:+ match = ""+ if decision.match is not None:+ match = (+ f"`{decision.match.insight_id}`: {decision.match.title} "+ f"(confidence {decision.match.confidence}, matched `{decision.match.matched_query}`)"+ )+ lines.append(+ "| "+ f"{markdown_link(decision.job.name, decision.job.html_url)} | "+ f"`{decision.action}` | "+ f"{escape_table(decision.reason)} | "+ f"{escape_table(match)} |"+ )+ if not decisions:+ lines.append("| No failed jobs | `skip unknown` | workflow has no failed jobs to inspect | |")+ with path.open("a") as summary:+ summary.write("\n".join(lines))+ summary.write("\n")+++def default_insights_command() -> tuple[str, ...]:+ local_hogli = Path("./bin/hogli")+ executable = str(local_hogli) if local_hogli.exists() else "hogli"+ return (executable, "ci:insights")+++def parse_workflows(value: str | None) -> tuple[str, ...]:+ if not value:+ return DEFAULT_ALLOWED_WORKFLOWS+ workflows = tuple(item.strip() for item in value.split(",") if item.strip())+ return workflows or DEFAULT_ALLOWED_WORKFLOWS+++def resolve_workflow_run(args: argparse.Namespace) -> WorkflowRun:+ if args.event_path:+ from_event = workflow_run_from_event(Path(args.event_path))+ if from_event is not None and (args.run_id is None or from_event.id == args.run_id):+ return from_event+ if args.run_id is None:+ raise ValueError("--run-id is required when the event payload does not contain workflow_run")+ return workflow_run_from_object(gh_json(args.repo, f"actions/runs/{args.run_id}"))+++def parse_args(argv: list[str]) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description="Conservatively rerun CI jobs that match known flaky signatures.")+ parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY", "PostHog/posthog"))+ parser.add_argument("--run-id", type=int)+ parser.add_argument("--event-path", default=os.environ.get("GITHUB_EVENT_PATH"))+ parser.add_argument(+ "--dry-run", action="store_true", default=as_bool_string(os.environ.get("CI_FLAKE_OVERSEER_DRY_RUN", ""))+ )+ parser.add_argument(+ "--enabled", action="store_true", default=as_bool_string(os.environ.get("CI_FLAKE_OVERSEER_ENABLED", ""))+ )+ parser.add_argument(+ "--max-reruns-per-job",+ type=int,+ default=env_int("CI_FLAKE_OVERSEER_MAX_RERUNS", 1),+ )+ parser.add_argument(+ "--confidence-threshold",+ type=int,+ default=env_int("CI_FLAKE_OVERSEER_CONFIDENCE_THRESHOLD", 80),+ )+ parser.add_argument("--insights-command", default=os.environ.get("CI_FLAKE_OVERSEER_HOGLI_COMMAND", ""))+ parser.add_argument("--insights-timeout-seconds", type=int, default=20)+ parser.add_argument("--allowed-workflows", default=os.environ.get("CI_FLAKE_OVERSEER_WORKFLOWS"))+ parser.add_argument("--summary-path", default=os.environ.get("GITHUB_STEP_SUMMARY"))+ # Reuses the DevEx project token already wired into other CI workflows (report_test_timings.py,+ # monitor-github-rate-limit.js); telemetry is a no-op when the secret is absent.+ parser.add_argument("--posthog-api-key", default=os.environ.get("POSTHOG_DEVEX_PROJECT_API_TOKEN", ""))+ parser.add_argument("--posthog-host", default=os.environ.get("POSTHOG_DEVEX_PROJECT_HOST") or DEFAULT_POSTHOG_HOST)+ parser.add_argument("--posthog-timeout-seconds", type=int, default=10)+ return parser.parse_args(argv)+++def main(argv: list[str]) -> int:+ args = parse_args(argv)+ summary_path = Path(args.summary_path) if args.summary_path else None+ try:+ workflow_run = resolve_workflow_run(args)+ except Exception as exc:+ print(f"::warning title=CI flake overseer failed closed::{escape_annotation(str(exc))}")+ return 0++ if workflow_run.name not in parse_workflows(args.allowed_workflows):+ print(f"::notice title=CI flake overseer skipped::Workflow `{workflow_run.name}` is not allowlisted")+ return 0+ if not args.enabled and not args.dry_run:+ print(+ "::notice title=CI flake overseer disabled::Set CI_FLAKE_OVERSEER_ENABLED=true to enable automatic reruns"+ )+ return 0++ command = tuple(shlex.split(args.insights_command)) if args.insights_command else default_insights_command()+ insights = CiInsightsSource(command, args.confidence_threshold, args.insights_timeout_seconds)+ dry_run = args.dry_run or not args.enabled++ # On a re-run attempt, record whether our prior reruns cleared — the value/safety signal — even when+ # this attempt succeeded (so we capture the wins), regardless of dry-run mode.+ events = report_rerun_outcomes(args.repo, workflow_run, insights, args.max_reruns_per_job, dry_run, args.enabled)++ # `cancelled` runs are usually superseded by a newer commit (cancel-in-progress); reranking their+ # leftover failures would resurrect an abandoned SHA, so only classify genuine failures and timeouts.+ if workflow_run.conclusion in {"failure", "timed_out"}:+ decisions = inspect_failed_jobs(args.repo, workflow_run, insights, args.max_reruns_per_job)+ reran_job_ids = rerun_eligible_jobs(args.repo, decisions, dry_run)+ write_summary(summary_path, workflow_run, decisions, dry_run, args.max_reruns_per_job)+ events.extend(build_decision_events(args.repo, workflow_run, decisions, dry_run, args.enabled, reran_job_ids))+ else:+ print(f"::notice title=CI flake overseer skipped::Workflow conclusion is `{workflow_run.conclusion}`")++ capture_events(args.posthog_api_key, args.posthog_host, events, args.posthog_timeout_seconds)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))diff --git a/.github/scripts/test_ci_flake_overseer.py b/.github/scripts/test_ci_flake_overseer.pynew file mode 100644index 000000000000..d9f7aac543a4--- /dev/null+++ b/.github/scripts/test_ci_flake_overseer.py@@ -0,0 +1,592 @@+from __future__ import annotations++import json++import pytest++import ci_flake_overseer+from ci_flake_overseer import (+ DECISION_EVENT,+ MAX_QUERY_COUNT,+ OUTCOME_EVENT,+ CiInsightsSource,+ Decision,+ FlakeMatch,+ InsightsSource,+ Job,+ JsonObject,+ Step,+ WorkflowRun,+ build_decision_events,+ capture_events,+ classify_job,+ extract_failure_queries,+ is_test_job_failure,+ report_rerun_outcomes,+ rerun_eligible_jobs,+ rerun_outcome_label,+)+++class StaticInsights:+ def __init__(self, match: FlakeMatch | None) -> None:+ self.match = match+ self.queries: tuple[str, ...] = ()++ def find_flake(self, queries: tuple[str, ...], workflow_name: str, log: str) -> FlakeMatch | None:+ self.queries = queries+ return self.match+++def make_job(+ name: str,+ *,+ run_attempt: int = 1,+ conclusion: str = "failure",+ failed_step: str = "Run Core tests",+) -> Job:+ return Job(+ id=123,+ name=name,+ conclusion=conclusion,+ run_attempt=run_attempt,+ html_url="https://github.com/PostHog/posthog/actions/runs/1/job/123",+ steps=(Step(name=failed_step, conclusion="failure"),),+ )+++def known_flake() -> FlakeMatch:+ return FlakeMatch(+ insight_id="01KNOWNFLAKE",+ title="Flaky test: test_acheck_query_found ClickHouse query ID collision",+ confidence=85,+ matched_query="test_acheck_query_found",+ summary="test_acheck_query_found fails intermittently",+ )+++def classify(job: Job, log: str, insights: InsightsSource) -> Decision:+ return classify_job(+ job,+ lambda: log,+ insights,+ workflow_name="Backend CI",+ max_reruns_per_job=1,+ )+++def test_known_flaky_test_failure_is_rerun_eligible() -> None:+ insights = StaticInsights(known_flake())+ decision = classify(+ make_job("Django tests - Temporal (1/1)"),+ "FAILED posthog/temporal/tests/test_clickhouse.py::test_acheck_query_found\nQUERY_WITH_SAME_ID_IS_ALREADY_RUNNING",+ insights,+ )++ assert decision.action == "rerun"+ assert decision.match == known_flake()+ assert "test_acheck_query_found" in insights.queries+++ ("job", "log", "insights", "expected_action", "expected_reason_fragment"),+ [+ pytest.param(+ make_job("Repo checks (depot-ubuntu-latest)", failed_step="Check module boundaries (tach)"),+ "tach check --dependencies --interfaces\nRepo checks failed deterministically",+ StaticInsights(known_flake()),+ "skip deterministic",+ "deterministic",+ id="deterministic-repo-checks",+ ),+ pytest.param(+ make_job("Validate OpenAPI types", failed_step="Check and update OpenAPI types"),+ "OpenAPI types are out of date. To fix, run locally: hogli build:openapi",+ StaticInsights(known_flake()),+ "skip deterministic",+ "deterministic",+ id="deterministic-openapi",+ ),+ pytest.param(+ make_job("Frontend lint", failed_step="Lint with Oxlint"),+ "oxlint found errors",+ StaticInsights(known_flake()),+ "skip deterministic",+ "deterministic",+ id="deterministic-lint",+ ),+ pytest.param(+ make_job("Frontend typescript checks", failed_step="Run typescript with strict"),+ "pnpm --filter=@posthog/frontend typescript:check failed",+ StaticInsights(known_flake()),+ "skip deterministic",+ "deterministic",+ id="deterministic-typescript",+ ),+ pytest.param(+ make_job("Validate migrations", failed_step="Check migrations"),+ "python manage.py makemigrations --check --dry-run failed",+ StaticInsights(known_flake()),+ "skip deterministic",+ "deterministic",+ id="deterministic-migrations",+ ),+ pytest.param(+ make_job("Django tests - Core (1/1)", failed_step="Run Core tests"),+ "Core tests failed\nA retry cannot fix this failure",+ StaticInsights(known_flake()),+ "skip deterministic",+ "deterministic",+ id="deterministic-from-log-only",+ ),+ pytest.param(+ make_job("Build and deploy", failed_step="Compile assets"),+ "error: build failed on attempt 1",+ StaticInsights(known_flake()),+ "skip unknown",+ "not an allowlisted test runner",+ id="non-test-job",+ ),+ pytest.param(+ make_job("Django tests - Core (1/1)"),+ "FAILED posthog/test/test_something.py::test_new_regression\nAssertionError: expected 1 == 2",+ StaticInsights(None),+ "skip unknown",+ "no high-confidence known flaky signature matched",+ id="unknown-signature",+ ),+ pytest.param(+ make_job("Django tests - Temporal (1/1)", run_attempt=2),+ "FAILED posthog/temporal/tests/test_clickhouse.py::test_acheck_query_found\nQUERY_WITH_SAME_ID_IS_ALREADY_RUNNING",+ StaticInsights(known_flake()),+ "skip cap reached",+ "automatic rerun cap 1",+ id="rerun-cap-exceeded",+ ),+ ],+)+def test_failures_are_not_rerun(+ job: Job,+ log: str,+ insights: StaticInsights,+ expected_action: str,+ expected_reason_fragment: str,+) -> None:+ decision = classify(job, log, insights)++ assert decision.action == expected_action+ assert expected_reason_fragment in decision.reason+++def test_non_test_job_at_attempt_above_cap_reports_test_type_not_cap() -> None:+ decision = classify(+ make_job("Build and deploy", run_attempt=2, failed_step="Compile assets"),+ "error: build failed on attempt 2",+ StaticInsights(known_flake()),+ )++ assert decision.action == "skip unknown"+ assert "not an allowlisted test runner" in decision.reason+++def test_prior_same_sha_rerun_cap_is_not_rerun() -> None:+ decision = classify_job(+ make_job("Django tests - Temporal (1/1)"),+ lambda: (+ "FAILED posthog/temporal/tests/test_clickhouse.py::test_acheck_query_found\nQUERY_WITH_SAME_ID_IS_ALREADY_RUNNING"+ ),+ StaticInsights(known_flake()),+ workflow_name="Backend CI",+ max_reruns_per_job=1,+ get_cap_reached_reason=lambda: "matching job already reached attempt 2 for head SHA abc123",+ )++ assert decision.action == "skip cap reached"+ assert "matching job already reached attempt 2" in decision.reason+++def test_job_log_is_not_fetched_for_metadata_only_skips() -> None:+ def explode() -> str:+ raise AssertionError("log should not be fetched for a non-test job")++ decision = classify_job(+ make_job("Build and deploy", failed_step="Compile assets"),+ explode,+ StaticInsights(known_flake()),+ workflow_name="Backend CI",+ max_reruns_per_job=1,+ )++ assert decision.action == "skip unknown"+++ ("job_name", "failed_step", "expected"),+ [+ pytest.param("Django tests - Temporal (1/1)", "Run Core tests", True, id="test-job-and-test-step"),+ pytest.param(+ "Django tests - Temporal (1/1)", "Stop containers", True, id="test-job-nontest-step-falls-back-to-name"+ ),+ pytest.param("Build and deploy", "Run Playwright tests", True, id="nontest-job-test-step"),+ pytest.param("Build and deploy", "Compile assets", False, id="nontest-job-and-nontest-step"),+ ],+)+def test_is_test_job_failure(job_name: str, failed_step: str, expected: bool) -> None:+ assert is_test_job_failure(make_job(job_name, failed_step=failed_step)) is expected+++QUERY = "test_acheck_query_found"+MATCH_LOG = "FAILED posthog/temporal/tests/test_clickhouse.py::test_acheck_query_found\n"+++def make_insight(**overrides: object) -> JsonObject:+ insight: JsonObject = {+ "id": "01ABC",+ "title": "Flaky test test_acheck_query_found",+ "summary": "fails intermittently with a ClickHouse query id collision",+ "hypothesis_confidence": 90,+ "status": "proposed",+ "source_ref": {"workflow_name": "Backend CI"},+ }+ insight.update(overrides)+ return insight+++def matcher() -> CiInsightsSource:+ return CiInsightsSource(("noop",), 80, 5)+++ ("overrides", "should_match"),+ [+ pytest.param({"status": "proposed"}, True, id="status-proposed"),+ pytest.param({"status": "in_review"}, True, id="status-in-review"),+ pytest.param({"status": "in_progress"}, True, id="status-in-progress"),+ pytest.param({"status": "rejected"}, False, id="status-rejected"),+ pytest.param({"status": "open"}, False, id="status-open-not-actionable"),+ pytest.param({"hypothesis_confidence": 50}, False, id="below-confidence-threshold"),+ pytest.param(+ {"title": "test_acheck_query_found regression", "summary": "a deterministic failure"},+ False,+ id="no-flakiness-keyword",+ ),+ pytest.param({"source_ref": {"workflow_name": "E2E CI Playwright"}}, False, id="workflow-scope-mismatch"),+ ],+)+def test_flake_match_gates(overrides: dict[str, object], should_match: bool) -> None:+ match = matcher().flake_match(make_insight(**overrides), QUERY, "Backend CI", MATCH_LOG)++ assert (match is not None) is should_match+++def test_flake_match_returns_insight_details() -> None:+ match = matcher().flake_match(make_insight(), QUERY, "Backend CI", MATCH_LOG)++ assert match is not None+ assert match.insight_id == "01ABC"+ assert match.confidence == 90+ assert match.matched_query == QUERY+++def test_flake_match_requires_term_in_both_log_and_insight() -> None:+ assert matcher().flake_match(make_insight(), QUERY, "Backend CI", "unrelated failure output") is None+++def test_flake_match_skips_when_no_significant_term() -> None:+ assert matcher().flake_match(make_insight(), "boom", "Backend CI", "boom happened") is None+++class FakeCli(CiInsightsSource):+ def __init__(self, search_results: list[JsonObject], views: dict[str, JsonObject]) -> None:+ super().__init__(("noop",), 80, 5)+ self._search_results = search_results+ self._views = views++ def search(self, query: str) -> list[JsonObject]:+ return self._search_results++ def view(self, insight_id: str) -> JsonObject:+ return self._views.get(insight_id, {})+++def test_find_flake_skips_insight_with_empty_view() -> None:+ cli = FakeCli([{"id": "01ABC"}], views={})++ assert cli.find_flake((QUERY,), "Backend CI", MATCH_LOG) is None+++def test_find_flake_matches_on_detailed_view() -> None:+ cli = FakeCli([{"id": "01ABC"}], views={"01ABC": make_insight()})++ match = cli.find_flake((QUERY,), "Backend CI", MATCH_LOG)++ assert match is not None+ assert match.insight_id == "01ABC"+++def make_rerun_decision() -> Decision:+ return Decision(+ action="rerun",+ reason="matched high-confidence known flaky signature",+ job=make_job("Django tests - Temporal (1/1)"),+ match=known_flake(),+ )+++def test_rerun_eligible_jobs_calls_api_when_active(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[str] = []+ monkeypatch.setattr(ci_flake_overseer, "gh_post", lambda repo, path: calls.append(path))++ rerun_eligible_jobs("PostHog/posthog", (make_rerun_decision(),), dry_run=False)++ assert calls == ["actions/jobs/123/rerun"]+++def test_rerun_eligible_jobs_skips_api_in_dry_run(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[str] = []+ monkeypatch.setattr(ci_flake_overseer, "gh_post", lambda repo, path: calls.append(path))++ rerun_eligible_jobs("PostHog/posthog", (make_rerun_decision(),), dry_run=True)++ assert calls == []+++def make_workflow_run(run_attempt: int = 1) -> WorkflowRun:+ return WorkflowRun(+ id=999,+ workflow_id=42,+ name="Backend CI",+ conclusion="failure",+ head_sha="abc123",+ run_attempt=run_attempt,+ html_url="https://github.com/PostHog/posthog/actions/runs/999",+ )+++def test_build_decision_events_one_event_per_decision() -> None:+ decisions = (+ make_rerun_decision(),+ Decision(action="skip unknown", reason="no signature", job=make_job("Django tests - Core (1/1)")),+ )++ events = build_decision_events(+ "PostHog/posthog", make_workflow_run(), decisions, dry_run=True, enabled=False, reran_job_ids=set()+ )++ assert [event["event"] for event in events] == [DECISION_EVENT, DECISION_EVENT]+ assert all(event["distinct_id"] == "PostHog/posthog" for event in events)+ first = events[0]["properties"]+ assert first["action"] == "rerun"+ assert first["workflow_name"] == "Backend CI"+ assert first["dry_run"] is True+ assert first["reran"] is False+ assert first["insight_id"] == "01KNOWNFLAKE"+ assert first["$groups"] == {"workflow_run": "999"}+++def test_build_decision_events_marks_reran_jobs() -> None:+ [event] = build_decision_events(+ "PostHog/posthog",+ make_workflow_run(),+ (make_rerun_decision(),),+ dry_run=False,+ enabled=True,+ reran_job_ids={123},+ )++ assert event["properties"]["reran"] is True+ assert event["properties"]["enabled"] is True+++def _raise_if_called(*args: object, **kwargs: object) -> None:+ raise AssertionError("telemetry should not POST")+++def test_capture_events_noop_without_api_key(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ci_flake_overseer.urllib.request, "urlopen", _raise_if_called)++ capture_events("", "https://us.i.posthog.com", [{"event": DECISION_EVENT}])+++def test_capture_events_noop_without_events(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ci_flake_overseer.urllib.request, "urlopen", _raise_if_called)++ capture_events("phc_test", "https://us.i.posthog.com", [])+++def test_capture_events_posts_batch(monkeypatch: pytest.MonkeyPatch) -> None:+ captured: dict[str, object] = {}++ class FakeResponse:+ def __enter__(self) -> FakeResponse:+ return self++ def __exit__(self, *args: object) -> bool:+ return False++ def fake_urlopen(request: object, timeout: object = None) -> FakeResponse:+ captured["url"] = request.full_url # type: ignore[attr-defined]+ captured["body"] = json.loads(request.data.decode()) # type: ignore[attr-defined]+ return FakeResponse()++ monkeypatch.setattr(ci_flake_overseer.urllib.request, "urlopen", fake_urlopen)+ events = [{"event": DECISION_EVENT, "distinct_id": "PostHog/posthog", "properties": {}}]++ capture_events("phc_test", "https://us.i.posthog.com/", events)++ assert captured["url"] == "https://us.i.posthog.com/batch/"+ assert captured["body"] == {"api_key": "phc_test", "batch": events}+++ ("conclusion", "expected"),+ [+ pytest.param("success", "cleared", id="success-cleared"),+ pytest.param("failure", "still_failing", id="failure-still-failing"),+ pytest.param("timed_out", "still_failing", id="timed-out-still-failing"),+ pytest.param(None, "unknown", id="missing-unknown"),+ pytest.param("cancelled", "unknown", id="cancelled-unknown"),+ ],+)+def test_rerun_outcome_label(conclusion: str | None, expected: str) -> None:+ assert rerun_outcome_label(conclusion) == expected+++def test_report_rerun_outcomes_empty_on_first_attempt() -> None:+ events = report_rerun_outcomes(+ "PostHog/posthog",+ make_workflow_run(run_attempt=1),+ StaticInsights(known_flake()),+ 1,+ dry_run=True,+ enabled=False,+ )++ assert events == []+++ ("current_conclusion", "expected_outcome"),+ [+ pytest.param("success", "cleared", id="rerun-cleared"),+ pytest.param("failure", "still_failing", id="rerun-still-failing"),+ pytest.param("timed_out", "still_failing", id="rerun-timed-out"),+ ],+)+def test_report_rerun_outcomes_attributes_prior_rerun(+ monkeypatch: pytest.MonkeyPatch, current_conclusion: str, expected_outcome: str+) -> None:+ job_name = "Django tests - Temporal (1/1)"++ def fake_fetch_jobs(repo: str, run_id: int, attempt: int) -> tuple[Job, ...]:+ if attempt == 1:+ return (make_job(job_name, conclusion="failure"),)+ return (make_job(job_name, conclusion=current_conclusion),)++ monkeypatch.setattr(ci_flake_overseer, "fetch_jobs", fake_fetch_jobs)+ monkeypatch.setattr(+ ci_flake_overseer,+ "gh_text",+ lambda repo, path: "FAILED posthog/temporal/tests/test_clickhouse.py::test_acheck_query_found\n",+ )++ events = report_rerun_outcomes(+ "PostHog/posthog",+ make_workflow_run(run_attempt=2),+ StaticInsights(known_flake()),+ 1,+ dry_run=True,+ enabled=False,+ )++ assert len(events) == 1+ assert events[0]["event"] == OUTCOME_EVENT+ props = events[0]["properties"]+ assert props["outcome"] == expected_outcome+ assert props["job_name"] == job_name+ assert props["prior_attempt"] == 1+ assert props["attempt"] == 2+ assert props["insight_id"] == "01KNOWNFLAKE"+++def test_report_rerun_outcomes_ignores_non_eligible_jobs(monkeypatch: pytest.MonkeyPatch) -> None:+ def fake_fetch_jobs(repo: str, run_id: int, attempt: int) -> tuple[Job, ...]:+ return (make_job("Build and deploy", conclusion="failure", failed_step="Compile assets"),)++ monkeypatch.setattr(ci_flake_overseer, "fetch_jobs", fake_fetch_jobs)+ monkeypatch.setattr(ci_flake_overseer, "gh_text", lambda repo, path: "build failed")++ events = report_rerun_outcomes(+ "PostHog/posthog",+ make_workflow_run(run_attempt=2),+ StaticInsights(known_flake()),+ 1,+ dry_run=True,+ enabled=False,+ )++ assert events == []+++ ("log", "expected_query"),+ [+ pytest.param(+ "FAILED posthog/test/test_x.py::test_alpha[param]",+ "posthog/test/test_x.py::test_alpha[param]",+ id="pytest-failed-line",+ ),+ pytest.param(+ " posthog/temporal/tests/test_clickhouse.py::test_acheck_query_found PASSED earlier",+ "posthog/temporal/tests/test_clickhouse.py::test_acheck_query_found",+ id="py-node-id",+ ),+ pytest.param(+ "some prose mentioning test_bare_function in passing",+ "test_bare_function",+ id="bare-test-name",+ ),+ pytest.param(+ "frontend/src/scenes/foo.spec.tsx:12:5 › my flow shows an error",+ "frontend/src/scenes/foo.spec.tsx:12:5 › my flow shows an error",+ id="playwright-spec-line",+ ),+ pytest.param(+ "[chromium] › login flow shows the error banner",+ "login flow shows the error banner",+ id="playwright-project-line",+ ),+ pytest.param(+ "raised QUERY_WITH_SAME_ID_IS_ALREADY_RUNNING during the run",+ "QUERY_WITH_SAME_ID_IS_ALREADY_RUNNING",+ id="screaming-snake-error-code",+ ),+ ],+)+def test_extract_failure_queries_matches_each_pattern(log: str, expected_query: str) -> None:+ assert expected_query in extract_failure_queries(log)+++def test_extract_failure_queries_returns_empty_when_no_signature() -> None:+ assert extract_failure_queries("everything is fine, nothing to see here\n") == ()+++def test_extract_failure_queries_dedupes_repeated_signatures() -> None:+ log = "FAILED a/b.py::test_x\nFAILED a/b.py::test_x\n"+ queries = extract_failure_queries(log)++ assert queries.count("a/b.py::test_x") == 1+++def test_extract_failure_queries_caps_total_count() -> None:+ log = "\n".join(f"FAILED a.py::test_n{i}" for i in range(MAX_QUERY_COUNT + 5))+ queries = extract_failure_queries(log)++ assert len(queries) == MAX_QUERY_COUNT+++def test_extract_failure_queries_truncates_long_query() -> None:+ log = "frontend/src/x.spec.tsx:1:1 › " + "a" * 400+ [query] = [q for q in extract_failure_queries(log) if q.startswith("frontend/src/x.spec.tsx")]++ assert len(query) == 220diff --git a/.github/workflows/ci-flake-overseer.yml b/.github/workflows/ci-flake-overseer.ymlnew file mode 100644index 000000000000..7cc62d8f8a20--- /dev/null+++ b/.github/workflows/ci-flake-overseer.yml@@ -0,0 +1,93 @@+name: CI Flake Overseer++on:+ workflow_run:+ workflows:+ - 'Backend CI'+ - 'Dagster CI'+ - 'E2E CI Playwright'+ types: [completed]+ workflow_dispatch:+ inputs:+ run_id:+ description: 'GitHub Actions run ID to inspect'+ required: true+ type: string+ dry_run:+ description: 'Print intended reruns without calling the rerun API'+ required: true+ type: boolean+ default: true++permissions:+ actions: write+ contents: read++env:+ # Master on/off switch. Defaults to off (dry-run only): set the repo/org variable+ # CI_FLAKE_OVERSEER_ENABLED=true to let the overseer actually rerun jobs.+ CI_FLAKE_OVERSEER_ENABLED: ${{ vars.CI_FLAKE_OVERSEER_ENABLED || 'false' }}+ CI_FLAKE_OVERSEER_MAX_RERUNS: ${{ vars.CI_FLAKE_OVERSEER_MAX_RERUNS || '1' }}+ CI_FLAKE_OVERSEER_CONFIDENCE_THRESHOLD: ${{ vars.CI_FLAKE_OVERSEER_CONFIDENCE_THRESHOLD || '80' }}+ CI_FLAKE_OVERSEER_HOGLI_COMMAND: mendral insight+ MENDRAL_VERSION: v0.1.1++jobs:+ oversee:+ name: Classify failed jobs+ # Spin up a runner only for actionable runs: failures/timeouts to classify, or any re-run+ # attempt (run_attempt > 1, including successes) so we can record rerun outcomes. Manual dispatch always runs.+ if: >-+ github.event_name == 'workflow_dispatch' ||+ github.event.workflow_run.conclusion == 'failure' ||+ github.event.workflow_run.conclusion == 'timed_out' ||+ github.event.workflow_run.run_attempt > 1+ runs-on: ubuntu-latest+ timeout-minutes: 10+ env:+ GH_TOKEN: ${{ github.token }}+ GITHUB_TOKEN: ${{ github.token }}+ MENDRAL_TOKEN: ${{ secrets.MENDRAL_TOKEN }}+ # Emits one ci_flake_overseer_decision event per classified job to the DevEx project.+ POSTHOG_DEVEX_PROJECT_API_TOKEN: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}+ # Coerce the dispatch boolean to a string ('true'/'false') first, otherwise a literal+ # `false` collapses the `&&` and the explicit dispatch choice is silently dropped.+ CI_FLAKE_OVERSEER_DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && (inputs.dry_run && 'true' || 'false') || vars.CI_FLAKE_OVERSEER_DRY_RUN || 'false' }}+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ id: checkout+ continue-on-error: true+ with:+ clean: false++ - name: Install Mendral CLI+ if: env.MENDRAL_TOKEN != ''+ continue-on-error: true+ env:+ ASSET: mendral-linux-amd64.tar.gz+ run: |+ set -euo pipefail+ base_url="https://github.com/mendral-ai/mendral-cli/releases/download/${MENDRAL_VERSION}"+ curl -fsSL "$base_url/checksums.txt" -o checksums.txt+ curl -fsSL "$base_url/$ASSET" -o "$ASSET"+ grep " $ASSET$" checksums.txt | sha256sum --check -+ tar -xzf "$ASSET"+ sudo mv mendral-*/mendral /usr/local/bin/mendral+ mendral auth status++ - name: Classify and rerun known flakes+ if: steps.checkout.outcome == 'success'+ env:+ EVENT_NAME: ${{ github.event_name }}+ INPUT_RUN_ID: ${{ inputs.run_id }}+ run: |+ set -euo pipefail+ args=()+ if [[ "$EVENT_NAME" == "workflow_dispatch" ]]; then+ args+=(--run-id "$INPUT_RUN_ID")+ fi+ python .github/scripts/ci_flake_overseer.py "${args[@]}"++ - name: Report skipped overseer+ if: steps.checkout.outcome != 'success'+ run: echo "::notice title=CI flake overseer skipped::Could not checkout the overseer script; leaving the source CI run unchanged."