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.

refactor(ci): flake overseer observe-only (drop mendral) (#64351)

Raúl Negrón-Otero0b3fe26feaa4
diff --git a/.github/scripts/ci_flake_overseer.py b/.github/scripts/ci_flake_overseer.py
index e94f801e6dd1..a858a56a2000 100644
--- a/.github/scripts/ci_flake_overseer.py
+++ b/.github/scripts/ci_flake_overseer.py
@@ -7,25 +7,19 @@ 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
+from typing import Literal, cast
JsonObject = dict[str, object]
-DecisionAction = Literal["rerun", "skip deterministic", "skip unknown", "skip cap reached"]
+# Observe-only: we classify failed CI jobs and record what reruns do, but never rerun anything.
+DecisionAction = Literal["observe", "skip deterministic", "skip non-test"]
-# 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"
@@ -35,6 +29,7 @@ def compile_patterns(*patterns: str) -> tuple[re.Pattern[str], ...]:
return tuple(re.compile(pattern, re.IGNORECASE) for pattern in patterns)
+# Jobs/steps whose failures a rerun can't fix — excluded from the flake measurement.
DETERMINISTIC_JOB_PATTERNS = compile_patterns(
r"\brepo checks?\b",
r"\bopenapi\b",
@@ -63,21 +58,6 @@ DETERMINISTIC_STEP_PATTERNS = compile_patterns(
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",
@@ -93,28 +73,11 @@ TEST_JOB_PATTERNS = compile_patterns(
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
@@ -145,25 +108,11 @@ class WorkflowRun:
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:
@@ -192,16 +141,6 @@ 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)
@@ -219,91 +158,6 @@ def gh_json(repo: str, path: str) -> JsonObject:
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,
@@ -357,41 +211,7 @@ def fetch_jobs(repo: str, run_id: int, run_attempt: int) -> tuple[Job, ...]:
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:
+def deterministic_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}`"
@@ -402,210 +222,44 @@ def deterministic_metadata_reason(job: Job) -> str | None:
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.
+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):
- 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)
+ 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)
- 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 classify_failed_jobs(repo: str, run_id: int, run_attempt: int) -> tuple[Decision, ...]:
+ return tuple(
+ classify_job(job) for job in fetch_jobs(repo, run_id, run_attempt) if job.conclusion in {"failure", "timed_out"}
+ )
-def base_event_properties(repo: str, workflow_run: WorkflowRun, dry_run: bool, enabled: bool) -> JsonObject:
+def base_event_properties(repo: str, workflow_run: WorkflowRun) -> 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]:
+def build_decision_events(repo: str, workflow_run: WorkflowRun, decisions: tuple[Decision, ...]) -> list[JsonObject]:
events: list[JsonObject] = []
for decision in decisions:
job = decision.job
- properties = base_event_properties(repo, workflow_run, dry_run, enabled)
+ properties = base_event_properties(repo, workflow_run)
properties.update(
{
"action": decision.action,
@@ -614,10 +268,8 @@ def build_decision_events(
"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
@@ -630,31 +282,26 @@ def rerun_outcome_label(conclusion: str | None) -> str:
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.
+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
- eligible = rerun_eligible_decisions(
- repo, workflow_run.id, prior_attempt, insights, workflow_run.name, max_reruns_per_job
- )
- if not eligible:
+ observed = {
+ decision.job.name
+ for decision in classify_failed_jobs(repo, workflow_run.id, prior_attempt)
+ if decision.action == "observe"
+ }
+ if not observed:
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():
+ for job_name in sorted(observed):
conclusion = current_conclusions.get(job_name)
- properties = base_event_properties(repo, workflow_run, dry_run, enabled)
+ properties = base_event_properties(repo, workflow_run)
properties.update(
{
"outcome": rerun_outcome_label(conclusion),
@@ -664,7 +311,6 @@ def report_rerun_outcomes(
"attempt": workflow_run.run_attempt,
}
)
- properties.update(match_properties(decision.match))
events.append({"event": OUTCOME_EVENT, "distinct_id": repo, "properties": properties})
return events
@@ -687,17 +333,6 @@ def capture_events(api_key: str, host: str, events: list[JsonObject], timeout_se
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")
@@ -711,54 +346,36 @@ def markdown_link(label: str, url: str) -> str:
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:
+def format_annotation(decision: Decision) -> str:
+ detail = f"{decision.job.name}: {decision.reason}"
+ return f"::notice title=CI flake overseer: {decision.action}::{escape_annotation(detail)}"
+
+
+def write_summary(path: Path | None, workflow_run: WorkflowRun, decisions: tuple[Decision, ...]) -> None:
if path is None:
return
lines = [
- "### CI flake overseer",
+ "### CI flake overseer (observe-only)",
"",
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 |",
- "| --- | --- | --- | --- |",
+ "| Job | Decision | Reason |",
+ "| --- | --- | --- |",
]
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)} |"
+ f"| {markdown_link(decision.job.name, decision.job.html_url)} | "
+ f"`{decision.action}` | {escape_table(decision.reason)} |"
)
if not decisions:
- lines.append("| No failed jobs | `skip unknown` | workflow has no failed jobs to inspect | |")
+ lines.append("| No failed jobs | `skip non-test` | 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
@@ -777,32 +394,16 @@ def resolve_workflow_run(args: argparse.Namespace) -> WorkflowRun:
def parse_args(argv: list[str]) -> argparse.Namespace:
- parser = argparse.ArgumentParser(description="Conservatively rerun CI jobs that match known flaky signatures.")
+ parser = argparse.ArgumentParser(description="Observe failed CI test jobs and record what reruns do.")
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.
+ # Reuses the DevEx project token already wired into other CI workflows; telemetry no-ops when 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)
@@ -821,27 +422,19 @@ def main(argv: list[str]) -> int:
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"
- )
+ if not args.enabled:
+ print("::notice title=CI flake overseer disabled::Set CI_FLAKE_OVERSEER_ENABLED=true to record observations")
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)
+ # On a re-run attempt, record whether the prior attempt's test failures cleared on rerun.
+ events = report_rerun_outcomes(args.repo, workflow_run)
- # `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))
+ decisions = classify_failed_jobs(args.repo, workflow_run.id, workflow_run.run_attempt)
+ for decision in decisions:
+ print(format_annotation(decision))
+ write_summary(summary_path, workflow_run, decisions)
+ events.extend(build_decision_events(args.repo, workflow_run, decisions))
else:
print(f"::notice title=CI flake overseer skipped::Workflow conclusion is `{workflow_run.conclusion}`")
diff --git a/.github/scripts/test_ci_flake_overseer.py b/.github/scripts/test_ci_flake_overseer.py
index d9f7aac543a4..85c5a715d719 100644
--- a/.github/scripts/test_ci_flake_overseer.py
+++ b/.github/scripts/test_ci_flake_overseer.py
@@ -7,37 +7,20 @@ 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,
*,
@@ -55,171 +38,66 @@ def make_job(
)
-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,
+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",
)
- assert decision.action == "rerun"
- assert decision.match == known_flake()
- assert "test_acheck_query_found" in insights.queries
-
@pytest.mark.parametrize(
- ("job", "log", "insights", "expected_action", "expected_reason_fragment"),
+ ("job", "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",
+ "skip non-test",
"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",
+ make_job("Django tests - Temporal (1/1)", failed_step="Run Temporal tests"),
+ "observe",
+ "test job failure",
+ id="observed-test-job",
),
],
)
-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)
+def test_classify_job(job: Job, expected_action: str, expected_reason_fragment: str) -> None:
+ decision = classify_job(job)
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"
-
-
@pytest.mark.parametrize(
("job_name", "failed_step", "expected"),
[
@@ -235,207 +113,22 @@ def test_is_test_job_failure(job_name: str, failed_step: str, expected: bool) ->
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)")),
+ classify_job(make_job("Django tests - Temporal (1/1)")),
+ classify_job(make_job("Build and deploy", failed_step="Compile assets")),
)
- events = build_decision_events(
- "PostHog/posthog", make_workflow_run(), decisions, dry_run=True, enabled=False, reran_job_ids=set()
- )
+ events = build_decision_events("PostHog/posthog", make_workflow_run(), decisions)
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["action"] == "observe"
assert first["workflow_name"] == "Backend CI"
- assert first["dry_run"] is True
- assert first["reran"] is False
- assert first["insight_id"] == "01KNOWNFLAKE"
+ assert first["job_name"] == "Django tests - Temporal (1/1)"
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}
+ assert events[1]["properties"]["action"] == "skip non-test"
@pytest.mark.parametrize(
@@ -453,16 +146,7 @@ def test_rerun_outcome_label(conclusion: str | None, expected: str) -> None:
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 == []
+ assert report_rerun_outcomes("PostHog/posthog", make_workflow_run(run_attempt=1)) == []
@pytest.mark.parametrize(
@@ -473,7 +157,7 @@ def test_report_rerun_outcomes_empty_on_first_attempt() -> None:
pytest.param("timed_out", "still_failing", id="rerun-timed-out"),
],
)
-def test_report_rerun_outcomes_attributes_prior_rerun(
+def test_report_rerun_outcomes_attributes_prior_test_failure(
monkeypatch: pytest.MonkeyPatch, current_conclusion: str, expected_outcome: str
) -> None:
job_name = "Django tests - Temporal (1/1)"
@@ -484,20 +168,8 @@ def test_report_rerun_outcomes_attributes_prior_rerun(
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,
- )
+ events = report_rerun_outcomes("PostHog/posthog", make_workflow_run(run_attempt=2))
assert len(events) == 1
assert events[0]["event"] == OUTCOME_EVENT
@@ -506,87 +178,57 @@ def test_report_rerun_outcomes_attributes_prior_rerun(
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 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, ...]:
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 == []
+ assert report_rerun_outcomes("PostHog/posthog", make_workflow_run(run_attempt=2)) == []
- ("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 _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_extract_failure_queries_returns_empty_when_no_signature() -> None:
- assert extract_failure_queries("everything is fine, nothing to see here\n") == ()
+def test_capture_events_posts_batch(monkeypatch: pytest.MonkeyPatch) -> None:
+ captured: dict[str, object] = {}
-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)
+ class FakeResponse:
+ def __enter__(self) -> FakeResponse:
+ return self
- assert queries.count("a/b.py::test_x") == 1
+ 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()
-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)
+ monkeypatch.setattr(ci_flake_overseer.urllib.request, "urlopen", fake_urlopen)
+ events = [{"event": DECISION_EVENT, "distinct_id": "PostHog/posthog", "properties": {}}]
- assert len(queries) == MAX_QUERY_COUNT
+ 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}
-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) == 220
+def test_decision_is_minimal_dataclass() -> None:
+ decision = Decision(action="observe", reason="x", job=make_job("Django tests - Temporal (1/1)"))
+ assert decision.action == "observe"
diff --git a/.github/workflows/ci-flake-overseer.yml b/.github/workflows/ci-flake-overseer.yml
index 7cc62d8f8a20..39baf0b02c57 100644
--- a/.github/workflows/ci-flake-overseer.yml
+++ b/.github/workflows/ci-flake-overseer.yml
@@ -13,24 +13,16 @@ on:
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
+# Observe-only: reads job state and emits telemetry, never reruns — so read-only actions scope.
permissions:
- actions: write
+ actions: read
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.
+ # Master on/off switch. Defaults to off: set the repo/org variable CI_FLAKE_OVERSEER_ENABLED=true
+ # to record observations to the DevEx project.
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:
@@ -47,12 +39,8 @@ jobs:
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.
+ # Emits ci_flake_overseer_decision / ci_flake_overseer_rerun_outcome events 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
@@ -60,22 +48,7 @@ jobs:
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
+ - name: Classify failed jobs and record rerun outcomes
if: steps.checkout.outcome == 'success'
env:
EVENT_NAME: ${{ github.event_name }}