: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): trace every master workflow run into PostHog (#84547)
Frank Hamand48dc9ff8be7d
diff --git a/.github/scripts/report_workflow_run_traces.py b/.github/scripts/report_workflow_run_traces.pynew file mode 100644index 000000000000..08ee9cdefeea--- /dev/null+++ b/.github/scripts/report_workflow_run_traces.py@@ -0,0 +1,810 @@+#!/usr/bin/env -S uv run --script+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "opentelemetry-api~=1.27",+# "opentelemetry-sdk~=1.27",+# "opentelemetry-exporter-otlp-proto-http~=1.27",+# ]+# ///+"""Emit OTLP traces for completed master-push workflow runs.++Scans the Actions API for master pushes that finished since the last successful+run of this reporter and emits one trace per (run_id, run_attempt), shaped:++ <workflow> (root, one trace per run attempt)+ ├── <job>+ │ ├── queued (created_at -> started_at)+ │ └── <step>+ └── ...++Covers every workflow, including ones with no telemetry of their own (container+builds, image pushes, deploys). Complements report_test_timings.py, which emits+per-test traces from JUnit XML under its own trace IDs — these are separate+traces, not a parent for those.++Jobs of a reusable workflow invoked with `uses:` surface in the *caller* run as+`caller-job / callee-job`, so they land as ordinary children of the caller's+root span; `ci.job.caller` / `ci.job.callee` recover the two levels.++The runs list only reports each run's latest attempt, so earlier attempts of a+re-run are not traced. The trace ID folds in run_attempt, so the attempts that+are traced never collide.++Exit status is the watermark's only feedback channel. A tick that traced everything+it found exits 0. A tick that lost anything exits non-zero, so GitHub records the+run as failed and the next tick re-covers the window: an errored scan, a run whose+jobs would not load, or a batch the endpoint rejected. Re-emitting is free, because+span IDs are deterministic and an overlapping window is idempotent. Nothing gates on+this workflow, so a red tick costs a notification rather than a blocked merge.+"""++from __future__ import annotations++import os+import re+import sys+import json+import time+import hashlib+import logging+import argparse+import urllib.error+import urllib.parse+import urllib.request+from collections.abc import Iterator, Mapping, Sequence+from dataclasses import dataclass+from datetime import UTC, datetime, timedelta+from typing import Any++from opentelemetry import trace+from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter+from opentelemetry.sdk.resources import Resource+from opentelemetry.sdk.trace import ReadableSpan, TracerProvider+from opentelemetry.sdk.trace.export import BatchSpanProcessor, SpanExporter, SpanExportResult+from opentelemetry.sdk.trace.id_generator import IdGenerator+from opentelemetry.trace import Status, StatusCode++logger = logging.getLogger("report_workflow_run_traces")++DEFAULT_OTLP_ENDPOINT = "https://us.i.posthog.com/i/v1/traces"+DEFAULT_REPO = "PostHog/posthog"+SERVICE_NAME = "ci-workflows"+INSTRUMENTATION_NAME = "posthog-ci-workflow-runs"+INSTRUMENTATION_VERSION = "0.1.0"++# Workflow file whose own run history is the watermark.+SELF_WORKFLOW_FILE = "ci-master-run-traces.yml"+DEFAULT_LOOKBACK_HOURS = 6.0+DEFAULT_MAX_RUNS = 200++API_ROOT = "https://api.github.com"+PER_PAGE = 100+MAX_PAGES = 20+API_ATTEMPTS = 3+API_BACKOFF_SECONDS = 2.0++# A single Backend CI run is ~3.6k spans and a cron tick throttled to hourly batches+# several runs, so the SDK default queue (2048) would silently drop the tail.+SPAN_QUEUE_SIZE = 65536+# ~230 KB serialized at this size — well clear of capture-logs' 2 MiB body limit.+SPAN_BATCH_SIZE = 512++EXIT_OK = 0+# Anything the tick meant to trace and lost. Holds the watermark at the last clean tick.+EXIT_INCOMPLETE = 1++RUN_ERROR_CONCLUSIONS = frozenset({"failure", "timed_out", "startup_failure"})+JOB_ERROR_CONCLUSIONS = frozenset({"failure", "timed_out"})+STEP_ERROR_CONCLUSIONS = frozenset({"failure"})++# Each token receives an identical copy of the spans (trace and span IDs are+# deterministic) — transitional dual emission while CI telemetry moves projects.+TOKEN_ENV_VARS = ("POSTHOG_DEVEX_PROJECT_API_TOKEN", "POSTHOG_CI_TRACES_EXTRA_TOKEN")++# One trailing parenthesized group, e.g. `Django tests – Core (…) (6/19)`.+MATRIX_SUFFIX_RE = re.compile(r"\s*\([^()]*\)\s*$")+REUSABLE_SEPARATOR = " / "+++@dataclass(frozen=True)+class Step:+ number: int+ name: str+ status: str+ conclusion: str+ start: datetime+ end: datetime++ @property+ def duration_seconds(self) -> float:+ return (self.end - self.start).total_seconds()+++@dataclass(frozen=True)+class Job:+ id: int+ name: str+ status: str+ conclusion: str+ url: str+ runner_name: str+ runner_group_name: str+ labels: tuple[str, ...]+ created: datetime+ start: datetime+ end: datetime+ steps: tuple[Step, ...]++ @property+ def duration_seconds(self) -> float:+ return (self.end - self.start).total_seconds()++ @property+ def queued_seconds(self) -> float:+ return (self.start - self.created).total_seconds()+++@dataclass(frozen=True)+class WorkflowRun:+ id: int+ attempt: int+ name: str+ path: str+ workflow_id: int+ run_number: int+ event: str+ status: str+ conclusion: str+ display_title: str+ head_sha: str+ head_branch: str+ actor: str+ triggering_actor: str+ repository: str+ html_url: str+ created: datetime+ start: datetime+ end: datetime+ jobs: tuple[Job, ...] = ()+ dropped_jobs: int = 0++ @property+ def duration_seconds(self) -> float:+ return (self.end - self.start).total_seconds()++ @property+ def queued_seconds(self) -> float:+ return (self.start - self.created).total_seconds()++ @property+ def step_count(self) -> int:+ return sum(len(job.steps) for job in self.jobs)+++@dataclass(frozen=True)+class Collection:+ """What this tick resolved, and whether it resolved everything it found."""++ runs: tuple[WorkflowRun, ...] = ()+ complete: bool = True+++# ---------- GitHub API ----------+++class ApiError(Exception):+ def __init__(self, message: str, status: int = 0) -> None:+ super().__init__(message)+ self.status = status+++def _api_get(path: str, token: str, *, opener: Any = None) -> Any:+ """GET a GitHub API path, retrying transient failures only.++ 5xx and network errors are worth another attempt; 403 and 404 are not — with an+ already-empty rate-limit bucket a retry just spends more of it.+ """+ url = f"{API_ROOT}/{path.lstrip('/')}"+ request = urllib.request.Request(+ url,+ headers={+ "Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28",+ "Authorization": f"Bearer {token}",+ "User-Agent": INSTRUMENTATION_NAME,+ },+ )+ do_open = opener or urllib.request.urlopen+ for attempt in range(1, API_ATTEMPTS + 1):+ try:+ with do_open(request, timeout=30) as response:+ return json.loads(response.read().decode("utf-8"))+ except urllib.error.HTTPError as error:+ if error.code < 500 or attempt == API_ATTEMPTS:+ raise ApiError(f"GET {url} failed with {error.code}", error.code) from error+ except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as error:+ if attempt == API_ATTEMPTS:+ raise ApiError(f"GET {url} failed: {error}") from error+ time.sleep(API_BACKOFF_SECONDS * attempt)+ raise ApiError(f"GET {url} exhausted {API_ATTEMPTS} attempts")+++def _paginate(path: str, token: str, key: str, *, opener: Any = None) -> list[dict]:+ """Collect `key` across pages, stopping on a short page or the page cap."""+ joiner = "&" if "?" in path else "?"+ items: list[dict] = []+ for page in range(1, MAX_PAGES + 1):+ payload = _api_get(f"{path}{joiner}per_page={PER_PAGE}&page={page}", token, opener=opener)+ batch = payload.get(key) or []+ items.extend(batch)+ if len(batch) < PER_PAGE:+ return items+ logger.warning("hit the %d-page cap on %s; collected %d %s", MAX_PAGES, path, len(items), key)+ return items+++def watermark(repo: str, token: str, *, lookback_hours: float, now: datetime, opener: Any = None) -> datetime:+ """Low-water mark: when the previous successful reporter run started.++ Reading our own run history is the entire state mechanism — no cache, no+ committed file. Keying on the last *success* means a failed tick doesn't+ advance the mark, so the next one re-covers the gap.+ """+ floor = now - timedelta(hours=lookback_hours)+ try:+ payload = _api_get(+ f"repos/{repo}/actions/workflows/{SELF_WORKFLOW_FILE}/runs?status=success&per_page=2",+ token,+ opener=opener,+ )+ except ApiError as error:+ # 404 just means this workflow has never run — the expected first tick, and+ # every local invocation. Anything else is worth a traceback.+ if error.status == 404:+ logger.info("no run history for %s yet; scanning from %s", SELF_WORKFLOW_FILE, floor.isoformat())+ else:+ logger.exception("could not read this reporter's own run history; falling back to %s", floor.isoformat())+ return floor+ runs = payload.get("workflow_runs") or []+ # Entry one is this run when it is already marked successful; entry two is the+ # previous success. A tick still in progress isn't listed, so either can be it.+ for run in runs:+ started = parse_iso_utc(run.get("run_started_at") or run.get("created_at") or "")+ if started is not None and started < now:+ return max(started, floor)+ logger.info("no previous successful run; falling back to %s", floor.isoformat())+ return floor+++def scan_runs(repo: str, token: str, since: datetime, *, opener: Any = None) -> list[dict]:+ """Completed master-push runs whose completion lands at or after `since`.++ The API can only filter on `created`, so widen the window by a day and narrow+ on `updated_at` — which for a completed run is when it finished.+ """+ created_floor = (since - timedelta(days=1)).date().isoformat()+ query = urllib.parse.urlencode(+ {+ "branch": "master",+ "event": "push",+ "status": "completed",+ "exclude_pull_requests": "true",+ "created": f">={created_floor}",+ }+ )+ raw = _paginate(f"repos/{repo}/actions/runs?{query}", token, "workflow_runs", opener=opener)+ fresh = []+ for run in raw:+ updated = parse_iso_utc(run.get("updated_at") or "")+ if updated is not None and updated >= since:+ fresh.append(run)+ return fresh+++def fetch_jobs(repo: str, run_id: int, attempt: int, token: str, *, opener: Any = None) -> list[dict]:+ return _paginate(+ f"repos/{repo}/actions/runs/{run_id}/attempts/{attempt}/jobs",+ token,+ "jobs",+ opener=opener,+ )+++def fetch_run(repo: str, run_id: int, token: str, *, attempt: int = 0, opener: Any = None) -> dict:+ """The run's metadata, for `attempt` when given and for the latest attempt otherwise.++ The attempt-agnostic path always describes the latest attempt, so pairing it with+ an older attempt's jobs puts `run_started_at` after every job end and collapses the+ root span to zero length.+ """+ path = f"repos/{repo}/actions/runs/{run_id}"+ if attempt:+ path = f"{path}/attempts/{attempt}"+ return _api_get(path, token, opener=opener)+++# ---------- Parsing ----------+++def parse_iso_utc(value: str) -> datetime | None:+ """Parse an ISO 8601 timestamp; treat a naive one as UTC."""+ if not value:+ return None+ try:+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ return dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+++def clamp(start: datetime, end: datetime) -> tuple[datetime, datetime]:+ """Guarantee end >= start. Skipped jobs really do report completion a second early."""+ return start, max(start, end)+++def split_reusable_name(name: str) -> tuple[str, str]:+ """`caller-job / callee-job` -> (caller, callee); ('', '') when not a reusable job.++ Splits on the first separator only: the callee half can contain another one.+ """+ caller, separator, callee = name.partition(REUSABLE_SEPARATOR)+ if not separator:+ return "", ""+ return caller, callee+++def job_group_name(name: str) -> str:+ """Job name with one trailing matrix group removed, so matrix legs aggregate.++ Best-effort: a job whose real name simply ends in parentheses loses them too.+ """+ stripped = MATRIX_SUFFIX_RE.sub("", name)+ return stripped or name+++def parse_step(raw: Mapping[str, Any], window: tuple[datetime, datetime]) -> Step | None:+ start = parse_iso_utc(raw.get("started_at") or "")+ end = parse_iso_utc(raw.get("completed_at") or "")+ if start is None or end is None:+ return None+ job_start, job_end = window+ # Step timestamps are second-granularity, so they can overhang the job window.+ start = min(max(start, job_start), job_end)+ end = min(max(end, job_start), job_end)+ start, end = clamp(start, end)+ return Step(+ number=int(raw.get("number") or 0),+ name=str(raw.get("name") or ""),+ status=str(raw.get("status") or ""),+ conclusion=str(raw.get("conclusion") or ""),+ start=start,+ end=end,+ )+++def parse_job(raw: Mapping[str, Any]) -> Job | None:+ """Build a Job, or None when it never ran to completion (queued on a cancelled run)."""+ created = parse_iso_utc(raw.get("created_at") or "")+ start = parse_iso_utc(raw.get("started_at") or "")+ end = parse_iso_utc(raw.get("completed_at") or "")+ if end is None:+ return None+ if start is None:+ start = created or end+ if created is None:+ created = start+ created = min(created, start)+ start, end = clamp(start, end)+ steps = [step for step in (parse_step(s, (start, end)) for s in raw.get("steps") or []) if step is not None]+ steps.sort(key=lambda step: step.number)+ return Job(+ id=int(raw.get("id") or 0),+ name=str(raw.get("name") or ""),+ status=str(raw.get("status") or ""),+ conclusion=str(raw.get("conclusion") or ""),+ url=str(raw.get("html_url") or ""),+ runner_name=str(raw.get("runner_name") or ""),+ runner_group_name=str(raw.get("runner_group_name") or ""),+ labels=tuple(str(label) for label in raw.get("labels") or []),+ created=created,+ start=start,+ end=end,+ steps=tuple(steps),+ )+++def parse_run(raw: Mapping[str, Any], raw_jobs: list[dict]) -> WorkflowRun | None:+ created = parse_iso_utc(raw.get("created_at") or "")+ start = parse_iso_utc(raw.get("run_started_at") or "") or created+ if start is None:+ logger.warning("run %s has no usable start timestamp; skipping", raw.get("id"))+ return None+ if created is None:+ created = start+ created = min(created, start)++ jobs: list[Job] = []+ dropped = 0+ for raw_job in raw_jobs:+ job = parse_job(raw_job)+ if job is None:+ dropped += 1+ continue+ jobs.append(job)+ jobs.sort(key=lambda job: (job.start, job.id))++ end = max((job.end for job in jobs), default=None) or parse_iso_utc(raw.get("updated_at") or "") or start+ start, end = clamp(start, end)+ return WorkflowRun(+ id=int(raw.get("id") or 0),+ attempt=int(raw.get("run_attempt") or 1),+ name=str(raw.get("name") or ""),+ path=str(raw.get("path") or ""),+ workflow_id=int(raw.get("workflow_id") or 0),+ run_number=int(raw.get("run_number") or 0),+ event=str(raw.get("event") or ""),+ status=str(raw.get("status") or ""),+ conclusion=str(raw.get("conclusion") or ""),+ display_title=str(raw.get("display_title") or ""),+ head_sha=str(raw.get("head_sha") or ""),+ head_branch=str(raw.get("head_branch") or ""),+ actor=str((raw.get("actor") or {}).get("login") or ""),+ triggering_actor=str((raw.get("triggering_actor") or {}).get("login") or ""),+ repository=str((raw.get("repository") or {}).get("full_name") or ""),+ html_url=str(raw.get("html_url") or ""),+ created=created,+ start=start,+ end=end,+ jobs=tuple(jobs),+ dropped_jobs=dropped,+ )+++# ---------- OTLP export ----------+++def deterministic_trace_id(run_id: int, run_attempt: int) -> int:+ """One trace per run attempt. Distinct from report_test_timings.py's per-shard keys."""+ digest = hashlib.sha256(f"{run_id}:{run_attempt}:workflow-run".encode()).digest()+ return int.from_bytes(digest[:16], "big") # OTLP trace IDs are 128-bit.+++def deterministic_span_id(*parts: object) -> int:+ """Span IDs derived from run/job/step identity, so a repeat emit is byte-identical."""+ digest = hashlib.sha256(":".join(str(part) for part in parts).encode()).digest()+ span_id = int.from_bytes(digest[:8], "big")+ return span_id or 1 # zero is reserved as the invalid span ID+++class _FixedIdGenerator(IdGenerator):+ """Hands out pre-computed IDs so every span is reproducible across emits.++ `trace_id` and `next_span_id` are set immediately before each start_span call;+ the generator has no state of its own to get out of sync.+ """++ def __init__(self) -> None:+ self.trace_id = 0+ self.next_span_id = 1++ def generate_trace_id(self) -> int:+ return self.trace_id++ def generate_span_id(self) -> int:+ return self.next_span_id+++def _to_ns(dt: datetime) -> int:+ return int(dt.timestamp() * 1_000_000_000)+++def run_resource_attributes(run: WorkflowRun) -> dict[str, str | int]:+ """Resource attributes for the *traced* run.++ Everything comes off the run payload — never this reporter's own GITHUB_* env,+ which describes the cron tick rather than the run being traced.+ """+ attrs: dict[str, str | int] = {+ "service.name": SERVICE_NAME,+ "ci.workflow": run.name,+ "ci.workflow_path": run.path,+ "ci.workflow_id": run.workflow_id,+ "ci.run_id": run.id,+ "ci.run_number": run.run_number,+ "ci.run_attempt": run.attempt,+ "ci.sha": run.head_sha,+ "ci.ref": f"refs/heads/{run.head_branch}" if run.head_branch else "",+ "ci.ref_name": run.head_branch,+ "ci.branch": run.head_branch,+ "ci.actor": run.actor,+ "ci.triggering_actor": run.triggering_actor,+ "ci.repository": run.repository,+ "ci.event_name": run.event,+ "ci.run_url": run.html_url,+ }+ return {k: v for k, v in attrs.items() if v != "" and v != 0}+++class ExportError(Exception):+ pass+++class _FailureRecordingExporter(SpanExporter):+ """Surfaces a rejected batch, which the SDK only logs.++ Without this an hour of 403s from the ingest endpoint reads as a clean tick and+ the watermark walks past every trace it dropped.+ """++ def __init__(self, inner: SpanExporter) -> None:+ self.inner = inner+ self.failed = False++ def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:+ # A transport failure (read timeout, refused connection, repeated connection+ # error) raises out of the inner exporter rather than returning FAILURE, and+ # the SDK's batch processor swallows that on its worker thread. Record it before+ # re-raising so the watermark check still sees the loss and the SDK still logs it.+ try:+ result = self.inner.export(spans)+ except Exception:+ self.failed = True+ raise+ if result is not SpanExportResult.SUCCESS:+ self.failed = True+ return result++ def force_flush(self, timeout_millis: int = 30_000) -> bool:+ return self.inner.force_flush(timeout_millis)++ def shutdown(self) -> None:+ self.inner.shutdown()+++def emit_trace(run: WorkflowRun, endpoint: str, token: str, exporter: Any = None) -> int:+ """Emit the run's whole span tree over OTLP HTTP. Returns the span count."""+ id_generator = _FixedIdGenerator()+ provider = TracerProvider(+ resource=Resource.create(run_resource_attributes(run)),+ id_generator=id_generator,+ )+ if exporter is None:+ exporter = OTLPSpanExporter(endpoint=endpoint, headers={"Authorization": f"Bearer {token}"})+ recorder = _FailureRecordingExporter(exporter)+ provider.add_span_processor(+ BatchSpanProcessor(recorder, max_queue_size=SPAN_QUEUE_SIZE, max_export_batch_size=SPAN_BATCH_SIZE)+ )+ tracer = provider.get_tracer(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION)+ id_generator.trace_id = deterministic_trace_id(run.id, run.attempt)++ try:+ span_count = _emit_run_span(tracer, id_generator, run)+ finally:+ # Drains the queue, so a rejected batch is recorded by the time this returns.+ provider.shutdown()+ if recorder.failed:+ raise ExportError(f"OTLP endpoint rejected spans for run {run.id} attempt {run.attempt}")+ return span_count+++def _emit_run_span(tracer: trace.Tracer, ids: _FixedIdGenerator, run: WorkflowRun) -> int:+ ids.next_span_id = deterministic_span_id(run.id, run.attempt, "run")+ root = tracer.start_span(run.name or run.path, start_time=_to_ns(run.start))+ failed = sum(1 for job in run.jobs if job.conclusion in JOB_ERROR_CONCLUSIONS)+ skipped = sum(1 for job in run.jobs if job.conclusion == "skipped")+ for key, value in (+ ("ci.workflow.status", run.status),+ ("ci.workflow.conclusion", run.conclusion),+ ("ci.workflow.display_title", run.display_title),+ ("ci.workflow.duration_seconds", run.duration_seconds),+ ("ci.workflow.queued_seconds", max(run.queued_seconds, 0.0)),+ ("ci.workflow.job_count", len(run.jobs)),+ ("ci.workflow.failed_job_count", failed),+ ("ci.workflow.skipped_job_count", skipped),+ ("ci.workflow.dropped_job_count", run.dropped_jobs),+ ("ci.workflow.step_count", run.step_count),+ ):+ root.set_attribute(key, value)+ # `cancelled` stays UNSET: master runs get cancelled by concurrency routinely, and+ # marking them Error would bury the runs that actually broke.+ if run.conclusion in RUN_ERROR_CONCLUSIONS:+ root.set_status(Status(StatusCode.ERROR))++ span_count = 1+ with trace.use_span(root, end_on_exit=False):+ for job in run.jobs:+ span_count += _emit_job_span(tracer, ids, run, job)+ root.end(end_time=_to_ns(run.end))+ return span_count+++def _emit_job_span(tracer: trace.Tracer, ids: _FixedIdGenerator, run: WorkflowRun, job: Job) -> int:+ ids.next_span_id = deterministic_span_id(run.id, run.attempt, "job", job.id)+ span = tracer.start_span(job.name, start_time=_to_ns(job.start))+ for key, value in (+ ("ci.job.id", job.id),+ ("ci.job.name", job.name),+ ("ci.job.group_name", job_group_name(job.name)),+ ("ci.job.url", job.url),+ ("ci.job.status", job.status),+ ("ci.job.conclusion", job.conclusion),+ ("ci.job.duration_seconds", job.duration_seconds),+ ("ci.job.queued_seconds", max(job.queued_seconds, 0.0)),+ ("ci.job.runner_name", job.runner_name),+ ("ci.job.runner_group_name", job.runner_group_name),+ # Joined rather than a sequence, so it stays one queryable value downstream.+ ("ci.job.labels", ",".join(job.labels)),+ ("ci.job.step_count", len(job.steps)),+ ):+ if value != "":+ span.set_attribute(key, value)+ caller, callee = split_reusable_name(job.name)+ if caller:+ span.set_attribute("ci.job.caller", caller)+ span.set_attribute("ci.job.callee", callee)+ if job.conclusion in JOB_ERROR_CONCLUSIONS:+ span.set_status(Status(StatusCode.ERROR))++ span_count = 1+ with trace.use_span(span, end_on_exit=False):+ # Without its own span the wait collapses into the first step, hiding the+ # one thing a queue delay looks like in a waterfall.+ if job.queued_seconds > 0:+ ids.next_span_id = deterministic_span_id(run.id, run.attempt, "queued", job.id)+ queued = tracer.start_span("queued", start_time=_to_ns(job.created))+ queued.set_attribute("ci.job.queued_seconds", job.queued_seconds)+ queued.set_attribute("ci.job.id", job.id)+ queued.end(end_time=_to_ns(job.start))+ span_count += 1+ for step in job.steps:+ ids.next_span_id = deterministic_span_id(run.id, run.attempt, "step", job.id, step.number)+ step_span = tracer.start_span(step.name, start_time=_to_ns(step.start))+ step_span.set_attribute("ci.step.number", step.number)+ step_span.set_attribute("ci.step.name", step.name)+ step_span.set_attribute("ci.step.status", step.status)+ step_span.set_attribute("ci.step.conclusion", step.conclusion)+ step_span.set_attribute("ci.step.duration_seconds", step.duration_seconds)+ step_span.set_attribute("ci.job.id", job.id)+ step_span.set_attribute("ci.job.name", job.name)+ if step.conclusion in STEP_ERROR_CONCLUSIONS:+ step_span.set_status(Status(StatusCode.ERROR))+ step_span.end(end_time=_to_ns(step.end))+ span_count += 1+ span.end(end_time=_to_ns(job.end))+ return span_count+++def format_span_tree(run: WorkflowRun) -> Iterator[str]:+ yield (+ f"{run.name} [run {run.id} attempt {run.attempt}] "+ f"{run.conclusion or run.status} {run.duration_seconds:.0f}s "+ f"({len(run.jobs)} jobs, {run.step_count} steps, {run.dropped_jobs} dropped)"+ )+ for job in run.jobs:+ yield f" ├─ {job.name} [{job.conclusion or job.status}] {job.duration_seconds:.0f}s queued {job.queued_seconds:.0f}s"+ for step in job.steps:+ yield f" │ ├─ {step.name} [{step.conclusion or step.status}] {step.duration_seconds:.0f}s"+++# ---------- CLI ----------+++def emission_tokens(env: Mapping[str, str]) -> list[str]:+ """Distinct project API tokens to emit to, in ``TOKEN_ENV_VARS`` order."""+ tokens = (env.get(var, "") for var in TOKEN_ENV_VARS)+ return list(dict.fromkeys(token for token in tokens if token))+++def parse_args(argv: list[str]) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0] if __doc__ else "")+ parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY") or DEFAULT_REPO)+ parser.add_argument("--since", default="", help="ISO 8601 watermark override, for a manual backfill")+ parser.add_argument(+ "--run-id",+ action="append",+ type=int,+ default=[],+ help="trace exactly these runs and skip the scan (repeatable)",+ )+ parser.add_argument("--run-attempt", type=int, default=0, help="attempt for --run-id; default is the run's latest")+ parser.add_argument("--lookback-hours", type=float, default=DEFAULT_LOOKBACK_HOURS)+ parser.add_argument("--max-runs", type=int, default=DEFAULT_MAX_RUNS)+ parser.add_argument(+ "--otlp-endpoint", default=os.environ.get("POSTHOG_OTLP_TRACES_ENDPOINT") or DEFAULT_OTLP_ENDPOINT+ )+ parser.add_argument("--dry-run", action="store_true", help="print the span tree without emitting")+ return parser.parse_args(argv)+++def collect_runs(args: argparse.Namespace, token: str, now: datetime) -> Collection:+ """Resolve the target runs into fully parsed span trees."""+ if args.run_id:+ raw_runs = [fetch_run(args.repo, run_id, token, attempt=args.run_attempt) for run_id in args.run_id]+ else:+ if args.run_attempt:+ # The scan returns latest-attempt payloads only, so an attempt override there+ # would pair one attempt's jobs with another attempt's window.+ logger.warning("--run-attempt only applies with --run-id; ignoring it for the scan")+ since = parse_iso_utc(args.since) or watermark(args.repo, token, lookback_hours=args.lookback_hours, now=now)+ logger.info("scanning master pushes completed since %s", since.isoformat())+ raw_runs = scan_runs(args.repo, token, since)+ if len(raw_runs) > args.max_runs:+ # Not an incomplete tick: holding the watermark here would re-scan the same+ # oversized window forever. Freshest runs win and the backlog's tail is lost.+ logger.warning("found %d runs; capping at %d newest", len(raw_runs), args.max_runs)+ raw_runs = raw_runs[: args.max_runs]++ runs = []+ complete = True+ for raw in raw_runs:+ run_id = int(raw.get("id") or 0)+ # Both fetch paths report the attempt their payload describes, so jobs, metadata+ # and the trace ID stay on one attempt.+ attempt = int(raw.get("run_attempt") or 1)+ try:+ raw_jobs = fetch_jobs(args.repo, run_id, attempt, token)+ except ApiError:+ logger.exception("could not fetch jobs for run %s attempt %s; skipping", run_id, attempt)+ complete = False+ continue+ if not raw_jobs:+ # Startup failures and very early cancellations report zero jobs. A bare root+ # span holds no job time to attribute, and an empty list from a transient API+ # fault would look the same as a run that genuinely had none, so it is skipped.+ # This is also why `startup_failure` in RUN_ERROR_CONCLUSIONS never fires here.+ logger.info("run %s attempt %s has no jobs; nothing to trace", run_id, attempt)+ continue+ run = parse_run(raw, raw_jobs)+ if run is not None:+ runs.append(run)+ return Collection(runs=tuple(runs), complete=complete)+++def main(argv: list[str] | None = None) -> int:+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")+ args = parse_args(argv if argv is not None else sys.argv[1:])++ github_token = os.environ.get("GITHUB_TOKEN", "")+ if not github_token:+ logger.error("GITHUB_TOKEN is not set; nothing was traced")+ return EXIT_INCOMPLETE++ try:+ collection = collect_runs(args, github_token, datetime.now(UTC))+ except Exception:+ logger.exception("failed to collect workflow runs")+ return EXIT_INCOMPLETE++ if not collection.runs:+ logger.info("no completed master-push runs to trace")+ return EXIT_OK if collection.complete else EXIT_INCOMPLETE++ if args.dry_run or os.environ.get("DRY_RUN") == "1":+ for run in collection.runs:+ for line in format_span_tree(run):+ logger.info("%s", line)+ return EXIT_OK if collection.complete else EXIT_INCOMPLETE++ tokens = emission_tokens(os.environ)+ if not tokens:+ logger.error("none of %s set; nothing was emitted", ", ".join(TOKEN_ENV_VARS))+ return EXIT_INCOMPLETE++ complete = collection.complete+ for token in tokens:+ emitted = 0+ for run in collection.runs:+ # Per-run isolation: one malformed run must not cost the rest of the batch.+ try:+ emitted += emit_trace(run, args.otlp_endpoint, token)+ except Exception:+ logger.exception("failed to emit trace for run %s attempt %s", run.id, run.attempt)+ complete = False+ logger.info("emitted %d spans across %d runs to %s", emitted, len(collection.runs), args.otlp_endpoint)++ return EXIT_OK if complete else EXIT_INCOMPLETE+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.github/scripts/test_report_workflow_run_traces.py b/.github/scripts/test_report_workflow_run_traces.pynew file mode 100644index 000000000000..32b735a56251--- /dev/null+++ b/.github/scripts/test_report_workflow_run_traces.py@@ -0,0 +1,713 @@+from __future__ import annotations++import io+import sys+import json+import urllib.error+import importlib.util+from datetime import UTC, datetime, timedelta+from pathlib import Path+from typing import Any++import pytest++from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter++SCRIPT_PATH = Path(__file__).with_name("report_workflow_run_traces.py")+SPEC = importlib.util.spec_from_file_location("report_workflow_run_traces", SCRIPT_PATH)+assert SPEC is not None and SPEC.loader is not None+reporter = importlib.util.module_from_spec(SPEC)+# Register before exec so @dataclass can resolve the module via sys.modules.+sys.modules["report_workflow_run_traces"] = reporter+SPEC.loader.exec_module(reporter)++RUN_START = datetime(2026, 8, 18, 10, 0, 0, tzinfo=UTC)+++def _iso(offset_seconds: int) -> str:+ return (RUN_START + timedelta(seconds=offset_seconds)).isoformat().replace("+00:00", "Z")+++def _raw_step(*, number: int = 1, name: str = "Set up job", start: int = 0, end: int = 1, **overrides: Any) -> dict:+ return {+ "number": number,+ "name": name,+ "status": "completed",+ "conclusion": "success",+ "started_at": _iso(start),+ "completed_at": _iso(end),+ **overrides,+ }+++def _raw_job(+ *, created: int = 0, start: int = 5, end: int = 60, steps: list[dict] | None = None, **overrides: Any+) -> dict:+ return {+ "id": 1234,+ "name": "build",+ "status": "completed",+ "conclusion": "success",+ "html_url": "https://github.com/PostHog/posthog/actions/runs/1/job/1234",+ "runner_name": "GitHub Actions 1",+ "runner_group_name": "GitHub Actions",+ "labels": ["ubuntu-latest"],+ "created_at": _iso(created),+ "started_at": _iso(start),+ "completed_at": _iso(end),+ "steps": steps if steps is not None else [_raw_step(start=5, end=20)],+ **overrides,+ }+++def _raw_run(**overrides: Any) -> dict:+ return {+ "id": 999,+ "run_attempt": 1,+ "name": "Container Images CD",+ "path": ".github/workflows/container-images-cd.yml",+ "workflow_id": 42,+ "run_number": 7,+ "event": "push",+ "status": "completed",+ "conclusion": "success",+ "display_title": "fix: something",+ "head_sha": "abc123",+ "head_branch": "master",+ "actor": {"login": "trunk-io[bot]"},+ "triggering_actor": {"login": "trunk-io[bot]"},+ "repository": {"full_name": "PostHog/posthog"},+ "html_url": "https://github.com/PostHog/posthog/actions/runs/999",+ "created_at": _iso(0),+ "run_started_at": _iso(0),+ "updated_at": _iso(120),+ **overrides,+ }+++class TestTimestampClamping:+ @pytest.mark.parametrize(+ "start_offset,end_offset,expected_duration",+ [+ (5, 60, 55.0),+ (5, 5, 0.0),+ # A skipped job really does report completion a second before it started.+ (20, 19, 0.0),+ ],+ )+ def test_job_duration_never_negative(self, start_offset: int, end_offset: int, expected_duration: float) -> None:+ job = reporter.parse_job(_raw_job(created=0, start=start_offset, end=end_offset, steps=[]))+ assert job is not None+ assert job.duration_seconds == expected_duration+ assert job.end >= job.start++ def test_job_created_never_after_start(self) -> None:+ job = reporter.parse_job(_raw_job(created=30, start=5, end=60, steps=[]))+ assert job is not None+ assert job.queued_seconds >= 0++ def test_step_clamped_into_job_window(self) -> None:+ # Second-granularity step timestamps can overhang the job they belong to.+ job = reporter.parse_job(_raw_job(start=5, end=60, steps=[_raw_step(start=3, end=90)]))+ assert job is not None+ assert job.steps[0].start >= job.start+ assert job.steps[0].end <= job.end++ def test_zero_length_step_is_emitted(self) -> None:+ # 57% of real CI steps complete within the same second; dropping them would+ # gut the waterfall.+ job = reporter.parse_job(_raw_job(steps=[_raw_step(start=10, end=10)]))+ assert job is not None+ assert len(job.steps) == 1+ assert job.steps[0].duration_seconds == 0.0+++class TestJobParsing:+ def test_drops_job_without_completed_at(self) -> None:+ assert reporter.parse_job(_raw_job(completed_at=None)) is None++ def test_keeps_job_with_no_steps(self) -> None:+ # Skipped jobs come back with `steps: []`; a skipped job is signal.+ job = reporter.parse_job(_raw_job(conclusion="skipped", steps=[]))+ assert job is not None+ assert job.steps == ()++ def test_missing_started_at_falls_back_to_created(self) -> None:+ job = reporter.parse_job(_raw_job(started_at=None, steps=[]))+ assert job is not None+ assert job.end >= job.start++ def test_steps_sorted_by_number_not_input_order(self) -> None:+ # Real step numbers are non-contiguous (1,2,3,4,5,10,11) and the API order+ # is not guaranteed.+ raw = _raw_job(+ steps=[+ _raw_step(number=11, name="Complete job", start=50, end=51),+ _raw_step(number=1, name="Set up job", start=5, end=6),+ _raw_step(number=10, name="Post checkout", start=45, end=46),+ ]+ )+ job = reporter.parse_job(raw)+ assert job is not None+ assert [step.number for step in job.steps] == [1, 10, 11]++ def test_step_without_timestamps_is_dropped(self) -> None:+ job = reporter.parse_job(_raw_job(steps=[_raw_step(), _raw_step(number=2, completed_at=None)]))+ assert job is not None+ assert [step.number for step in job.steps] == [1]+++class TestJobNaming:+ @pytest.mark.parametrize(+ "name,expected",+ [+ ("build-images / build cymbal", ("build-images", "build cymbal")),+ ("compute affected images", ("", "")),+ # The callee half can carry another separator; only the first splits.+ ("outer / inner / leaf", ("outer", "inner / leaf")),+ ],+ )+ def test_split_reusable_name(self, name: str, expected: tuple[str, str]) -> None:+ assert reporter.split_reusable_name(name) == expected++ @pytest.mark.parametrize(+ "name,expected",+ [+ ("Django tests – Core (6/19)", "Django tests – Core"),+ ("Validate product.yaml owners (ubuntu-latest)", "Validate product.yaml owners"),+ ("compute affected images", "compute affected images"),+ # Strip one group only, so an inner group survives for grouping.+ ("Django tests (FOSS) (3/9)", "Django tests (FOSS)"),+ ],+ )+ def test_job_group_name_strips_one_matrix_suffix(self, name: str, expected: str) -> None:+ assert reporter.job_group_name(name) == expected++ def test_unexpanded_matrix_expression_survives(self) -> None:+ # A skipped matrix job keeps the literal expression as its name.+ job = reporter.parse_job(_raw_job(name="deploy ${{ matrix.release }}", conclusion="skipped", steps=[]))+ assert job is not None+ assert job.name == "deploy ${{ matrix.release }}"+ assert reporter.job_group_name(job.name) == "deploy ${{ matrix.release }}"+++class TestResourceAttributes:+ def test_ignores_this_reporters_own_github_env(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # The reporter runs on a cron tick, so its own GITHUB_* describes the tick and+ # not the run being traced. Leaking those in would silently mislabel every span.+ for name, value in {+ "GITHUB_RUN_ID": "SENTINEL_RUN",+ "GITHUB_RUN_ATTEMPT": "SENTINEL_ATTEMPT",+ "GITHUB_WORKFLOW": "SENTINEL_WORKFLOW",+ "GITHUB_SHA": "SENTINEL_SHA",+ "GITHUB_ACTOR": "SENTINEL_ACTOR",+ "GITHUB_RUN_NUMBER": "SENTINEL_NUMBER",+ }.items():+ monkeypatch.setenv(name, value)+ run = reporter.parse_run(_raw_run(), [_raw_job()])+ assert run is not None+ rendered = json.dumps(reporter.run_resource_attributes(run))+ assert "SENTINEL" not in rendered++ def test_carries_traced_run_identity(self) -> None:+ run = reporter.parse_run(_raw_run(), [_raw_job()])+ assert run is not None+ attrs = reporter.run_resource_attributes(run)+ assert attrs["ci.workflow"] == "Container Images CD"+ assert attrs["ci.run_id"] == 999+ assert attrs["ci.sha"] == "abc123"+ assert attrs["ci.branch"] == "master"+ assert attrs["ci.ref"] == "refs/heads/master"+ assert attrs["service.name"] == "ci-workflows"++ def test_drops_empty_values(self) -> None:+ run = reporter.parse_run(_raw_run(head_branch="", display_title=""), [_raw_job()])+ assert run is not None+ attrs = reporter.run_resource_attributes(run)+ assert "ci.branch" not in attrs+ assert "ci.ref" not in attrs+++class TestRunParsing:+ def test_end_is_last_job_completion(self) -> None:+ run = reporter.parse_run(+ _raw_run(updated_at=_iso(9999)),+ [_raw_job(id=1, start=5, end=60, steps=[]), _raw_job(id=2, start=5, end=200, steps=[])],+ )+ assert run is not None+ assert run.duration_seconds == 200.0++ def test_counts_dropped_jobs(self) -> None:+ run = reporter.parse_run(_raw_run(), [_raw_job(), _raw_job(id=2, completed_at=None)])+ assert run is not None+ assert len(run.jobs) == 1+ assert run.dropped_jobs == 1++ def test_step_count_sums_jobs(self) -> None:+ run = reporter.parse_run(+ _raw_run(),+ [+ _raw_job(id=1, steps=[_raw_step(), _raw_step(number=2)]),+ _raw_job(id=2, steps=[_raw_step()]),+ ],+ )+ assert run is not None+ assert run.step_count == 3+++class TestDeterministicIds:+ def test_trace_id_varies_with_attempt(self) -> None:+ assert reporter.deterministic_trace_id(999, 1) != reporter.deterministic_trace_id(999, 2)++ def test_trace_id_fits_128_bits(self) -> None:+ assert 0 < reporter.deterministic_trace_id(999, 1) < 2**128++ def test_span_id_fits_64_bits_and_is_never_zero(self) -> None:+ for parts in [(999, 1, "run"), (999, 1, "job", 5), (999, 1, "step", 5, 10)]:+ span_id = reporter.deterministic_span_id(*parts)+ assert 0 < span_id < 2**64++ def test_span_ids_distinct_across_kinds(self) -> None:+ ids = {+ reporter.deterministic_span_id(999, 1, "run"),+ reporter.deterministic_span_id(999, 1, "job", 5),+ reporter.deterministic_span_id(999, 1, "queued", 5),+ reporter.deterministic_span_id(999, 1, "step", 5, 1),+ }+ assert len(ids) == 4+++class _FakeOpener:+ """Stands in for urllib.request.urlopen, keyed on a substring of the URL."""++ def __init__(self, routes: dict[str, Any], default: Any = None) -> None:+ self.routes = routes+ self.default = default if default is not None else {}+ self.calls: list[str] = []++ def __call__(self, request: Any, timeout: int = 0) -> Any:+ url = request.full_url+ self.calls.append(url)+ for fragment, payload in self.routes.items():+ if fragment in url:+ if isinstance(payload, Exception):+ raise payload+ return _FakeResponse(payload)+ return _FakeResponse(self.default)+++class _FakeResponse(io.BytesIO):+ def __init__(self, payload: Any) -> None:+ super().__init__(json.dumps(payload).encode())++ def __enter__(self) -> _FakeResponse:+ return self++ def __exit__(self, *_: Any) -> None:+ return None+++class TestPagination:+ def test_stops_on_short_page(self) -> None:+ opener = _FakeOpener({"/jobs": {"jobs": [{"id": 1}]}})+ jobs = reporter.fetch_jobs("PostHog/posthog", 1, 1, "t", opener=opener)+ assert len(jobs) == 1+ assert len(opener.calls) == 1++ def test_follows_full_pages(self) -> None:+ # Backend CI is already 91 jobs, so a heavier matrix crosses the page size.+ pages = iter(+ [+ {"jobs": [{"id": i} for i in range(reporter.PER_PAGE)]},+ {"jobs": [{"id": 999}]},+ ]+ )+ jobs = reporter.fetch_jobs(+ "PostHog/posthog", 1, 1, "t", opener=lambda request, timeout=0: _FakeResponse(next(pages))+ )+ assert len(jobs) == reporter.PER_PAGE + 1++ def test_respects_max_pages(self) -> None:+ full = {"jobs": [{"id": i} for i in range(reporter.PER_PAGE)]}+ opener = _FakeOpener({"/jobs": full})+ jobs = reporter.fetch_jobs("PostHog/posthog", 1, 1, "t", opener=opener)+ assert len(jobs) == reporter.PER_PAGE * reporter.MAX_PAGES+ assert len(opener.calls) == reporter.MAX_PAGES+++class TestWatermark:+ def test_uses_previous_successful_run_start(self) -> None:+ opener = _FakeOpener(+ {+ f"/workflows/{reporter.SELF_WORKFLOW_FILE}/runs": {+ "workflow_runs": [+ {"run_started_at": _iso(600)},+ {"run_started_at": _iso(300)},+ ]+ }+ }+ )+ since = reporter.watermark(+ "PostHog/posthog", "t", lookback_hours=6.0, now=RUN_START + timedelta(seconds=900), opener=opener+ )+ assert since == RUN_START + timedelta(seconds=600)++ def test_falls_back_to_lookback_without_history(self) -> None:+ # The very first tick has no prior success and must not wedge.+ opener = _FakeOpener({f"/workflows/{reporter.SELF_WORKFLOW_FILE}/runs": {"workflow_runs": []}})+ now = RUN_START + timedelta(hours=12)+ since = reporter.watermark("PostHog/posthog", "t", lookback_hours=6.0, now=now, opener=opener)+ assert since == now - timedelta(hours=6)++ def test_falls_back_when_history_is_a_404(self) -> None:+ error = urllib.error.HTTPError("u", 404, "Not Found", {}, None) # type: ignore[arg-type]+ opener = _FakeOpener({f"/workflows/{reporter.SELF_WORKFLOW_FILE}/runs": error})+ now = RUN_START + timedelta(hours=12)+ since = reporter.watermark("PostHog/posthog", "t", lookback_hours=6.0, now=now, opener=opener)+ assert since == now - timedelta(hours=6)++ def test_never_reaches_further_back_than_the_lookback(self) -> None:+ # A long reporter outage must not trigger an unbounded backfill.+ opener = _FakeOpener(+ {f"/workflows/{reporter.SELF_WORKFLOW_FILE}/runs": {"workflow_runs": [{"run_started_at": _iso(0)}]}}+ )+ now = RUN_START + timedelta(days=30)+ since = reporter.watermark("PostHog/posthog", "t", lookback_hours=6.0, now=now, opener=opener)+ assert since == now - timedelta(hours=6)+++class TestScan:+ def test_filters_on_updated_at(self) -> None:+ # The API can only filter on `created`, so without the updated_at narrowing+ # every tick would re-emit the whole window.+ opener = _FakeOpener(+ {+ "/actions/runs": {+ "workflow_runs": [+ {"id": 1, "updated_at": _iso(100)},+ {"id": 2, "updated_at": _iso(500)},+ ]+ }+ }+ )+ fresh = reporter.scan_runs("PostHog/posthog", "t", RUN_START + timedelta(seconds=300), opener=opener)+ assert [run["id"] for run in fresh] == [2]++ def test_includes_runs_updated_exactly_at_the_watermark(self) -> None:+ opener = _FakeOpener({"/actions/runs": {"workflow_runs": [{"id": 1, "updated_at": _iso(300)}]}})+ fresh = reporter.scan_runs("PostHog/posthog", "t", RUN_START + timedelta(seconds=300), opener=opener)+ assert [run["id"] for run in fresh] == [1]++ def test_scopes_the_query_to_master_pushes(self) -> None:+ opener = _FakeOpener({"/actions/runs": {"workflow_runs": []}})+ reporter.scan_runs("PostHog/posthog", "t", RUN_START, opener=opener)+ url = opener.calls[0]+ assert "branch=master" in url+ assert "event=push" in url+ assert "status=completed" in url+++class TestAttemptSelection:+ def test_selected_attempt_uses_that_attempts_window(self) -> None:+ # Pairing an older attempt's jobs with the latest attempt's `run_started_at` puts+ # every job before the root span starts, which clamps the root to zero length.+ opener = _FakeOpener(+ {+ "/attempts/2/jobs": {"jobs": [_raw_job()]},+ "/attempts/2": _raw_run(run_attempt=2),+ "/actions/runs/999": _raw_run(+ run_attempt=3, created_at=_iso(10_000), run_started_at=_iso(10_000), updated_at=_iso(10_100)+ ),+ }+ )+ args = reporter.parse_args(["--run-id", "999", "--run-attempt", "2"])+ with pytest.MonkeyPatch.context() as patch:+ patch.setattr(reporter.urllib.request, "urlopen", opener)+ collection = reporter.collect_runs(args, "t", RUN_START)++ run = collection.runs[0]+ assert run.attempt == 2+ assert run.duration_seconds == 60.0+ assert run.jobs[0].start >= run.start+ assert run.jobs[0].end <= run.end+++class TestApiRetries:+ def test_does_not_retry_a_404(self) -> None:+ # With an empty rate-limit bucket a retry just spends more of it.+ error = urllib.error.HTTPError("u", 404, "Not Found", {}, None) # type: ignore[arg-type]+ opener = _FakeOpener({"anything": error})+ with pytest.raises(reporter.ApiError) as excinfo:+ reporter._api_get("anything", "t", opener=opener)+ assert excinfo.value.status == 404+ assert len(opener.calls) == 1++ def test_retries_a_500(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(reporter.time, "sleep", lambda _seconds: None)+ error = urllib.error.HTTPError("u", 503, "Unavailable", {}, None) # type: ignore[arg-type]+ opener = _FakeOpener({"anything": error})+ with pytest.raises(reporter.ApiError):+ reporter._api_get("anything", "t", opener=opener)+ assert len(opener.calls) == reporter.API_ATTEMPTS+++class TestExitStatus:+ """The watermark is this workflow's last *successful* run, so exit status decides+ whether the next tick re-covers the window. A tick that lost traces must not be+ recorded as clean, and a tick with nothing to do must not be recorded as broken."""++ @pytest.mark.parametrize(+ "failure",+ [+ urllib.error.URLError("connection reset"),+ urllib.error.HTTPError("u", 500, "Server Error", {}, None), # type: ignore[arg-type]+ urllib.error.HTTPError("u", 403, "Forbidden", {}, None), # type: ignore[arg-type]+ ],+ )+ def test_a_failed_scan_holds_the_watermark(self, failure: Exception, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("GITHUB_TOKEN", "t")+ monkeypatch.setattr(reporter.time, "sleep", lambda _seconds: None)+ monkeypatch.setattr(reporter.urllib.request, "urlopen", _FakeOpener({"": failure}))+ assert reporter.main(["--dry-run"]) == reporter.EXIT_INCOMPLETE++ def test_malformed_json_holds_the_watermark(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("GITHUB_TOKEN", "t")+ monkeypatch.setattr(reporter.time, "sleep", lambda _seconds: None)++ class _Garbage(io.BytesIO):+ def __enter__(self) -> _Garbage:+ return self++ def __exit__(self, *_: Any) -> None:+ return None++ monkeypatch.setattr(reporter.urllib.request, "urlopen", lambda request, timeout=0: _Garbage(b"not json"))+ assert reporter.main(["--dry-run"]) == reporter.EXIT_INCOMPLETE++ def test_a_missing_github_token_holds_the_watermark(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)+ assert reporter.main([]) == reporter.EXIT_INCOMPLETE++ def test_missing_project_tokens_hold_the_watermark(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("GITHUB_TOKEN", "t")+ for var in reporter.TOKEN_ENV_VARS:+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setattr(+ reporter.urllib.request,+ "urlopen",+ _FakeOpener({"/jobs": {"jobs": [_raw_job()]}, "/actions/runs/999": _raw_run()}),+ )+ assert reporter.main(["--run-id", "999"]) == reporter.EXIT_INCOMPLETE++ def test_a_run_whose_jobs_will_not_load_holds_the_watermark(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("GITHUB_TOKEN", "t")+ monkeypatch.setattr(reporter.time, "sleep", lambda _seconds: None)+ monkeypatch.setattr(+ reporter.urllib.request,+ "urlopen",+ _FakeOpener(+ {+ "/jobs": urllib.error.HTTPError("u", 500, "Server Error", {}, None), # type: ignore[arg-type]+ "/actions/runs/999": _raw_run(),+ }+ ),+ )+ assert reporter.main(["--dry-run", "--run-id", "999"]) == reporter.EXIT_INCOMPLETE++ def test_a_rejected_export_holds_the_watermark(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # The SDK only logs a rejected batch, so an hour of 403s from the ingest+ # endpoint would otherwise read as a clean tick.+ class _RejectingExporter(SpanExporter):+ def export(self, spans: Any) -> SpanExportResult:+ return SpanExportResult.FAILURE++ monkeypatch.setenv("GITHUB_TOKEN", "t")+ monkeypatch.setenv("POSTHOG_DEVEX_PROJECT_API_TOKEN", "p")+ monkeypatch.delenv("POSTHOG_CI_TRACES_EXTRA_TOKEN", raising=False)+ monkeypatch.setattr(reporter, "OTLPSpanExporter", lambda **_kwargs: _RejectingExporter())+ monkeypatch.setattr(+ reporter.urllib.request,+ "urlopen",+ _FakeOpener({"/jobs": {"jobs": [_raw_job()]}, "/actions/runs/999": _raw_run()}),+ )+ assert reporter.main(["--run-id", "999"]) == reporter.EXIT_INCOMPLETE++ def test_an_exporter_that_raises_holds_the_watermark(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # A transport failure raises rather than returning FAILURE, and the SDK's batch+ # processor swallows it on its worker thread, so without recording the loss a total+ # outage would read as a clean tick and the watermark would advance past every trace.+ class _RaisingExporter(SpanExporter):+ def export(self, spans: Any) -> SpanExportResult:+ raise ConnectionError("ingest endpoint unreachable")++ monkeypatch.setenv("GITHUB_TOKEN", "t")+ monkeypatch.setenv("POSTHOG_DEVEX_PROJECT_API_TOKEN", "p")+ monkeypatch.delenv("POSTHOG_CI_TRACES_EXTRA_TOKEN", raising=False)+ monkeypatch.setattr(reporter, "OTLPSpanExporter", lambda **_kwargs: _RaisingExporter())+ monkeypatch.setattr(+ reporter.urllib.request,+ "urlopen",+ _FakeOpener({"/jobs": {"jobs": [_raw_job()]}, "/actions/runs/999": _raw_run()}),+ )+ assert reporter.main(["--run-id", "999"]) == reporter.EXIT_INCOMPLETE++ def test_a_run_reporting_zero_jobs_advances_the_watermark(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # A cancelled run really can report zero jobs, and nothing was lost, so the tick is clean.+ monkeypatch.setenv("GITHUB_TOKEN", "t")+ monkeypatch.setattr(+ reporter.urllib.request,+ "urlopen",+ _FakeOpener({"/jobs": {"jobs": []}, "/actions/runs/999": _raw_run()}),+ )+ assert reporter.main(["--dry-run", "--run-id", "999"]) == reporter.EXIT_OK+++class TestDryRunTree:+ def test_renders_without_touching_an_exporter(self) -> None:+ run = reporter.parse_run(_raw_run(), [_raw_job(name="Build and push PostHog")])+ assert run is not None+ lines = list(reporter.format_span_tree(run))+ assert "Container Images CD" in lines[0]+ assert any("Build and push PostHog" in line for line in lines)+++class TestSpanTree:+ """Exercises the real emit path, so an invalid attribute type or a broken+ parent link fails here rather than silently in CI."""++ @staticmethod+ def _emit(run: Any) -> list[Any]:+ exporter = InMemorySpanExporter()+ reporter.emit_trace(run, "http://unused", "token", exporter=exporter)+ return list(exporter.get_finished_spans())++ def test_builds_run_job_step_hierarchy(self) -> None:+ run = reporter.parse_run(+ _raw_run(),+ [_raw_job(name="Build and push PostHog", steps=[_raw_step(name="Set up job", start=5, end=8)])],+ )+ assert run is not None+ spans = self._emit(run)+ by_name = {span.name: span for span in spans}++ root, job, step = by_name["Container Images CD"], by_name["Build and push PostHog"], by_name["Set up job"]+ assert root.parent is None+ assert job.parent.span_id == root.context.span_id+ assert step.parent.span_id == job.context.span_id+ # One trace, so a reader sees the whole run as a single waterfall.+ assert {span.context.trace_id for span in spans} == {reporter.deterministic_trace_id(999, 1)}++ def test_queued_span_covers_the_wait(self) -> None:+ run = reporter.parse_run(_raw_run(), [_raw_job(created=0, start=30, end=60, steps=[])])+ assert run is not None+ queued = next(span for span in self._emit(run) if span.name == "queued")+ assert (queued.end_time - queued.start_time) / 1_000_000_000 == 30.0++ def test_no_queued_span_without_a_wait(self) -> None:+ run = reporter.parse_run(_raw_run(), [_raw_job(created=5, start=5, end=60, steps=[])])+ assert run is not None+ assert not [span for span in self._emit(run) if span.name == "queued"]++ def test_every_span_ends_at_or_after_it_starts(self) -> None:+ # OTLP rejects an inverted window, and skipped jobs report one.+ run = reporter.parse_run(+ _raw_run(conclusion="cancelled"),+ [+ _raw_job(id=1, name="ok", start=5, end=60),+ _raw_job(id=2, name="skipped one", conclusion="skipped", start=20, end=19, steps=[]),+ ],+ )+ assert run is not None+ spans = self._emit(run)+ assert spans+ assert all(span.end_time >= span.start_time for span in spans)++ @pytest.mark.parametrize(+ "conclusion,expected",+ [+ ("failure", "ERROR"),+ ("timed_out", "ERROR"),+ ("startup_failure", "ERROR"),+ ("success", "UNSET"),+ # Master runs get cancelled by concurrency routinely, so marking those Error+ # would bury the runs that actually broke.+ ("cancelled", "UNSET"),+ ("skipped", "UNSET"),+ ],+ )+ def test_root_status_reflects_only_the_failure_family(self, conclusion: str, expected: str) -> None:+ run = reporter.parse_run(_raw_run(conclusion=conclusion), [_raw_job(steps=[])])+ assert run is not None+ root = next(span for span in self._emit(run) if span.name == "Container Images CD")+ assert root.status.status_code.name == expected+ # The conclusion is still queryable even when the span isn't an error.+ assert root.attributes["ci.workflow.conclusion"] == conclusion++ @pytest.mark.parametrize(+ "conclusion,expected",+ [("failure", "ERROR"), ("timed_out", "ERROR"), ("cancelled", "UNSET"), ("skipped", "UNSET")],+ )+ def test_job_status_reflects_only_the_failure_family(self, conclusion: str, expected: str) -> None:+ run = reporter.parse_run(_raw_run(), [_raw_job(conclusion=conclusion, steps=[])])+ assert run is not None+ job = next(span for span in self._emit(run) if span.name == "build")+ assert job.status.status_code.name == expected++ def test_failure_marks_the_step_too(self) -> None:+ run = reporter.parse_run(+ _raw_run(conclusion="failure"),+ [_raw_job(conclusion="failure", steps=[_raw_step(name="boom", conclusion="failure")])],+ )+ assert run is not None+ statuses = {span.name: span.status.status_code.name for span in self._emit(run)}+ assert statuses["boom"] == "ERROR"+ assert statuses["build"] == "ERROR"+ assert statuses["Container Images CD"] == "ERROR"++ def test_reusable_job_records_caller_and_callee(self) -> None:+ run = reporter.parse_run(_raw_run(), [_raw_job(name="build-images / build cymbal", steps=[])])+ assert run is not None+ job = next(span for span in self._emit(run) if span.name == "build-images / build cymbal")+ assert job.attributes["ci.job.caller"] == "build-images"+ assert job.attributes["ci.job.callee"] == "build cymbal"++ def test_labels_are_a_joined_string(self) -> None:+ # A sequence would fragment downstream; one string stays queryable.+ run = reporter.parse_run(_raw_run(), [_raw_job(labels=["depot-ubuntu-24.04", "self-hosted"], steps=[])])+ assert run is not None+ job = next(span for span in self._emit(run) if span.name == "build")+ assert job.attributes["ci.job.labels"] == "depot-ubuntu-24.04,self-hosted"++ def test_span_ids_are_stable_across_emits(self) -> None:+ # A duplicate tick at the watermark boundary re-emits identical spans.+ run = reporter.parse_run(_raw_run(), [_raw_job()])+ assert run is not None+ first = {span.name: span.context.span_id for span in self._emit(run)}+ second = {span.name: span.context.span_id for span in self._emit(run)}+ assert first == second++ def test_span_count_matches_what_is_exported(self) -> None:+ run = reporter.parse_run(+ _raw_run(),+ [_raw_job(id=1, steps=[_raw_step(), _raw_step(number=2)]), _raw_job(id=2, steps=[_raw_step()])],+ )+ assert run is not None+ exporter = InMemorySpanExporter()+ reported = reporter.emit_trace(run, "http://unused", "token", exporter=exporter)+ assert reported == len(exporter.get_finished_spans())+++class TestEmissionTokens:+ @pytest.mark.parametrize(+ "env,expected_count",+ [+ ({}, 0),+ ({"POSTHOG_DEVEX_PROJECT_API_TOKEN": "a"}, 1),+ ({"POSTHOG_DEVEX_PROJECT_API_TOKEN": "a", "POSTHOG_CI_TRACES_EXTRA_TOKEN": "b"}, 2),+ # The same token in both vars must not double-emit.+ ({"POSTHOG_DEVEX_PROJECT_API_TOKEN": "a", "POSTHOG_CI_TRACES_EXTRA_TOKEN": "a"}, 1),+ ],+ )+ def test_dedupes_and_skips_empties(self, env: dict[str, str], expected_count: int) -> None:+ assert len(reporter.emission_tokens(env)) == expected_countdiff --git a/.github/workflows/ci-master-run-traces.yml b/.github/workflows/ci-master-run-traces.ymlnew file mode 100644index 000000000000..120e8f6caa46--- /dev/null+++ b/.github/workflows/ci-master-run-traces.yml@@ -0,0 +1,93 @@+name: Master run traces++# Emits one OTLP trace per completed master-push workflow run: root span = the run,+# a span per job beneath it, a span per step beneath those. Covers every workflow,+# including the ones with no telemetry of their own (Container Images CD, the+# container CD lane, the Rust image builds).+#+# Complements .github/scripts/report_test_timings.py, which emits per-test traces+# from JUnit XML under its own trace IDs. Those stay separate traces.+#+# Cron rather than a `workflow_run: workflows: ['*']` listener: that listener fires+# once per completed run (~40 per master push) and `'*'` matches the listener itself,+# so it self-triggers up to GitHub's 3-level workflow_run chain cap — thousands of+# dispatches a day against a repo that has to respect a 500-runs/10s cap. One cron+# tick that scans for newly-finished runs costs 24 dispatches a day instead.+#+# The watermark is this workflow's own last successful run, read back from the Actions+# API, so there is no cache or committed state to lose. A failed tick doesn't advance+# it, so the next tick re-covers the gap.+on:+ schedule:+ # Hourly. GitHub can delay a scheduled tick under load, which only means the next+ # one batches more runs — the watermark is time-based, so nothing is missed. The+ # 6h default lookback leaves plenty of headroom for a few skipped ticks.+ - cron: '0 * * * *'+ workflow_dispatch:+ inputs:+ since:+ description: 'ISO 8601 watermark override, for a manual backfill'+ required: false+ type: string++# Serialize ticks so two never scan the same window at once.+concurrency:+ group: ci-master-run-traces+ cancel-in-progress: false++permissions:+ contents: read+ actions: read # list master runs and read their jobs when the App-token mint falls back++jobs:+ emit-traces:+ name: Emit master run traces+ # hogli-lint: not-a-required-gate — report-only telemetry, gates nothing.+ if: github.repository == 'PostHog/posthog'+ runs-on: ubuntu-latest+ timeout-minutes: 20+ steps:+ # A cron workflow always runs the default-branch copy of this file, so the+ # checked-out script is master's. The base-ref pinning that ci-backend.yml's+ # report-test-timings needs guards against a PR swapping the script that+ # receives the project token, which cannot happen here.+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ sparse-checkout: |+ .github/scripts/report_workflow_run_traces.py+ sparse-checkout-cone-mode: false++ # Reads job durations from the Actions API — the same purpose as+ # ci-backend.yml's calculate-running-time, so it shares that bucket rather+ # than the posthog-tests app ci-alerts-devex already bursts on at merge+ # peaks. A failed mint degrades to github.token instead of skipping the tick.+ - name: Mint telemetry GitHub token+ id: app-token+ continue-on-error: true+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1+ with:+ client-id: ${{ secrets.GH_APP_TELEMETRY_APP_ID }}+ private-key: ${{ secrets.GH_APP_TELEMETRY_PRIVATE_KEY }}+ skip-token-revoke: true++ - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0+ with:+ version: '0.11.28' # pinned: unpinned setup-uv calls GH API on every job, exhausts rate limit++ # Deliberately not continue-on-error: a red tick is what holds the watermark+ # at the last clean one, so the next tick re-covers the window. This workflow+ # gates nothing, so failing costs a notification rather than a blocked merge.+ - name: Emit master run traces+ env:+ GITHUB_TOKEN: ${{ steps.app-token.outputs.token || github.token }}+ SINCE: ${{ inputs.since }}+ POSTHOG_DEVEX_PROJECT_API_TOKEN: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}+ # dual emission while CI traces migrate to the project behind POSTHOG_API_TOKEN+ POSTHOG_CI_TRACES_EXTRA_TOKEN: ${{ secrets.POSTHOG_API_TOKEN }}+ POSTHOG_OTLP_TRACES_ENDPOINT: ${{ vars.POSTHOG_OTLP_TRACES_ENDPOINT || 'https://us.i.posthog.com/i/v1/traces' }}+ run: |+ args=()+ if [[ -n "$SINCE" ]]; then+ args+=(--since "$SINCE")+ fi+ uv run --script .github/scripts/report_workflow_run_traces.py "${args[@]}"diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.ymlindex 1c140ad0cb95..8e285ba4d96f 100644--- a/.github/workflows/ci-scripts.yml+++ b/.github/workflows/ci-scripts.yml@@ -50,6 +50,11 @@ jobs:- name: Test-timings reporter tests (Python)run: python -m pytest .github/scripts/test_report_test_timings.py -v -c /dev/null -p no:cacheprovider --noconftest+ # hashFiles guard so an unrebased PR predating this script doesn't fail here.+ - name: Workflow-run trace reporter tests (Python)+ if: ${{ hashFiles('.github/scripts/test_report_workflow_run_traces.py') != '' }}+ run: python -m pytest .github/scripts/test_report_workflow_run_traces.py -v -c /dev/null -p no:cacheprovider --noconftest+# Shells out to schema_usage_scan.py via python3 (preinstalled on ubuntu).- name: Schema-impact tests (Node)run: node --test .github/scripts/schema-impact.test.js