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(eng-analytics): split presentation views and fix team scope (#72664)

Raúl Negrón-Otero1d42d3cd08c0
diff --git a/products/engineering_analytics/backend/apps.py b/products/engineering_analytics/backend/apps.py
index 8ab4e9747d88..d0b06f90ad51 100644
--- a/products/engineering_analytics/backend/apps.py
+++ b/products/engineering_analytics/backend/apps.py
@@ -4,7 +4,7 @@ from typing import TYPE_CHECKING
from django.apps import AppConfig
-# Light re-export modules (no heavy deps) — safe to import on the startup path.
+# Light re-export modules (no heavy deps), safe to import on the startup path.
from products.data_modeling.backend.facade.managed_viewset_hooks import ProvidedView, register_expected_views_provider
from products.warehouse_sources.backend.facade.hooks import register_engineering_analytics_view_sync
from products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKind
@@ -12,32 +12,33 @@ from products.warehouse_sources.backend.facade.types import DataWarehouseManaged
if TYPE_CHECKING:
from posthog.models.team import Team
+ from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
-class EngineeringAnalyticsConfig(AppConfig):
- name = "products.engineering_analytics.backend"
- label = "engineering_analytics"
- def ready(self) -> None:
- # Register the warehouse view-sync so the data-import pipeline can trigger it without
- # importing this product (it depends on warehouse_sources). The impl is imported lazily to
- # keep the read layer / data_modeling off the django.setup() path.
- def _sync_engineering_analytics_views(schema: object, source: object) -> None:
- from products.engineering_analytics.backend.warehouse_view_sync import ( # noqa: PLC0415 — keeps data_modeling + read layer off the startup path
- sync_engineering_analytics_views,
- )
+def _sync_views(schema: "ExternalDataSchema", source: "ExternalDataSource") -> None:
+ """Post-load warehouse view sync; the impl is imported lazily to keep the read layer off django.setup()."""
+ from products.engineering_analytics.backend.warehouse_view_sync import ( # noqa: PLC0415 - keeps data_modeling + the read layer off the startup path
+ sync_engineering_analytics_views,
+ )
+
+ sync_engineering_analytics_views(schema, source)
- sync_engineering_analytics_views(schema, source) # type: ignore[arg-type]
- register_engineering_analytics_view_sync(_sync_engineering_analytics_views)
+def _provided_views(team: "Team") -> list[ProvidedView]:
+ """The team's expected managed views; the impl is imported lazily (same startup constraint)."""
+ from products.engineering_analytics.backend.warehouse_view_provider import ( # noqa: PLC0415 - keeps the read layer off the startup path
+ get_provided_views,
+ )
- # Register the expected-views provider so data_modeling can sync this product's managed
- # views without importing its read layer. The impl is imported lazily to keep it off the
- # django.setup() path.
- def _get_provided_views(team: "Team") -> list[ProvidedView]:
- from products.engineering_analytics.backend.warehouse_view_provider import ( # noqa: PLC0415 — keeps the read layer off the startup path
- get_provided_views,
- )
+ return get_provided_views(team)
- return get_provided_views(team)
- register_expected_views_provider(DataWarehouseManagedViewSetKind.ENGINEERING_ANALYTICS, _get_provided_views)
+class EngineeringAnalyticsConfig(AppConfig):
+ name = "products.engineering_analytics.backend"
+ label = "engineering_analytics"
+
+ def ready(self) -> None:
+ # Hook inversion: the data-import pipeline and data_modeling call this product without
+ # importing it (a direct import in either direction would be a dependency cycle).
+ register_engineering_analytics_view_sync(_sync_views)
+ register_expected_views_provider(DataWarehouseManagedViewSetKind.ENGINEERING_ANALYTICS, _provided_views)
diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.py
deleted file mode 100644
index 7d0767e19c7d..000000000000
--- a/products/engineering_analytics/backend/presentation/views.py
+++ /dev/null
@@ -1,1473 +0,0 @@
-"""DRF views for engineering_analytics.
-
-Named, typed read endpoints over the curated PR/CI query builders. Each action
-runs curated HogQL privately (no global view registration) and returns a typed
-contract. These same endpoints back both the MCP tools and the UI:
-
-- ``ci_cards`` — backlog headline counts.
-- ``pull_requests`` — PR list with head-SHA CI rollup.
-- ``workflow_health`` — per-workflow CI health over a window.
-- ``current_branch_health`` — complete current default-branch CI verdict.
-- ``pr_lifecycle`` — a single PR's header plus its ordered CI timeline.
-- ``quarantine`` — the repo's checked-in flaky-test quarantine file.
-"""
-
-from datetime import datetime
-
-from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
-from rest_framework import serializers, status, viewsets
-from rest_framework.decorators import action
-from rest_framework.request import Request
-from rest_framework.response import Response
-
-from posthog.api.mixins import TypedRequest, validated_request
-from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.permissions import PostHogFeatureFlagPermission
-
-from products.engineering_analytics.backend.facade import api
-from products.engineering_analytics.backend.facade.contracts import (
- FLAKY_TEST_SIGNAL_CAVEAT,
- GitHubSourceNotConnectedError,
- QuarantineRequest,
- QuarantineWriteError,
- WorkflowHealthRunScope,
-)
-from products.engineering_analytics.backend.presentation.serializers import (
- BranchPRMatchSerializer,
- BrokenTestsResultSerializer,
- CICardSummarySerializer,
- CIFailureLogsSerializer,
- CurrentBranchHealthSerializer,
- FlakyTestListSerializer,
- GitHubSourceSerializer,
- MasterFailureGroupSerializer,
- PRCostSummarySerializer,
- PRLifecycleSerializer,
- PullRequestListSerializer,
- QuarantineFileSerializer,
- QuarantineRequestResultSerializer,
- QuarantineRequestSerializer,
- RepoOverviewSerializer,
- RunFailureLogsSerializer,
- TeamCIActivitySerializer,
- TeamCIHealthListSerializer,
- TeamMergeTrendSerializer,
- WorkflowCostSerializer,
- WorkflowHealthItemSerializer,
- WorkflowJobAggregateSerializer,
- WorkflowJobSerializer,
- WorkflowRunActivitySerializer,
- WorkflowRunDetailSerializer,
- WorkflowRunnerCostSerializer,
-)
-
-ENGINEERING_ANALYTICS_TAG = "engineering_analytics"
-
-_DATE_FROM = OpenApiParameter(
- name="date_from",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.",
-)
-
-# Workflow health defaults to a tighter window than the PR list (a CI-health "now" view), so it
-# advertises its own default rather than reusing _DATE_FROM's -30d.
-_WORKFLOW_DATE_FROM = OpenApiParameter(
- name="date_from",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Window start: relative ('-24h', '-7d') or ISO8601. Defaults to -24h.",
-)
-
-_DATE_TO = OpenApiParameter(
- name="date_to",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Window end: relative or ISO8601. Defaults to now.",
-)
-
-_BRANCH = OpenApiParameter(
- name="branch",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Optional exact git branch (head_branch) to scope results to, e.g. 'main'. "
- "Omit or leave blank to aggregate across all branches.",
-)
-
-_RUN_SCOPE = OpenApiParameter(
- name="run_scope",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- enum=[scope.value for scope in WorkflowHealthRunScope],
- description="Run scope for workflow health: 'all' (default) includes every run; 'pull_request' includes runs "
- "attributed to pull requests, excluding default-branch (master/main) runs. Fork PRs carry no PR attribution "
- "(a GitHub limitation), so 'pull_request' covers same-repo PRs only. Any other value is a 400.",
-)
-
-_SOURCE_ID = OpenApiParameter(
- name="source_id",
- type=OpenApiTypes.UUID,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub "
- "source when the team has more than one.",
-)
-
-_REPO = OpenApiParameter(
- name="repo",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="'owner/name' repository to scope to when the selected source syncs several repositories "
- "(from the `sources` list). Defaults to the source's first repository.",
-)
-
-
-def _bad_request(exc: ValueError, *, fallback: str) -> Response:
- return Response({"detail": str(exc) or fallback}, status=status.HTTP_400_BAD_REQUEST)
-
-
-def _require_int_param(request: Request, name: str) -> int:
- """Required integer query param; raises ValueError (handled by `_bad_request`) when missing or non-int."""
- raw = request.query_params.get(name)
- if raw is None:
- raise ValueError(f"{name} is required")
- try:
- return int(raw)
- except ValueError:
- raise ValueError(f"{name} must be an integer") from None
-
-
-def _optional_int_param(request: Request, name: str) -> int | None:
- """Optional integer query param; None when absent/blank, ValueError when present but non-int."""
- raw = request.query_params.get(name)
- if not raw:
- return None
- try:
- return int(raw)
- except ValueError:
- raise ValueError(f"{name} must be an integer") from None
-
-
-def _optional_datetime_param(request: Request, name: str) -> datetime | None:
- """Optional ISO8601 datetime query param; None when absent/blank, ValueError when present but unparseable."""
- raw = request.query_params.get(name)
- if not raw:
- return None
- try:
- return serializers.DateTimeField().to_internal_value(raw)
- except serializers.ValidationError:
- raise ValueError(f"{name} must be an ISO8601 datetime") from None
-
-
-def _bool_param(request: Request, name: str, *, default: bool) -> bool:
- """Optional boolean query param; the default when absent/blank, ValueError when present but not true/false."""
- raw = request.query_params.get(name)
- if not raw:
- return default
- lowered = raw.lower()
- if lowered in ("true", "1"):
- return True
- if lowered in ("false", "0"):
- return False
- raise ValueError(f"{name} must be true or false")
-
-
-@extend_schema(tags=[ENGINEERING_ANALYTICS_TAG])
-class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
- """PR and CI lifecycle analytics over the GitHub warehouse data."""
-
- scope_object = "engineering_analytics"
- # Same rollout flag as the UI scene and the MCP tools, so the product is gated end to end.
- permission_classes = [PostHogFeatureFlagPermission]
- posthog_feature_flag = "engineering-analytics"
- scope_object_read_actions = [
- "sources",
- "ci_cards",
- "pull_requests",
- "workflow_health",
- "pr_lifecycle",
- "resolve_branch",
- "quarantine",
- "pr_runs",
- "ci_failure_logs",
- "pr_cost",
- "workflow_run",
- "workflow_runs",
- "workflow_run_activity",
- "workflow_runner_costs",
- "author_workflow_costs",
- "workflow_jobs",
- "flaky_tests",
- "broken_tests",
- "repo_overview",
- "repo_run_activity",
- "current_branch_health",
- "master_failures",
- "run_failure_logs",
- "job_aggregates",
- ]
- scope_object_write_actions: list[str] = ["quarantine_request"]
-
- def handle_exception(self, exc: Exception) -> Response:
- # No GitHub warehouse source connected — every read action degrades the same way.
- if isinstance(exc, GitHubSourceNotConnectedError):
- return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)
- # A quarantine write that can't proceed (App not installed, malformed file, GitHub
- # failure) — the message is user-safe and explains what to fix.
- if isinstance(exc, QuarantineWriteError):
- return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)
- return super().handle_exception(exc)
-
- @extend_schema(
- operation_id="engineering_analytics_sources",
- responses={200: GitHubSourceSerializer(many=True)},
- description=(
- "The team's selectable GitHub repositories, oldest source first — one entry per repository a "
- "source is configured to sync, so a source syncing several repositories appears once per repo. "
- "Populate a repo picker from this and pass a chosen entry's `id` back as `source_id` and its "
- "`repo` back as `repo` to the other endpoints. Includes repositories whose tables aren't fully "
- "synced yet."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def sources(self, request: Request, **kwargs) -> Response:
- result = api.list_github_sources(team=self.team, user_access_control=self.user_access_control)
- return Response(GitHubSourceSerializer(instance=result, many=True).data)
-
- @extend_schema(
- operation_id="engineering_analytics_ci_cards",
- parameters=[_SOURCE_ID, _REPO],
- responses={
- 200: CICardSummarySerializer,
- 400: OpenApiResponse(description="Invalid source_id."),
- },
- description=(
- "Headline counts for the open-PR backlog: open PRs, distinct repos, stuck PRs (open, non-draft, "
- "non-bot, older than 7 days), and PRs with failing CI. The failing-CI count rests on the head-SHA "
- "join and can lag until late CI completions settle."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def ci_cards(self, request: Request, **kwargs) -> Response:
- try:
- result = api.get_ci_cards(
- team=self.team,
- source_id=request.query_params.get("source_id") or None,
- repo=request.query_params.get("repo") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid source_id")
- return Response(CICardSummarySerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_pull_requests",
- parameters=[
- _DATE_FROM,
- OpenApiParameter(
- name="author",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Optional GitHub login to scope the list to one author's pull requests.",
- ),
- _SOURCE_ID,
- _REPO,
- ],
- responses={
- 200: PullRequestListSerializer,
- 400: OpenApiResponse(description="Invalid date_from or source_id."),
- },
- description=(
- "Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with "
- "its head-SHA CI rollup. The list is capped; when more match, `truncated` is true and the ci_cards "
- "counts can exceed it. open_to_merge_seconds is coarse — it fuses draft and ready-for-review time; "
- "CI counts can lag until late completions settle."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def pull_requests(self, request: Request, **kwargs) -> Response:
- try:
- result = api.list_pull_requests(
- team=self.team,
- date_from=request.query_params.get("date_from") or None,
- author=request.query_params.get("author") or None,
- source_id=request.query_params.get("source_id") or None,
- repo=request.query_params.get("repo") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid date_from or source_id")
- return Response(PullRequestListSerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_workflow_health",
- parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _RUN_SCOPE, _SOURCE_ID, _REPO],
- responses={
- 200: WorkflowHealthItemSerializer(many=True),
- 400: OpenApiResponse(
- description="Invalid date_from, date_to, run_scope, or source_id, or a window longer than 366 days."
- ),
- },
- description=(
- "Per-workflow CI health over a window (default last 24 hours, maximum 366 days): run count, success "
- "rate, p50/p95 duration, last failure time, latest-run status, and a zero-filled run history bucketed "
- "by hour/day/week to fit the window. p50/p95 are over successful runs only, so cancelled (superseded) "
- "and failed runs never bias the duration trend. Optionally scope to a single git branch via `branch`, "
- "or to attributed pull-request runs via `run_scope=pull_request`. Use this for 'is CI getting slower' "
- "and 'which workflow is the long pole'; compare two windows to get a trend."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def workflow_health(self, request: Request, **kwargs) -> Response:
- try:
- result = api.list_workflow_health(
- team=self.team,
- date_from=request.query_params.get("date_from") or None,
- date_to=request.query_params.get("date_to") or None,
- branch=request.query_params.get("branch") or None,
- run_scope=request.query_params.get("run_scope") or None,
- source_id=request.query_params.get("source_id") or None,
- repo=request.query_params.get("repo") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid date_from, date_to, or source_id")
- return Response(WorkflowHealthItemSerializer(instance=result, many=True).data)
-
- @extend_schema(
- operation_id="engineering_analytics_pr_lifecycle",
- parameters=[
- OpenApiParameter(
- name="pr_number",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=True,
- description="Pull request number to inspect.",
- ),
- OpenApiParameter(
- name="repo",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="'owner/name' repository the pull request belongs to.",
- ),
- _SOURCE_ID,
- ],
- responses={
- 200: PRLifecycleSerializer,
- 400: OpenApiResponse(description="Missing pr_number/repo, or invalid repo or source_id."),
- 404: OpenApiResponse(description="No pull request with that number in the warehouse."),
- },
- description=(
- "The timeline of a single pull request: header plus ordered events (opened, CI started/finished, "
- "merged or closed). Use this to answer 'where is this PR stuck and what happened to it'. This is a "
- "partial view: review and comment events are not yet available."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def pr_lifecycle(self, request: Request, **kwargs) -> Response:
- repo = request.query_params.get("repo")
- try:
- pr_number = _require_int_param(request, "pr_number")
- if not repo:
- raise ValueError("repo is required")
- result = api.get_pr_lifecycle(
- team=self.team,
- pr_number=pr_number,
- repo=repo,
- source_id=request.query_params.get("source_id") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid repo or source_id")
- if result is None:
- return Response({"detail": "Pull request not found"}, status=status.HTTP_404_NOT_FOUND)
- return Response(PRLifecycleSerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_resolve_branch",
- parameters=[
- OpenApiParameter(
- name="branch",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="Git branch (the PR's head ref) to resolve. Open PRs are returned first, then most "
- "recently updated.",
- ),
- OpenApiParameter(
- name="repo",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Optional 'owner/name' repository to narrow matching to a single repo.",
- ),
- OpenApiParameter(
- name="timestamp",
- type=OpenApiTypes.DATETIME,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Optional ISO8601 timestamp, e.g. the trace's capture time. When a branch name has been "
- "reused across PRs over time, the PR whose lifetime window contains this moment is ranked first so the "
- "result matches the PR that was active when the trace was captured. A preference only, not a filter; "
- "omit to rank purely by open state then recency.",
- ),
- _SOURCE_ID,
- ],
- responses={
- 200: BranchPRMatchSerializer(many=True),
- 400: OpenApiResponse(description="Branch missing/empty, or invalid repo/timestamp/source_id."),
- },
- description=(
- "Resolve a git branch to the pull request(s) it belongs to — the cross-product link seam so another "
- "product (the LLM analytics UI) can turn a git branch into a PR detail link. Matches the PR's head ref, "
- "open PRs first then most recently updated. Pass `timestamp` (the trace's capture time) to prefer the PR "
- "that was active at that moment when a branch name has been reused across PRs. `branch` is required. "
- "Returns a possibly-empty, possibly-multi list — an empty list is a valid 200 (the caller renders a plain "
- "chip)."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def resolve_branch(self, request: Request, **kwargs) -> Response:
- try:
- matches = api.resolve_branch(
- team=self.team,
- branch=request.query_params.get("branch") or None,
- repo=request.query_params.get("repo") or None,
- timestamp=_optional_datetime_param(request, "timestamp"),
- source_id=request.query_params.get("source_id") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Provide a branch")
- return Response(BranchPRMatchSerializer(instance=matches, many=True).data)
-
- @extend_schema(
- operation_id="engineering_analytics_pr_runs",
- parameters=[
- OpenApiParameter(
- name="pr_number",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=True,
- description="Pull request number whose runs to list.",
- ),
- OpenApiParameter(
- name="repo",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="'owner/name' repository the pull request belongs to.",
- ),
- _SOURCE_ID,
- ],
- responses={
- 200: WorkflowRunDetailSerializer(many=True),
- 400: OpenApiResponse(description="Missing pr_number/repo, or invalid repo or source_id."),
- },
- description=(
- "Every workflow run attributed to a pull request, across all its commits (grouped by head SHA "
- "client-side), newest first. Run-level only."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def pr_runs(self, request: Request, **kwargs) -> Response:
- repo = request.query_params.get("repo")
- try:
- pr_number = _require_int_param(request, "pr_number")
- if not repo:
- raise ValueError("repo is required")
- runs = api.list_pr_runs(
- team=self.team,
- pr_number=pr_number,
- repo=repo,
- source_id=request.query_params.get("source_id") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid repo or source_id")
- return Response(WorkflowRunDetailSerializer(instance=runs, many=True).data)
-
- @extend_schema(
- operation_id="engineering_analytics_ci_failure_logs",
- parameters=[
- OpenApiParameter(
- name="pr_number",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=True,
- description="Pull request number whose CI failure logs to fetch.",
- ),
- OpenApiParameter(
- name="repo",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="'owner/name' repository the pull request belongs to.",
- ),
- _SOURCE_ID,
- ],
- responses={
- 200: CIFailureLogsSerializer,
- 400: OpenApiResponse(description="Missing pr_number/repo, or invalid repo or source_id."),
- },
- description=(
- "The thinned CI failure logs for a pull request, grouped by failed job. Resolves the PR to "
- "its workflow runs via the pull_requests association (all of the PR's pushes, not just the "
- "latest commit), then reads the Logs product joined on run_id. Returns failed jobs only (the "
- "worker fetches logs for failures); logs_available is false when CI hasn't failed, the logs "
- "aged out of the short Logs retention, or a fork PR has no run association. Each line carries "
- "its original 1-based line number in the full pre-thinning log; lines are the failure region "
- "(errors plus surrounding context, with omission markers), capped per job and overall."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def ci_failure_logs(self, request: Request, **kwargs) -> Response:
- repo = request.query_params.get("repo")
- try:
- pr_number = _require_int_param(request, "pr_number")
- if not repo:
- raise ValueError("repo is required")
- result = api.get_ci_failure_logs(
- team=self.team,
- pr_number=pr_number,
- repo=repo,
- source_id=request.query_params.get("source_id") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid repo or source_id")
- return Response(CIFailureLogsSerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_pr_cost",
- parameters=[
- OpenApiParameter(
- name="pr_number",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=True,
- description="Pull request number to estimate cost for.",
- ),
- OpenApiParameter(
- name="repo",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="'owner/name' repository the pull request belongs to.",
- ),
- _SOURCE_ID,
- ],
- responses={
- 200: PRCostSummarySerializer,
- 400: OpenApiResponse(description="Missing pr_number/repo, or invalid repo or source_id."),
- },
- description=(
- "Estimated CI cost for a pull request, summed over the jobs of all its workflow runs. "
- "Billable self-hosted Linux runners only — provider-hosted (free GitHub-hosted) and non-Linux "
- "jobs are excluded. Every figure is zero/null with `jobs_available` false when the job-level "
- "source isn't synced yet. `llm_spend` carries the agent LLM token spend attributed to the PR "
- "by git branch, or null when no `$ai_generation` event matched."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def pr_cost(self, request: Request, **kwargs) -> Response:
- repo = request.query_params.get("repo")
- try:
- pr_number = _require_int_param(request, "pr_number")
- if not repo:
- raise ValueError("repo is required")
- result = api.get_pr_cost(
- team=self.team,
- pr_number=pr_number,
- repo=repo,
- source_id=request.query_params.get("source_id") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid repo or source_id")
- return Response(PRCostSummarySerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_workflow_run",
- parameters=[
- OpenApiParameter(
- name="run_id",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=True,
- description="GitHub Actions run id to inspect.",
- ),
- _SOURCE_ID,
- _REPO,
- ],
- responses={
- 200: WorkflowRunDetailSerializer,
- 400: OpenApiResponse(description="Missing or non-integer run_id, or invalid source_id."),
- 404: OpenApiResponse(description="No workflow run with that id in the warehouse."),
- },
- description=(
- "A single workflow run: status, conclusion, duration, branch, attempt, and the attributed pull "
- "request. Run-level only — per-job and per-step detail are not tracked yet."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def workflow_run(self, request: Request, **kwargs) -> Response:
- try:
- result = api.get_workflow_run(
- team=self.team,
- run_id=_require_int_param(request, "run_id"),
- source_id=request.query_params.get("source_id") or None,
- repo=request.query_params.get("repo") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid source_id")
- if result is None:
- return Response({"detail": "Workflow run not found"}, status=status.HTTP_404_NOT_FOUND)
- return Response(WorkflowRunDetailSerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_workflow_runs",
- parameters=[
- OpenApiParameter(
- name="workflow_name",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="Workflow name to list runs for.",
- ),
- OpenApiParameter(
- name="repo",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="'owner/name' repository the workflow belongs to.",
- ),
- _DATE_FROM,
- _DATE_TO,
- _BRANCH,
- _SOURCE_ID,
- ],
- responses={
- 200: WorkflowRunDetailSerializer(many=True),
- 400: OpenApiResponse(description="Missing workflow_name/repo, or invalid date or source_id."),
- },
- description=(
- "Runs of a single workflow within a repo over a window (date_from default -30d), newest first. "
- "Optionally scope to a single git branch via `branch`. Each row is run-level — per-job and "
- "per-step detail are not tracked yet. Use this as the GitHub 'workflow' page between the "
- "workflow list and a single run."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def workflow_runs(self, request: Request, **kwargs) -> Response:
- workflow_name = request.query_params.get("workflow_name")
- repo = request.query_params.get("repo")
- if not workflow_name or not repo:
- return Response({"detail": "workflow_name and repo are required"}, status=status.HTTP_400_BAD_REQUEST)
-
- try:
- runs = api.list_workflow_runs(
- team=self.team,
- repo=repo,
- workflow_name=workflow_name,
- date_from=request.query_params.get("date_from") or None,
- date_to=request.query_params.get("date_to") or None,
- branch=request.query_params.get("branch") or None,
- source_id=request.query_params.get("source_id") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid date, repo, or source_id")
- return Response(WorkflowRunDetailSerializer(instance=runs, many=True).data)
-
- @extend_schema(
- operation_id="engineering_analytics_workflow_run_activity",
- parameters=[
- OpenApiParameter(
- name="workflow_name",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="Workflow name to load run activity for.",
- ),
- OpenApiParameter(
- name="repo",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="'owner/name' repository the workflow belongs to.",
- ),
- _DATE_FROM,
- _DATE_TO,
- _BRANCH,
- _SOURCE_ID,
- ],
- responses={
- 200: WorkflowRunActivitySerializer,
- 400: OpenApiResponse(description="Missing workflow_name/repo, or invalid date or source_id."),
- },
- description=(
- "Compact per-run points for a single workflow over a window (date_from default -30d), newest first, for "
- "the run-activity chart: each run's start time, duration, conclusion, branch, and attributed PR. "
- "Optionally scope to a single git branch via `branch`, matching workflow_runs. Leaner and higher-capped "
- "than workflow_runs so the chart spans the full window even on busy workflows; `truncated` is true when "
- "the cap is hit, so the chart covers only the most recent runs."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def workflow_run_activity(self, request: Request, **kwargs) -> Response:
- workflow_name = request.query_params.get("workflow_name")
- repo = request.query_params.get("repo")
- if not workflow_name or not repo:
- return Response({"detail": "workflow_name and repo are required"}, status=status.HTTP_400_BAD_REQUEST)
- try:
- result = api.get_workflow_run_activity(
- team=self.team,
- repo=repo,
- workflow_name=workflow_name,
- date_from=request.query_params.get("date_from") or None,
- date_to=request.query_params.get("date_to") or None,
- branch=request.query_params.get("branch") or None,
- source_id=request.query_params.get("source_id") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid date, repo, or source_id")
- return Response(WorkflowRunActivitySerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_workflow_runner_costs",
- parameters=[
- OpenApiParameter(
- name="workflow_name",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="Workflow name to break down cost for.",
- ),
- OpenApiParameter(
- name="repo",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="'owner/name' repository the workflow belongs to.",
- ),
- _DATE_FROM,
- _DATE_TO,
- _BRANCH,
- _SOURCE_ID,
- ],
- responses={
- 200: WorkflowRunnerCostSerializer(many=True),
- 400: OpenApiResponse(description="Missing workflow_name/repo, or invalid date or source_id."),
- },
- description=(
- "A workflow's estimated CI cost broken down by runner tier over a window (date_from default "
- "-30d), highest spend first. Optionally scope to a single git branch via `branch`. Returns an "
- "empty list when the job-level source isn't synced."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def workflow_runner_costs(self, request: Request, **kwargs) -> Response:
- workflow_name = request.query_params.get("workflow_name")
- repo = request.query_params.get("repo")
- if not workflow_name or not repo:
- return Response({"detail": "workflow_name and repo are required"}, status=status.HTTP_400_BAD_REQUEST)
- try:
- costs = api.get_workflow_runner_costs(
- team=self.team,
- repo=repo,
- workflow_name=workflow_name,
- date_from=request.query_params.get("date_from") or None,
- date_to=request.query_params.get("date_to") or None,
- branch=request.query_params.get("branch") or None,
- source_id=request.query_params.get("source_id") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid date, repo, or source_id")
- return Response(WorkflowRunnerCostSerializer(instance=costs, many=True).data)
-
- @extend_schema(
- operation_id="engineering_analytics_author_workflow_costs",
- parameters=[
- OpenApiParameter(
- name="author",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="GitHub handle whose CI spend to break down.",
- ),
- _DATE_FROM,
- _DATE_TO,
- _SOURCE_ID,
- _REPO,
- ],
- responses={
- 200: WorkflowCostSerializer(many=True),
- 400: OpenApiResponse(description="Missing author, or invalid date or source_id."),
- },
- description=(
- "One author's estimated CI cost split by workflow over a window (date_from default -30d), "
- "highest spend first. Runs are attributed to the author through their pull requests (attribution "
- "is by PR number). Returns an empty list when the job-level source isn't synced."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def author_workflow_costs(self, request: Request, **kwargs) -> Response:
- author = request.query_params.get("author")
- if not author:
- return Response({"detail": "author is required"}, status=status.HTTP_400_BAD_REQUEST)
- try:
- costs = api.list_author_workflow_costs(
- team=self.team,
- author=author,
- date_from=request.query_params.get("date_from") or None,
- date_to=request.query_params.get("date_to") or None,
- source_id=request.query_params.get("source_id") or None,
- repo=request.query_params.get("repo") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid author, date, or source_id")
- return Response(WorkflowCostSerializer(instance=costs, many=True).data)
-
- @extend_schema(
- operation_id="engineering_analytics_workflow_jobs",
- parameters=[
- OpenApiParameter(
- name="run_id",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=True,
- description="Workflow run id to list jobs for.",
- ),
- OpenApiParameter(
- name="run_attempt",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Which re-run attempt to scope jobs to. Omit to use the run's latest attempt; pass an "
- "explicit attempt to avoid mixing jobs across a re-run's attempts.",
- ),
- _SOURCE_ID,
- _REPO,
- ],
- responses={
- 200: WorkflowJobSerializer(many=True),
- 400: OpenApiResponse(description="Missing or non-integer run_id/run_attempt, or invalid source_id."),
- },
- description=(
- "Jobs of a single workflow run attempt, with per-job duration, runner tier, and estimated cost. "
- "Scoped to one run_attempt (the latest unless specified) so a re-run's attempts don't merge. "
- "Returns an empty list when the job-level source isn't synced yet."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def workflow_jobs(self, request: Request, **kwargs) -> Response:
- try:
- jobs = api.list_workflow_jobs(
- team=self.team,
- run_id=_require_int_param(request, "run_id"),
- run_attempt=_optional_int_param(request, "run_attempt"),
- source_id=request.query_params.get("source_id") or None,
- repo=request.query_params.get("repo") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid source_id")
- return Response(WorkflowJobSerializer(instance=jobs, many=True).data)
-
- @extend_schema(
- operation_id="engineering_analytics_flaky_tests",
- parameters=[
- OpenApiParameter(
- name="date_from",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Window start: relative ('-7d', '-30d') or ISO8601. Defaults to -7d; the window "
- "may span at most 30 days.",
- ),
- _DATE_TO,
- OpenApiParameter(
- name="min_rerun_passes",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=False,
- description="A test qualifies once it passed on retry at least this many times in the window "
- "(OR-ed with min_failed_prs). Minimum 1. Defaults to 1.",
- ),
- OpenApiParameter(
- name="min_failed_prs",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=False,
- description="A test qualifies once it failed on at least this many distinct pull requests in "
- "the window (OR-ed with min_rerun_passes). Minimum 1. Defaults to 3.",
- ),
- OpenApiParameter(
- name="limit",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Maximum number of tests to return (1-200). Defaults to 50.",
- ),
- _SOURCE_ID,
- _REPO,
- ],
- responses={
- 200: FlakyTestListSerializer,
- 400: OpenApiResponse(
- description="Invalid date, threshold, limit, or source_id, or a window longer than 30 days."
- ),
- },
- description=(
- "The flaky-test leaderboard: backend tests ranked by flakiness signal from the per-test CI spans, "
- "over a window (default -7d, maximum 30 days). A test qualifies by passing on retry at least "
- "min_rerun_passes times OR failing on at least min_failed_prs distinct PRs. " + FLAKY_TEST_SIGNAL_CAVEAT
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def flaky_tests(self, request: Request, **kwargs) -> Response:
- try:
- result = api.list_flaky_tests(
- team=self.team,
- date_from=request.query_params.get("date_from") or None,
- date_to=request.query_params.get("date_to") or None,
- min_rerun_passes=_optional_int_param(request, "min_rerun_passes"),
- min_failed_prs=_optional_int_param(request, "min_failed_prs"),
- limit=_optional_int_param(request, "limit"),
- source_id=request.query_params.get("source_id") or None,
- repo=request.query_params.get("repo") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid date, threshold, limit, or source_id")
- return Response(FlakyTestListSerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_team_ci_health",
- parameters=[
- OpenApiParameter(
- name="date_from",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window "
- "may span at most 30 days. An equal-length prior window is scanned for the *_prior twins; "
- "near the 30-day ceiling that prior window can reach past Traces retention, deflating "
- "*_prior counts and overstating deltas.",
- ),
- _DATE_TO,
- OpenApiParameter(
- name="min_rerun_passes",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=False,
- description="A test counts as flaky once it passed on retry at least this many times in the "
- "window (OR-ed with min_failed_prs). Minimum 1. Defaults to 1.",
- ),
- OpenApiParameter(
- name="min_failed_prs",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=False,
- description="A test counts as flaky once it failed on at least this many distinct pull "
- "requests in the window (OR-ed with min_rerun_passes). Minimum 1. Defaults to 3.",
- ),
- OpenApiParameter(
- name="limit",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Maximum number of teams to return (1-200). Defaults to 100.",
- ),
- _SOURCE_ID,
- ],
- responses={
- 200: TeamCIHealthListSerializer,
- 400: OpenApiResponse(
- description="Invalid date, threshold, limit, or source_id, or a window longer than 30 days."
- ),
- },
- description=(
- "Per-owning-team rollup of the CI test surfaces each team owns: flaky-test count, failure and "
- "pass-on-retry span counts, each with an equal-length previous-window twin for honest deltas. "
- "Ownership is stamped on the spans at CI emission time from the repo's ownership map "
- "(products/*/product.yaml + CODEOWNERS); unstamped spans aggregate under the literal team "
- "'unowned'. Teams are organizational owners of code surfaces, never authors. " + FLAKY_TEST_SIGNAL_CAVEAT
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def team_ci_health(self, request: Request, **kwargs) -> Response:
- try:
- result = api.list_team_ci_health(
- team=self.team,
- date_from=request.query_params.get("date_from") or None,
- date_to=request.query_params.get("date_to") or None,
- min_rerun_passes=_optional_int_param(request, "min_rerun_passes"),
- min_failed_prs=_optional_int_param(request, "min_failed_prs"),
- limit=_optional_int_param(request, "limit"),
- source_id=request.query_params.get("source_id") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid date, threshold, limit, or source_id")
- return Response(TeamCIHealthListSerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_team_ci_activity",
- parameters=[
- OpenApiParameter(
- name="owner_team",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="Owning team slug to scope to (as returned by team_ci_health), e.g. 'team-replay', "
- "or the literal 'unowned' for tests with no ownership stamp.",
- ),
- OpenApiParameter(
- name="date_from",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window "
- "may span at most 30 days. An equal-length prior window feeds the *_prior twins; near the "
- "30-day ceiling that prior window can reach past Traces retention, deflating *_prior counts.",
- ),
- _DATE_TO,
- OpenApiParameter(
- name="test_limit",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Maximum number of per-test signal rows to return (1-100). Defaults to 25.",
- ),
- _SOURCE_ID,
- ],
- responses={
- 200: TeamCIActivitySerializer,
- 400: OpenApiResponse(
- description="Missing owner_team, invalid date, test_limit, or source_id, or a window longer "
- "than 30 days."
- ),
- },
- description=(
- "One owning team's CI test activity: per-test current-vs-prior signal pairs (the before/after "
- "comparison) over the window and its equal-length prior twin. Signal = failed + error + "
- "pass-on-retry spans on the team's owned tests. " + FLAKY_TEST_SIGNAL_CAVEAT
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def team_ci_activity(self, request: Request, **kwargs) -> Response:
- try:
- result = api.get_team_ci_activity(
- team=self.team,
- owner_team=request.query_params.get("owner_team") or "",
- date_from=request.query_params.get("date_from") or None,
- date_to=request.query_params.get("date_to") or None,
- test_limit=_optional_int_param(request, "test_limit"),
- source_id=request.query_params.get("source_id") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid owner_team, date, test_limit, or source_id")
- return Response(TeamCIActivitySerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_team_merge_trend",
- parameters=[
- OpenApiParameter(
- name="owner_team",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="Team slug to scope to (as returned by team_ci_health), matched against the "
- "GitHub org team slug of the source's team_members snapshot. The literal 'unowned' names "
- "an ownership gap, not an org team, and has no merge trend.",
- ),
- OpenApiParameter(
- name="date_from",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window "
- "may span at most 30 days.",
- ),
- _DATE_TO,
- _SOURCE_ID,
- ],
- responses={
- 200: TeamMergeTrendSerializer,
- 400: OpenApiResponse(
- description="Missing owner_team, invalid date or source_id, or a window longer than 30 days."
- ),
- },
- description=(
- "One team's daily time-to-merge trend: the median and average open→merge seconds over the PRs "
- "the team's members merged each day (PR author login → GitHub org team membership). Team-level "
- "aggregates only, never per-member figures or cross-team rankings. Timing is the coarse "
- "open→merge (draft + review time combined); bots are excluded. Requires the GitHub source's "
- "team_members snapshot; has_membership_data is false without it."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def team_merge_trend(self, request: Request, **kwargs) -> Response:
- try:
- result = api.get_team_merge_trend(
- team=self.team,
- owner_team=request.query_params.get("owner_team") or "",
- date_from=request.query_params.get("date_from") or None,
- date_to=request.query_params.get("date_to") or None,
- source_id=request.query_params.get("source_id") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid owner_team, date, or source_id")
- return Response(TeamMergeTrendSerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_broken_tests",
- parameters=[_SOURCE_ID, _REPO],
- responses={
- 200: BrokenTestsResultSerializer,
- 400: OpenApiResponse(description="Invalid source_id."),
- },
- description=(
- "The broken-tests triage panel: live CI failures over the last 2 days grouped into distinct "
- "failures (by test id + normalized error signature) and classified by how each is behaving right "
- "now — breaking trunk, a new failure spreading across branches, probably-resolved, flaky, or one "
- "PR's own problem — ranked with the most urgent first. Also returns breaking_master_jobs, the "
- "default-branch jobs whose latest run is red. Reach for this to answer 'what CI failures should I "
- "care about right now'; expand a row's latest_run_id via run_failure_logs for the failing lines. "
- "Fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and "
- "the breaking/resolved distinction needs the job-level source synced — without it those failures "
- "fall through to flaky/pr_only rather than being misreported."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def broken_tests(self, request: Request, **kwargs) -> Response:
- try:
- result = api.get_broken_tests(
- team=self.team,
- source_id=request.query_params.get("source_id") or None,
- repo=request.query_params.get("repo") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid source_id")
- return Response(BrokenTestsResultSerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_repo_overview",
- parameters=[
- _DATE_FROM,
- _DATE_TO,
- OpenApiParameter(
- name="include_series",
- type=OpenApiTypes.BOOL,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Set false to skip the chart series (cost_series, time_to_green_series, "
- "success_rate_series, open_to_merge_series return empty) and their query cost — for "
- "headline-only consumers like the weekly digest. Defaults to true.",
- ),
- _SOURCE_ID,
- _REPO,
- ],
- responses={
- 200: RepoOverviewSerializer,
- 400: OpenApiResponse(description="Invalid date_from, date_to, or source_id, or a window over 366 days."),
- },
- description=(
- "Repo-level headline aggregates over a window (default -30d): run count, success rate, re-run "
- "cycles, merged-PR count (bots included), median PR open-to-merge (bots and drafts excluded; "
- "coarse — draft and ready time fused), and billable minutes + estimated cost — each with its "
- "equal-length previous-window twin so a caller can render honest deltas. Also carries the "
- "detected default branch and its completed-run history series (skippable via include_series=false). "
- "Cost figures are null until the job-level source is synced."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def repo_overview(self, request: Request, **kwargs) -> Response:
- try:
- result = api.get_repo_overview(
- team=self.team,
- date_from=request.query_params.get("date_from") or None,
- date_to=request.query_params.get("date_to") or None,
- include_series=_bool_param(request, "include_series", default=True),
- source_id=request.query_params.get("source_id") or None,
- repo=request.query_params.get("repo") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid date_from, date_to, include_series, or source_id")
- return Response(RepoOverviewSerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_current_branch_health",
- parameters=[_SOURCE_ID, _REPO],
- responses={
- 200: CurrentBranchHealthSerializer,
- 400: OpenApiResponse(description="Invalid source_id."),
- },
- description=(
- "Current default-branch CI verdict over the fixed last-24-hours window. Counts every workflow whose "
- "latest completed run failed or timed out; failing workflow names are a bounded preview. The default "
- "branch is detected from the same window, independently of analytics date filters."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def current_branch_health(self, request: Request, **kwargs) -> Response:
- try:
- result = api.get_current_branch_health(
- team=self.team,
- source_id=request.query_params.get("source_id") or None,
- repo=request.query_params.get("repo") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid source_id")
- return Response(CurrentBranchHealthSerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_repo_run_activity",
- parameters=[
- _DATE_FROM,
- _DATE_TO,
- # This endpoint never aggregates across branches, so the shared _BRANCH "omit to aggregate"
- # wording would misdescribe the omit behavior in every generated client.
- OpenApiParameter(
- name="branch",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Optional exact git branch (head_branch) to chart, e.g. 'main'. "
- "Omit or leave blank to use the repo's detected default branch.",
- ),
- _SOURCE_ID,
- _REPO,
- ],
- responses={
- 200: WorkflowRunActivitySerializer,
- 400: OpenApiResponse(description="Invalid date_from, date_to, or source_id, or a window over 366 days."),
- },
- description=(
- "Default-branch health as compact chart points over a window (default -30d), newest first, for the "
- "repo-hub run-activity chart. All of a commit's workflow runs are collapsed into ONE point per commit "
- "(head SHA): its earliest workflow start, wall-clock duration until the last workflow settled (null "
- "while any is still running), and an overall conclusion that is 'failure' if any workflow decisively "
- "failed, else 'success' when at least one passed, else 'neutral'. `branch` overrides the detected "
- "default branch. `truncated` is true when more commits matched than the cap, so the chart covers only "
- "the most recent commits."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def repo_run_activity(self, request: Request, **kwargs) -> Response:
- try:
- result = api.get_repo_run_activity(
- team=self.team,
- date_from=request.query_params.get("date_from") or None,
- date_to=request.query_params.get("date_to") or None,
- branch=request.query_params.get("branch") or None,
- source_id=request.query_params.get("source_id") or None,
- repo=request.query_params.get("repo") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid date_from, date_to, or source_id")
- return Response(WorkflowRunActivitySerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_master_failures",
- parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _SOURCE_ID, _REPO],
- responses={
- 200: MasterFailureGroupSerializer(many=True),
- 400: OpenApiResponse(description="Invalid date_from, date_to, or source_id, or a window over 366 days."),
- },
- description=(
- "Default-branch failures over a window (default -24h), grouped error-tracking style by "
- "(workflow, de-sharded failing job) with a run count and first/last seen, newest group first. "
- "`branch` overrides the detected default branch. PR-branch failures are deliberately excluded — "
- "at monorepo volume a flat feed is a firehose; those surface per PR. Groups degrade to workflow "
- "level (failed_job '') when the job-level source isn't synced."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def master_failures(self, request: Request, **kwargs) -> Response:
- try:
- result = api.list_master_failures(
- team=self.team,
- date_from=request.query_params.get("date_from") or None,
- date_to=request.query_params.get("date_to") or None,
- branch=request.query_params.get("branch") or None,
- source_id=request.query_params.get("source_id") or None,
- repo=request.query_params.get("repo") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid date_from, date_to, or source_id")
- return Response(MasterFailureGroupSerializer(instance=result, many=True).data)
-
- @extend_schema(
- operation_id="engineering_analytics_run_failure_logs",
- parameters=[
- OpenApiParameter(
- name="run_id",
- type=OpenApiTypes.INT,
- location=OpenApiParameter.QUERY,
- required=True,
- description="Workflow run id whose failure logs to fetch.",
- ),
- _SOURCE_ID,
- _REPO,
- ],
- responses={
- 200: RunFailureLogsSerializer,
- 400: OpenApiResponse(description="Missing or non-integer run_id, or invalid source_id."),
- },
- description=(
- "The thinned CI failure logs of one workflow run, grouped by failed job — the run-scoped twin of "
- "ci_failure_logs for surfaces that aren't PR-scoped (default-branch failures, the run page). "
- "logs_available is false when the run didn't fail or its logs aged out of the short Logs retention."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def run_failure_logs(self, request: Request, **kwargs) -> Response:
- try:
- result = api.get_run_failure_logs(
- team=self.team,
- run_id=_require_int_param(request, "run_id"),
- source_id=request.query_params.get("source_id") or None,
- repo=request.query_params.get("repo") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid source_id")
- return Response(RunFailureLogsSerializer(instance=result).data)
-
- @extend_schema(
- operation_id="engineering_analytics_job_aggregates",
- parameters=[
- OpenApiParameter(
- name="workflow_name",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=True,
- description="Workflow name to aggregate jobs for.",
- ),
- _DATE_FROM,
- _DATE_TO,
- _BRANCH,
- _SOURCE_ID,
- _REPO,
- ],
- responses={
- 200: WorkflowJobAggregateSerializer(many=True),
- 400: OpenApiResponse(description="Missing workflow_name, or invalid date or source_id."),
- },
- description=(
- "Per-job aggregates for one workflow over a window (default -30d), one row per de-sharded job "
- "name (matrix shards aggregate together), busiest first: queue p50, duration p50/p95, failure "
- "rate, retry pressure, run share (below 1.0 = conditional job), and billable cost. Jobs always "
- "need their run as context — this is the aggregate view; use workflow_jobs for one run's jobs. "
- "Empty when the job-level source isn't synced."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def job_aggregates(self, request: Request, **kwargs) -> Response:
- workflow_name = request.query_params.get("workflow_name")
- if not workflow_name:
- return Response({"detail": "workflow_name is required"}, status=status.HTTP_400_BAD_REQUEST)
- try:
- result = api.list_job_aggregates(
- team=self.team,
- workflow_name=workflow_name,
- date_from=request.query_params.get("date_from") or None,
- date_to=request.query_params.get("date_to") or None,
- branch=request.query_params.get("branch") or None,
- source_id=request.query_params.get("source_id") or None,
- repo=request.query_params.get("repo") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid date, workflow_name, or source_id")
- return Response(WorkflowJobAggregateSerializer(instance=result, many=True).data)
-
- @extend_schema(
- operation_id="engineering_analytics_quarantine",
- summary="Flaky-test quarantine file",
- parameters=[
- OpenApiParameter(
- name="repo",
- type=OpenApiTypes.STR,
- location=OpenApiParameter.QUERY,
- required=False,
- description="Optional 'owner/name' repository to read the quarantine file from. Defaults to the "
- "connected GitHub source's most active repo over the last 30 days.",
- ),
- _SOURCE_ID,
- ],
- responses={
- 200: QuarantineFileSerializer,
- 400: OpenApiResponse(description="Invalid repo or source_id."),
- },
- description=(
- "The repository's checked-in .test_quarantine.json: flaky tests temporarily quarantined with a hard "
- "expiry, classified by urgency (overdue, in grace, expiring soon, active). `available` is false when "
- "the repo has no quarantine file — that is not an error. Parsing is fail-open: malformed entries are "
- "reported in parse_errors while well-formed ones are kept."
- ),
- )
- @action(detail=False, methods=["get"], pagination_class=None)
- def quarantine(self, request: Request, **kwargs) -> Response:
- try:
- result = api.get_quarantine(
- team=self.team,
- repo=request.query_params.get("repo") or None,
- source_id=request.query_params.get("source_id") or None,
- user_access_control=self.user_access_control,
- )
- except ValueError as exc:
- return _bad_request(exc, fallback="Invalid repo or source_id")
- return Response(QuarantineFileSerializer(instance=result).data)
-
- @validated_request(
- request_serializer=QuarantineRequestSerializer,
- operation_id="engineering_analytics_quarantine_request",
- responses={
- 201: OpenApiResponse(
- response=QuarantineRequestResultSerializer,
- description="The opened pull request, plus the tracking issue for a new quarantine.",
- ),
- 400: OpenApiResponse(
- description="Invalid input, or the write could not be completed (no GitHub App installed on the "
- "repo's org, a malformed quarantine file, or a GitHub failure). The detail message is safe to show."
- ),
- },
- summary="Quarantine, extend, or unquarantine a flaky test",
- description=(
- "Opens a pull request that edits the repository's checked-in .test_quarantine.json — and, for a new "
- "quarantine, a tracking issue the PR links but does not close. The file stays the source of truth that "
- "CI enforces; this never bypasses it. A quarantine only affects CI runs that start after the PR merges."
- ),
- )
- @action(detail=False, methods=["post"], url_path="quarantine/request", pagination_class=None)
- def quarantine_request(self, request: TypedRequest[QuarantineRequest], **kwargs) -> Response:
- result = api.request_quarantine(
- team=self.team,
- request=request.validated_data,
- user_access_control=self.user_access_control,
- )
- return Response(QuarantineRequestResultSerializer(instance=result).data, status=status.HTTP_201_CREATED)
diff --git a/products/engineering_analytics/backend/presentation/views/__init__.py b/products/engineering_analytics/backend/presentation/views/__init__.py
new file mode 100644
index 000000000000..5de97c8b3c7e
--- /dev/null
+++ b/products/engineering_analytics/backend/presentation/views/__init__.py
@@ -0,0 +1,67 @@
+"""DRF views for engineering_analytics.
+
+Named, typed read endpoints over the curated PR/CI query builders, one module per surface area,
+composed here into the single ``EngineeringAnalyticsViewSet`` (one URL space, one OpenAPI tag).
+Shared parameters, query-param helpers, and error degradation live in ``_base``.
+"""
+
+from drf_spectacular.utils import extend_schema
+
+from products.engineering_analytics.backend.presentation.views._base import (
+ ENGINEERING_ANALYTICS_TAG,
+ EngineeringAnalyticsViewSetBase,
+)
+from products.engineering_analytics.backend.presentation.views.pull_requests import PullRequestActionsMixin
+from products.engineering_analytics.backend.presentation.views.sources import SourcesMixin
+from products.engineering_analytics.backend.presentation.views.suite_health import TestHealthActionsMixin
+from products.engineering_analytics.backend.presentation.views.teams import TeamActionsMixin
+from products.engineering_analytics.backend.presentation.views.workflows import WorkflowActionsMixin
+
+
+@extend_schema(tags=[ENGINEERING_ANALYTICS_TAG])
+class EngineeringAnalyticsViewSet(
+ SourcesMixin,
+ PullRequestActionsMixin,
+ WorkflowActionsMixin,
+ TestHealthActionsMixin,
+ TeamActionsMixin,
+ EngineeringAnalyticsViewSetBase,
+):
+ """PR and CI lifecycle analytics over the GitHub warehouse data."""
+
+ # Grouped by mixin; TestScopeEnrollment asserts this stays in lockstep with the actions.
+ scope_object_read_actions = [
+ # sources
+ "sources",
+ # pull_requests
+ "ci_cards",
+ "pull_requests",
+ "pr_lifecycle",
+ "resolve_branch",
+ "pr_runs",
+ "ci_failure_logs",
+ "pr_cost",
+ "author_workflow_costs",
+ # workflows
+ "workflow_health",
+ "workflow_run",
+ "workflow_runs",
+ "workflow_run_activity",
+ "workflow_runner_costs",
+ "workflow_jobs",
+ "repo_overview",
+ "current_branch_health",
+ "repo_run_activity",
+ "master_failures",
+ "run_failure_logs",
+ "job_aggregates",
+ # test_health
+ "flaky_tests",
+ "broken_tests",
+ "quarantine",
+ # teams
+ "team_ci_health",
+ "team_ci_activity",
+ "team_merge_trend",
+ ]
+ scope_object_write_actions: list[str] = ["quarantine_request"]
diff --git a/products/engineering_analytics/backend/presentation/views/_base.py b/products/engineering_analytics/backend/presentation/views/_base.py
new file mode 100644
index 000000000000..e68522c1f687
--- /dev/null
+++ b/products/engineering_analytics/backend/presentation/views/_base.py
@@ -0,0 +1,153 @@
+"""Shared OpenAPI parameter vocabulary, query-param helpers, and the viewset base."""
+
+from datetime import datetime
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter
+from rest_framework import serializers, status, viewsets
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.permissions import PostHogFeatureFlagPermission
+
+from products.engineering_analytics.backend.facade.contracts import (
+ GitHubSourceNotConnectedError,
+ QuarantineWriteError,
+ WorkflowHealthRunScope,
+)
+
+ENGINEERING_ANALYTICS_TAG = "engineering_analytics"
+
+_DATE_FROM = OpenApiParameter(
+ name="date_from",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.",
+)
+
+# Workflow health defaults to a tighter window than the PR list (a CI-health "now" view), so it
+# advertises its own default rather than reusing _DATE_FROM's -30d.
+_WORKFLOW_DATE_FROM = OpenApiParameter(
+ name="date_from",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Window start: relative ('-24h', '-7d') or ISO8601. Defaults to -24h.",
+)
+
+_DATE_TO = OpenApiParameter(
+ name="date_to",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Window end: relative or ISO8601. Defaults to now.",
+)
+
+_BRANCH = OpenApiParameter(
+ name="branch",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Optional exact git branch (head_branch) to scope results to, e.g. 'main'. "
+ "Omit or leave blank to aggregate across all branches.",
+)
+
+_RUN_SCOPE = OpenApiParameter(
+ name="run_scope",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ enum=[scope.value for scope in WorkflowHealthRunScope],
+ description="Run scope for workflow health: 'all' (default) includes every run; 'pull_request' includes runs "
+ "attributed to pull requests, excluding default-branch (master/main) runs. Fork PRs carry no PR attribution "
+ "(a GitHub limitation), so 'pull_request' covers same-repo PRs only. Any other value is a 400.",
+)
+
+_SOURCE_ID = OpenApiParameter(
+ name="source_id",
+ type=OpenApiTypes.UUID,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub "
+ "source when the team has more than one.",
+)
+
+_REPO = OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="'owner/name' repository to scope to when the selected source syncs several repositories "
+ "(from the `sources` list). Defaults to the source's first repository.",
+)
+
+
+def _bad_request(exc: ValueError, *, fallback: str) -> Response:
+ return Response({"detail": str(exc) or fallback}, status=status.HTTP_400_BAD_REQUEST)
+
+
+def _require_int_param(request: Request, name: str) -> int:
+ """Required integer query param; raises ValueError (handled by `_bad_request`) when missing or non-int."""
+ raw = request.query_params.get(name)
+ if raw is None:
+ raise ValueError(f"{name} is required")
+ try:
+ return int(raw)
+ except ValueError:
+ raise ValueError(f"{name} must be an integer") from None
+
+
+def _optional_int_param(request: Request, name: str) -> int | None:
+ """Optional integer query param; None when absent/blank, ValueError when present but non-int."""
+ raw = request.query_params.get(name)
+ if not raw:
+ return None
+ try:
+ return int(raw)
+ except ValueError:
+ raise ValueError(f"{name} must be an integer") from None
+
+
+def _optional_datetime_param(request: Request, name: str) -> datetime | None:
+ """Optional ISO8601 datetime query param; None when absent/blank, ValueError when present but unparseable."""
+ raw = request.query_params.get(name)
+ if not raw:
+ return None
+ try:
+ return serializers.DateTimeField().to_internal_value(raw)
+ except serializers.ValidationError:
+ raise ValueError(f"{name} must be an ISO8601 datetime") from None
+
+
+def _bool_param(request: Request, name: str, *, default: bool) -> bool:
+ """Optional boolean query param; the default when absent/blank, ValueError when present but not true/false."""
+ raw = request.query_params.get(name)
+ if not raw:
+ return default
+ lowered = raw.lower()
+ if lowered in ("true", "1"):
+ return True
+ if lowered in ("false", "0"):
+ return False
+ raise ValueError(f"{name} must be true or false")
+
+
+class EngineeringAnalyticsViewSetBase(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ """Shared config and error degradation for every engineering_analytics action mixin."""
+
+ scope_object = "engineering_analytics"
+ # Same rollout flag as the UI scene and the MCP tools, so the product is gated end to end.
+ permission_classes = [PostHogFeatureFlagPermission]
+ posthog_feature_flag = "engineering-analytics"
+
+ def handle_exception(self, exc: Exception) -> Response:
+ # No GitHub warehouse source connected: every read action degrades the same way.
+ if isinstance(exc, GitHubSourceNotConnectedError):
+ return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)
+ # A quarantine write that can't proceed (App not installed, malformed file, GitHub
+ # failure): the message is user-safe and explains what to fix.
+ if isinstance(exc, QuarantineWriteError):
+ return Response({"detail": str(exc)}, status=status.HTTP_400_BAD_REQUEST)
+ return super().handle_exception(exc)
diff --git a/products/engineering_analytics/backend/presentation/views/pull_requests.py b/products/engineering_analytics/backend/presentation/views/pull_requests.py
new file mode 100644
index 000000000000..bbdb5178eb96
--- /dev/null
+++ b/products/engineering_analytics/backend/presentation/views/pull_requests.py
@@ -0,0 +1,396 @@
+"""PR-scoped reads: backlog cards, lists, lifecycle, runs, logs, and cost."""
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
+from rest_framework import status
+from rest_framework.decorators import action
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from products.engineering_analytics.backend.facade import api
+from products.engineering_analytics.backend.presentation.serializers import (
+ BranchPRMatchSerializer,
+ CICardSummarySerializer,
+ CIFailureLogsSerializer,
+ PRCostSummarySerializer,
+ PRLifecycleSerializer,
+ PullRequestListSerializer,
+ WorkflowCostSerializer,
+ WorkflowRunDetailSerializer,
+)
+from products.engineering_analytics.backend.presentation.views._base import (
+ _DATE_FROM,
+ _DATE_TO,
+ _REPO,
+ _SOURCE_ID,
+ EngineeringAnalyticsViewSetBase,
+ _bad_request,
+ _optional_datetime_param,
+ _require_int_param,
+)
+
+
+class PullRequestActionsMixin(EngineeringAnalyticsViewSetBase):
+ @extend_schema(
+ operation_id="engineering_analytics_ci_cards",
+ parameters=[_SOURCE_ID, _REPO],
+ responses={
+ 200: CICardSummarySerializer,
+ 400: OpenApiResponse(description="Invalid source_id."),
+ },
+ description=(
+ "Headline counts for the open-PR backlog: open PRs, distinct repos, stuck PRs (open, non-draft, "
+ "non-bot, older than 7 days), and PRs with failing CI. The failing-CI count rests on the head-SHA "
+ "join and can lag until late CI completions settle."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def ci_cards(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_ci_cards(
+ team=self.team,
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid source_id")
+ return Response(CICardSummarySerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_pull_requests",
+ parameters=[
+ _DATE_FROM,
+ OpenApiParameter(
+ name="author",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Optional GitHub login to scope the list to one author's pull requests.",
+ ),
+ _SOURCE_ID,
+ _REPO,
+ ],
+ responses={
+ 200: PullRequestListSerializer,
+ 400: OpenApiResponse(description="Invalid date_from or source_id."),
+ },
+ description=(
+ "Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with "
+ "its head-SHA CI rollup. The list is capped; when more match, `truncated` is true and the ci_cards "
+ "counts can exceed it. open_to_merge_seconds is coarse — it fuses draft and ready-for-review time; "
+ "CI counts can lag until late completions settle."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def pull_requests(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.list_pull_requests(
+ team=self.team,
+ date_from=request.query_params.get("date_from") or None,
+ author=request.query_params.get("author") or None,
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date_from or source_id")
+ return Response(PullRequestListSerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_pr_lifecycle",
+ parameters=[
+ OpenApiParameter(
+ name="pr_number",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Pull request number to inspect.",
+ ),
+ OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="'owner/name' repository the pull request belongs to.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: PRLifecycleSerializer,
+ 400: OpenApiResponse(description="Missing pr_number/repo, or invalid repo or source_id."),
+ 404: OpenApiResponse(description="No pull request with that number in the warehouse."),
+ },
+ description=(
+ "The timeline of a single pull request: header plus ordered events (opened, CI started/finished, "
+ "merged or closed). Use this to answer 'where is this PR stuck and what happened to it'. This is a "
+ "partial view: review and comment events are not yet available."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def pr_lifecycle(self, request: Request, **kwargs) -> Response:
+ repo = request.query_params.get("repo")
+ try:
+ pr_number = _require_int_param(request, "pr_number")
+ if not repo:
+ raise ValueError("repo is required")
+ result = api.get_pr_lifecycle(
+ team=self.team,
+ pr_number=pr_number,
+ repo=repo,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid repo or source_id")
+ if result is None:
+ return Response({"detail": "Pull request not found"}, status=status.HTTP_404_NOT_FOUND)
+ return Response(PRLifecycleSerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_resolve_branch",
+ parameters=[
+ OpenApiParameter(
+ name="branch",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Git branch (the PR's head ref) to resolve. Open PRs are returned first, then most "
+ "recently updated.",
+ ),
+ OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Optional 'owner/name' repository to narrow matching to a single repo.",
+ ),
+ OpenApiParameter(
+ name="timestamp",
+ type=OpenApiTypes.DATETIME,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Optional ISO8601 timestamp, e.g. the trace's capture time. When a branch name has been "
+ "reused across PRs over time, the PR whose lifetime window contains this moment is ranked first so the "
+ "result matches the PR that was active when the trace was captured. A preference only, not a filter; "
+ "omit to rank purely by open state then recency.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: BranchPRMatchSerializer(many=True),
+ 400: OpenApiResponse(description="Branch missing/empty, or invalid repo/timestamp/source_id."),
+ },
+ description=(
+ "Resolve a git branch to the pull request(s) it belongs to — the cross-product link seam so another "
+ "product (the LLM analytics UI) can turn a git branch into a PR detail link. Matches the PR's head ref, "
+ "open PRs first then most recently updated. Pass `timestamp` (the trace's capture time) to prefer the PR "
+ "that was active at that moment when a branch name has been reused across PRs. `branch` is required. "
+ "Returns a possibly-empty, possibly-multi list — an empty list is a valid 200 (the caller renders a plain "
+ "chip)."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def resolve_branch(self, request: Request, **kwargs) -> Response:
+ try:
+ matches = api.resolve_branch(
+ team=self.team,
+ branch=request.query_params.get("branch") or None,
+ repo=request.query_params.get("repo") or None,
+ timestamp=_optional_datetime_param(request, "timestamp"),
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Provide a branch")
+ return Response(BranchPRMatchSerializer(instance=matches, many=True).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_pr_runs",
+ parameters=[
+ OpenApiParameter(
+ name="pr_number",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Pull request number whose runs to list.",
+ ),
+ OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="'owner/name' repository the pull request belongs to.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: WorkflowRunDetailSerializer(many=True),
+ 400: OpenApiResponse(description="Missing pr_number/repo, or invalid repo or source_id."),
+ },
+ description=(
+ "Every workflow run attributed to a pull request, across all its commits (grouped by head SHA "
+ "client-side), newest first. Run-level only."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def pr_runs(self, request: Request, **kwargs) -> Response:
+ repo = request.query_params.get("repo")
+ try:
+ pr_number = _require_int_param(request, "pr_number")
+ if not repo:
+ raise ValueError("repo is required")
+ runs = api.list_pr_runs(
+ team=self.team,
+ pr_number=pr_number,
+ repo=repo,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid repo or source_id")
+ return Response(WorkflowRunDetailSerializer(instance=runs, many=True).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_ci_failure_logs",
+ parameters=[
+ OpenApiParameter(
+ name="pr_number",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Pull request number whose CI failure logs to fetch.",
+ ),
+ OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="'owner/name' repository the pull request belongs to.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: CIFailureLogsSerializer,
+ 400: OpenApiResponse(description="Missing pr_number/repo, or invalid repo or source_id."),
+ },
+ description=(
+ "The thinned CI failure logs for a pull request, grouped by failed job. Resolves the PR to "
+ "its workflow runs via the pull_requests association (all of the PR's pushes, not just the "
+ "latest commit), then reads the Logs product joined on run_id. Returns failed jobs only (the "
+ "worker fetches logs for failures); logs_available is false when CI hasn't failed, the logs "
+ "aged out of the short Logs retention, or a fork PR has no run association. Each line carries "
+ "its original 1-based line number in the full pre-thinning log; lines are the failure region "
+ "(errors plus surrounding context, with omission markers), capped per job and overall."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def ci_failure_logs(self, request: Request, **kwargs) -> Response:
+ repo = request.query_params.get("repo")
+ try:
+ pr_number = _require_int_param(request, "pr_number")
+ if not repo:
+ raise ValueError("repo is required")
+ result = api.get_ci_failure_logs(
+ team=self.team,
+ pr_number=pr_number,
+ repo=repo,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid repo or source_id")
+ return Response(CIFailureLogsSerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_pr_cost",
+ parameters=[
+ OpenApiParameter(
+ name="pr_number",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Pull request number to estimate cost for.",
+ ),
+ OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="'owner/name' repository the pull request belongs to.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: PRCostSummarySerializer,
+ 400: OpenApiResponse(description="Missing pr_number/repo, or invalid repo or source_id."),
+ },
+ description=(
+ "Estimated CI cost for a pull request, summed over the jobs of all its workflow runs. "
+ "Billable self-hosted Linux runners only — provider-hosted (free GitHub-hosted) and non-Linux "
+ "jobs are excluded. Every figure is zero/null with `jobs_available` false when the job-level "
+ "source isn't synced yet. `llm_spend` carries the agent LLM token spend attributed to the PR "
+ "by git branch, or null when no `$ai_generation` event matched."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def pr_cost(self, request: Request, **kwargs) -> Response:
+ repo = request.query_params.get("repo")
+ try:
+ pr_number = _require_int_param(request, "pr_number")
+ if not repo:
+ raise ValueError("repo is required")
+ result = api.get_pr_cost(
+ team=self.team,
+ pr_number=pr_number,
+ repo=repo,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid repo or source_id")
+ return Response(PRCostSummarySerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_author_workflow_costs",
+ parameters=[
+ OpenApiParameter(
+ name="author",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="GitHub handle whose CI spend to break down.",
+ ),
+ _DATE_FROM,
+ _DATE_TO,
+ _SOURCE_ID,
+ _REPO,
+ ],
+ responses={
+ 200: WorkflowCostSerializer(many=True),
+ 400: OpenApiResponse(description="Missing author, or invalid date or source_id."),
+ },
+ description=(
+ "One author's estimated CI cost split by workflow over a window (date_from default -30d), "
+ "highest spend first. Runs are attributed to the author through their pull requests (attribution "
+ "is by PR number). Returns an empty list when the job-level source isn't synced."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def author_workflow_costs(self, request: Request, **kwargs) -> Response:
+ author = request.query_params.get("author")
+ if not author:
+ return Response({"detail": "author is required"}, status=status.HTTP_400_BAD_REQUEST)
+ try:
+ costs = api.list_author_workflow_costs(
+ team=self.team,
+ author=author,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid author, date, or source_id")
+ return Response(WorkflowCostSerializer(instance=costs, many=True).data)
diff --git a/products/engineering_analytics/backend/presentation/views/sources.py b/products/engineering_analytics/backend/presentation/views/sources.py
new file mode 100644
index 000000000000..af1e7bcf635d
--- /dev/null
+++ b/products/engineering_analytics/backend/presentation/views/sources.py
@@ -0,0 +1,28 @@
+"""The GitHub source/repo picker backing every other endpoint's scope."""
+
+from drf_spectacular.utils import extend_schema
+from rest_framework.decorators import action
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from products.engineering_analytics.backend.facade import api
+from products.engineering_analytics.backend.presentation.serializers import GitHubSourceSerializer
+from products.engineering_analytics.backend.presentation.views._base import EngineeringAnalyticsViewSetBase
+
+
+class SourcesMixin(EngineeringAnalyticsViewSetBase):
+ @extend_schema(
+ operation_id="engineering_analytics_sources",
+ responses={200: GitHubSourceSerializer(many=True)},
+ description=(
+ "The team's selectable GitHub repositories, oldest source first — one entry per repository a "
+ "source is configured to sync, so a source syncing several repositories appears once per repo. "
+ "Populate a repo picker from this and pass a chosen entry's `id` back as `source_id` and its "
+ "`repo` back as `repo` to the other endpoints. Includes repositories whose tables aren't fully "
+ "synced yet."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def sources(self, request: Request, **kwargs) -> Response:
+ result = api.list_github_sources(team=self.team, user_access_control=self.user_access_control)
+ return Response(GitHubSourceSerializer(instance=result, many=True).data)
diff --git a/products/engineering_analytics/backend/presentation/views/suite_health.py b/products/engineering_analytics/backend/presentation/views/suite_health.py
new file mode 100644
index 000000000000..9634b55faf96
--- /dev/null
+++ b/products/engineering_analytics/backend/presentation/views/suite_health.py
@@ -0,0 +1,197 @@
+"""Test-health reads plus the quarantine sidecar (the product's one write)."""
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
+from rest_framework import status
+from rest_framework.decorators import action
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.mixins import TypedRequest, validated_request
+
+from products.engineering_analytics.backend.facade import api
+from products.engineering_analytics.backend.facade.contracts import FLAKY_TEST_SIGNAL_CAVEAT, QuarantineRequest
+from products.engineering_analytics.backend.presentation.serializers import (
+ BrokenTestsResultSerializer,
+ FlakyTestListSerializer,
+ QuarantineFileSerializer,
+ QuarantineRequestResultSerializer,
+ QuarantineRequestSerializer,
+)
+from products.engineering_analytics.backend.presentation.views._base import (
+ _DATE_TO,
+ _REPO,
+ _SOURCE_ID,
+ EngineeringAnalyticsViewSetBase,
+ _bad_request,
+ _optional_int_param,
+)
+
+
+class TestHealthActionsMixin(EngineeringAnalyticsViewSetBase):
+ @extend_schema(
+ operation_id="engineering_analytics_flaky_tests",
+ parameters=[
+ OpenApiParameter(
+ name="date_from",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Window start: relative ('-7d', '-30d') or ISO8601. Defaults to -7d; the window "
+ "may span at most 30 days.",
+ ),
+ _DATE_TO,
+ OpenApiParameter(
+ name="min_rerun_passes",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="A test qualifies once it passed on retry at least this many times in the window "
+ "(OR-ed with min_failed_prs). Minimum 1. Defaults to 1.",
+ ),
+ OpenApiParameter(
+ name="min_failed_prs",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="A test qualifies once it failed on at least this many distinct pull requests in "
+ "the window (OR-ed with min_rerun_passes). Minimum 1. Defaults to 3.",
+ ),
+ OpenApiParameter(
+ name="limit",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Maximum number of tests to return (1-200). Defaults to 50.",
+ ),
+ _SOURCE_ID,
+ _REPO,
+ ],
+ responses={
+ 200: FlakyTestListSerializer,
+ 400: OpenApiResponse(
+ description="Invalid date, threshold, limit, or source_id, or a window longer than 30 days."
+ ),
+ },
+ description=(
+ "The flaky-test leaderboard: backend tests ranked by flakiness signal from the per-test CI spans, "
+ "over a window (default -7d, maximum 30 days). A test qualifies by passing on retry at least "
+ "min_rerun_passes times OR failing on at least min_failed_prs distinct PRs. " + FLAKY_TEST_SIGNAL_CAVEAT
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def flaky_tests(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.list_flaky_tests(
+ team=self.team,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ min_rerun_passes=_optional_int_param(request, "min_rerun_passes"),
+ min_failed_prs=_optional_int_param(request, "min_failed_prs"),
+ limit=_optional_int_param(request, "limit"),
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date, threshold, limit, or source_id")
+ return Response(FlakyTestListSerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_broken_tests",
+ parameters=[_SOURCE_ID, _REPO],
+ responses={
+ 200: BrokenTestsResultSerializer,
+ 400: OpenApiResponse(description="Invalid source_id."),
+ },
+ description=(
+ "The broken-tests triage panel: live CI failures over the last 2 days grouped into distinct "
+ "failures (by test id + normalized error signature) and classified by how each is behaving right "
+ "now — breaking trunk, a new failure spreading across branches, probably-resolved, flaky, or one "
+ "PR's own problem — ranked with the most urgent first. Also returns breaking_master_jobs, the "
+ "default-branch jobs whose latest run is red. Reach for this to answer 'what CI failures should I "
+ "care about right now'; expand a row's latest_run_id via run_failure_logs for the failing lines. "
+ "Fingerprinting is pytest-only for now (jest/playwright/cargo failures aren't grouped yet), and "
+ "the breaking/resolved distinction needs the job-level source synced — without it those failures "
+ "fall through to flaky/pr_only rather than being misreported."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def broken_tests(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_broken_tests(
+ team=self.team,
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid source_id")
+ return Response(BrokenTestsResultSerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_quarantine",
+ summary="Flaky-test quarantine file",
+ parameters=[
+ OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Optional 'owner/name' repository to read the quarantine file from. Defaults to the "
+ "connected GitHub source's most active repo over the last 30 days.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: QuarantineFileSerializer,
+ 400: OpenApiResponse(description="Invalid repo or source_id."),
+ },
+ description=(
+ "The repository's checked-in .test_quarantine.json: flaky tests temporarily quarantined with a hard "
+ "expiry, classified by urgency (overdue, in grace, expiring soon, active). `available` is false when "
+ "the repo has no quarantine file — that is not an error. Parsing is fail-open: malformed entries are "
+ "reported in parse_errors while well-formed ones are kept."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def quarantine(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_quarantine(
+ team=self.team,
+ repo=request.query_params.get("repo") or None,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid repo or source_id")
+ return Response(QuarantineFileSerializer(instance=result).data)
+
+ @validated_request(
+ request_serializer=QuarantineRequestSerializer,
+ operation_id="engineering_analytics_quarantine_request",
+ responses={
+ 201: OpenApiResponse(
+ response=QuarantineRequestResultSerializer,
+ description="The opened pull request, plus the tracking issue for a new quarantine.",
+ ),
+ 400: OpenApiResponse(
+ description="Invalid input, or the write could not be completed (no GitHub App installed on the "
+ "repo's org, a malformed quarantine file, or a GitHub failure). The detail message is safe to show."
+ ),
+ },
+ summary="Quarantine, extend, or unquarantine a flaky test",
+ description=(
+ "Opens a pull request that edits the repository's checked-in .test_quarantine.json — and, for a new "
+ "quarantine, a tracking issue the PR links but does not close. The file stays the source of truth that "
+ "CI enforces; this never bypasses it. A quarantine only affects CI runs that start after the PR merges."
+ ),
+ )
+ @action(detail=False, methods=["post"], url_path="quarantine/request", pagination_class=None)
+ def quarantine_request(self, request: TypedRequest[QuarantineRequest], **kwargs) -> Response:
+ result = api.request_quarantine(
+ team=self.team,
+ request=request.validated_data,
+ user_access_control=self.user_access_control,
+ )
+ return Response(QuarantineRequestResultSerializer(instance=result).data, status=status.HTTP_201_CREATED)
diff --git a/products/engineering_analytics/backend/presentation/views/teams.py b/products/engineering_analytics/backend/presentation/views/teams.py
new file mode 100644
index 000000000000..095d8cb8b006
--- /dev/null
+++ b/products/engineering_analytics/backend/presentation/views/teams.py
@@ -0,0 +1,205 @@
+"""Team-level rollups: CI health, activity, and merge trend."""
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
+from rest_framework.decorators import action
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from products.engineering_analytics.backend.facade import api
+from products.engineering_analytics.backend.facade.contracts import FLAKY_TEST_SIGNAL_CAVEAT
+from products.engineering_analytics.backend.presentation.serializers import (
+ TeamCIActivitySerializer,
+ TeamCIHealthListSerializer,
+ TeamMergeTrendSerializer,
+)
+from products.engineering_analytics.backend.presentation.views._base import (
+ _DATE_TO,
+ _SOURCE_ID,
+ EngineeringAnalyticsViewSetBase,
+ _bad_request,
+ _optional_int_param,
+)
+
+
+class TeamActionsMixin(EngineeringAnalyticsViewSetBase):
+ @extend_schema(
+ operation_id="engineering_analytics_team_ci_health",
+ parameters=[
+ OpenApiParameter(
+ name="date_from",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window "
+ "may span at most 30 days. An equal-length prior window is scanned for the *_prior twins; "
+ "near the 30-day ceiling that prior window can reach past Traces retention, deflating "
+ "*_prior counts and overstating deltas.",
+ ),
+ _DATE_TO,
+ OpenApiParameter(
+ name="min_rerun_passes",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="A test counts as flaky once it passed on retry at least this many times in the "
+ "window (OR-ed with min_failed_prs). Minimum 1. Defaults to 1.",
+ ),
+ OpenApiParameter(
+ name="min_failed_prs",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="A test counts as flaky once it failed on at least this many distinct pull "
+ "requests in the window (OR-ed with min_rerun_passes). Minimum 1. Defaults to 3.",
+ ),
+ OpenApiParameter(
+ name="limit",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Maximum number of teams to return (1-200). Defaults to 100.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: TeamCIHealthListSerializer,
+ 400: OpenApiResponse(
+ description="Invalid date, threshold, limit, or source_id, or a window longer than 30 days."
+ ),
+ },
+ description=(
+ "Per-owning-team rollup of the CI test surfaces each team owns: flaky-test count, failure and "
+ "pass-on-retry span counts, each with an equal-length previous-window twin for honest deltas. "
+ "Ownership is stamped on the spans at CI emission time from the repo's ownership map "
+ "(products/*/product.yaml + CODEOWNERS); unstamped spans aggregate under the literal team "
+ "'unowned'. Teams are organizational owners of code surfaces, never authors. " + FLAKY_TEST_SIGNAL_CAVEAT
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def team_ci_health(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.list_team_ci_health(
+ team=self.team,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ min_rerun_passes=_optional_int_param(request, "min_rerun_passes"),
+ min_failed_prs=_optional_int_param(request, "min_failed_prs"),
+ limit=_optional_int_param(request, "limit"),
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date, threshold, limit, or source_id")
+ return Response(TeamCIHealthListSerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_team_ci_activity",
+ parameters=[
+ OpenApiParameter(
+ name="owner_team",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Owning team slug to scope to (as returned by team_ci_health), e.g. 'team-replay', "
+ "or the literal 'unowned' for tests with no ownership stamp.",
+ ),
+ OpenApiParameter(
+ name="date_from",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window "
+ "may span at most 30 days. An equal-length prior window feeds the *_prior twins; near the "
+ "30-day ceiling that prior window can reach past Traces retention, deflating *_prior counts.",
+ ),
+ _DATE_TO,
+ OpenApiParameter(
+ name="test_limit",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Maximum number of per-test signal rows to return (1-100). Defaults to 25.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: TeamCIActivitySerializer,
+ 400: OpenApiResponse(
+ description="Missing owner_team, invalid date, test_limit, or source_id, or a window longer "
+ "than 30 days."
+ ),
+ },
+ description=(
+ "One owning team's CI test activity: per-test current-vs-prior signal pairs (the before/after "
+ "comparison) over the window and its equal-length prior twin. Signal = failed + error + "
+ "pass-on-retry spans on the team's owned tests. " + FLAKY_TEST_SIGNAL_CAVEAT
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def team_ci_activity(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_team_ci_activity(
+ team=self.team,
+ owner_team=request.query_params.get("owner_team") or "",
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ test_limit=_optional_int_param(request, "test_limit"),
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid owner_team, date, test_limit, or source_id")
+ return Response(TeamCIActivitySerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_team_merge_trend",
+ parameters=[
+ OpenApiParameter(
+ name="owner_team",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Team slug to scope to (as returned by team_ci_health), matched against the "
+ "GitHub org team slug of the source's team_members snapshot. The literal 'unowned' names "
+ "an ownership gap, not an org team, and has no merge trend.",
+ ),
+ OpenApiParameter(
+ name="date_from",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Window start: relative ('-14d', '-7d') or ISO8601. Defaults to -14d; the window "
+ "may span at most 30 days.",
+ ),
+ _DATE_TO,
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: TeamMergeTrendSerializer,
+ 400: OpenApiResponse(
+ description="Missing owner_team, invalid date or source_id, or a window longer than 30 days."
+ ),
+ },
+ description=(
+ "One team's daily time-to-merge trend: the median and average open→merge seconds over the PRs "
+ "the team's members merged each day (PR author login → GitHub org team membership). Team-level "
+ "aggregates only, never per-member figures or cross-team rankings. Timing is the coarse "
+ "open→merge (draft + review time combined); bots are excluded. Requires the GitHub source's "
+ "team_members snapshot; has_membership_data is false without it."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def team_merge_trend(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_team_merge_trend(
+ team=self.team,
+ owner_team=request.query_params.get("owner_team") or "",
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid owner_team, date, or source_id")
+ return Response(TeamMergeTrendSerializer(instance=result).data)
diff --git a/products/engineering_analytics/backend/presentation/views/workflows.py b/products/engineering_analytics/backend/presentation/views/workflows.py
new file mode 100644
index 000000000000..03f7be18d83c
--- /dev/null
+++ b/products/engineering_analytics/backend/presentation/views/workflows.py
@@ -0,0 +1,557 @@
+"""Workflow/run/job-scoped reads: health, activity, jobs, costs, and master state."""
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
+from rest_framework import status
+from rest_framework.decorators import action
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from products.engineering_analytics.backend.facade import api
+from products.engineering_analytics.backend.presentation.serializers import (
+ CurrentBranchHealthSerializer,
+ MasterFailureGroupSerializer,
+ RepoOverviewSerializer,
+ RunFailureLogsSerializer,
+ WorkflowHealthItemSerializer,
+ WorkflowJobAggregateSerializer,
+ WorkflowJobSerializer,
+ WorkflowRunActivitySerializer,
+ WorkflowRunDetailSerializer,
+ WorkflowRunnerCostSerializer,
+)
+from products.engineering_analytics.backend.presentation.views._base import (
+ _BRANCH,
+ _DATE_FROM,
+ _DATE_TO,
+ _REPO,
+ _RUN_SCOPE,
+ _SOURCE_ID,
+ _WORKFLOW_DATE_FROM,
+ EngineeringAnalyticsViewSetBase,
+ _bad_request,
+ _bool_param,
+ _optional_int_param,
+ _require_int_param,
+)
+
+
+class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):
+ @extend_schema(
+ operation_id="engineering_analytics_workflow_health",
+ parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _RUN_SCOPE, _SOURCE_ID, _REPO],
+ responses={
+ 200: WorkflowHealthItemSerializer(many=True),
+ 400: OpenApiResponse(
+ description="Invalid date_from, date_to, run_scope, or source_id, or a window longer than 366 days."
+ ),
+ },
+ description=(
+ "Per-workflow CI health over a window (default last 24 hours, maximum 366 days): run count, success "
+ "rate, p50/p95 duration, last failure time, latest-run status, and a zero-filled run history bucketed "
+ "by hour/day/week to fit the window. p50/p95 are over successful runs only, so cancelled (superseded) "
+ "and failed runs never bias the duration trend. Optionally scope to a single git branch via `branch`, "
+ "or to attributed pull-request runs via `run_scope=pull_request`. Use this for 'is CI getting slower' "
+ "and 'which workflow is the long pole'; compare two windows to get a trend."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def workflow_health(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.list_workflow_health(
+ team=self.team,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ branch=request.query_params.get("branch") or None,
+ run_scope=request.query_params.get("run_scope") or None,
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date_from, date_to, or source_id")
+ return Response(WorkflowHealthItemSerializer(instance=result, many=True).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_workflow_run",
+ parameters=[
+ OpenApiParameter(
+ name="run_id",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="GitHub Actions run id to inspect.",
+ ),
+ _SOURCE_ID,
+ _REPO,
+ ],
+ responses={
+ 200: WorkflowRunDetailSerializer,
+ 400: OpenApiResponse(description="Missing or non-integer run_id, or invalid source_id."),
+ 404: OpenApiResponse(description="No workflow run with that id in the warehouse."),
+ },
+ description=(
+ "A single workflow run: status, conclusion, duration, branch, attempt, and the attributed pull "
+ "request. Run-level only — per-job and per-step detail are not tracked yet."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def workflow_run(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_workflow_run(
+ team=self.team,
+ run_id=_require_int_param(request, "run_id"),
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid source_id")
+ if result is None:
+ return Response({"detail": "Workflow run not found"}, status=status.HTTP_404_NOT_FOUND)
+ return Response(WorkflowRunDetailSerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_workflow_runs",
+ parameters=[
+ OpenApiParameter(
+ name="workflow_name",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Workflow name to list runs for.",
+ ),
+ OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="'owner/name' repository the workflow belongs to.",
+ ),
+ _DATE_FROM,
+ _DATE_TO,
+ _BRANCH,
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: WorkflowRunDetailSerializer(many=True),
+ 400: OpenApiResponse(description="Missing workflow_name/repo, or invalid date or source_id."),
+ },
+ description=(
+ "Runs of a single workflow within a repo over a window (date_from default -30d), newest first. "
+ "Optionally scope to a single git branch via `branch`. Each row is run-level — per-job and "
+ "per-step detail are not tracked yet. Use this as the GitHub 'workflow' page between the "
+ "workflow list and a single run."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def workflow_runs(self, request: Request, **kwargs) -> Response:
+ workflow_name = request.query_params.get("workflow_name")
+ repo = request.query_params.get("repo")
+ if not workflow_name or not repo:
+ return Response({"detail": "workflow_name and repo are required"}, status=status.HTTP_400_BAD_REQUEST)
+
+ try:
+ runs = api.list_workflow_runs(
+ team=self.team,
+ repo=repo,
+ workflow_name=workflow_name,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ branch=request.query_params.get("branch") or None,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date, repo, or source_id")
+ return Response(WorkflowRunDetailSerializer(instance=runs, many=True).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_workflow_run_activity",
+ parameters=[
+ OpenApiParameter(
+ name="workflow_name",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Workflow name to load run activity for.",
+ ),
+ OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="'owner/name' repository the workflow belongs to.",
+ ),
+ _DATE_FROM,
+ _DATE_TO,
+ _BRANCH,
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: WorkflowRunActivitySerializer,
+ 400: OpenApiResponse(description="Missing workflow_name/repo, or invalid date or source_id."),
+ },
+ description=(
+ "Compact per-run points for a single workflow over a window (date_from default -30d), newest first, for "
+ "the run-activity chart: each run's start time, duration, conclusion, branch, and attributed PR. "
+ "Optionally scope to a single git branch via `branch`, matching workflow_runs. Leaner and higher-capped "
+ "than workflow_runs so the chart spans the full window even on busy workflows; `truncated` is true when "
+ "the cap is hit, so the chart covers only the most recent runs."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def workflow_run_activity(self, request: Request, **kwargs) -> Response:
+ workflow_name = request.query_params.get("workflow_name")
+ repo = request.query_params.get("repo")
+ if not workflow_name or not repo:
+ return Response({"detail": "workflow_name and repo are required"}, status=status.HTTP_400_BAD_REQUEST)
+ try:
+ result = api.get_workflow_run_activity(
+ team=self.team,
+ repo=repo,
+ workflow_name=workflow_name,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ branch=request.query_params.get("branch") or None,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date, repo, or source_id")
+ return Response(WorkflowRunActivitySerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_workflow_runner_costs",
+ parameters=[
+ OpenApiParameter(
+ name="workflow_name",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Workflow name to break down cost for.",
+ ),
+ OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="'owner/name' repository the workflow belongs to.",
+ ),
+ _DATE_FROM,
+ _DATE_TO,
+ _BRANCH,
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: WorkflowRunnerCostSerializer(many=True),
+ 400: OpenApiResponse(description="Missing workflow_name/repo, or invalid date or source_id."),
+ },
+ description=(
+ "A workflow's estimated CI cost broken down by runner tier over a window (date_from default "
+ "-30d), highest spend first. Optionally scope to a single git branch via `branch`. Returns an "
+ "empty list when the job-level source isn't synced."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def workflow_runner_costs(self, request: Request, **kwargs) -> Response:
+ workflow_name = request.query_params.get("workflow_name")
+ repo = request.query_params.get("repo")
+ if not workflow_name or not repo:
+ return Response({"detail": "workflow_name and repo are required"}, status=status.HTTP_400_BAD_REQUEST)
+ try:
+ costs = api.get_workflow_runner_costs(
+ team=self.team,
+ repo=repo,
+ workflow_name=workflow_name,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ branch=request.query_params.get("branch") or None,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date, repo, or source_id")
+ return Response(WorkflowRunnerCostSerializer(instance=costs, many=True).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_workflow_jobs",
+ parameters=[
+ OpenApiParameter(
+ name="run_id",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Workflow run id to list jobs for.",
+ ),
+ OpenApiParameter(
+ name="run_attempt",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Which re-run attempt to scope jobs to. Omit to use the run's latest attempt; pass an "
+ "explicit attempt to avoid mixing jobs across a re-run's attempts.",
+ ),
+ _SOURCE_ID,
+ _REPO,
+ ],
+ responses={
+ 200: WorkflowJobSerializer(many=True),
+ 400: OpenApiResponse(description="Missing or non-integer run_id/run_attempt, or invalid source_id."),
+ },
+ description=(
+ "Jobs of a single workflow run attempt, with per-job duration, runner tier, and estimated cost. "
+ "Scoped to one run_attempt (the latest unless specified) so a re-run's attempts don't merge. "
+ "Returns an empty list when the job-level source isn't synced yet."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def workflow_jobs(self, request: Request, **kwargs) -> Response:
+ try:
+ jobs = api.list_workflow_jobs(
+ team=self.team,
+ run_id=_require_int_param(request, "run_id"),
+ run_attempt=_optional_int_param(request, "run_attempt"),
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid source_id")
+ return Response(WorkflowJobSerializer(instance=jobs, many=True).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_repo_overview",
+ parameters=[
+ _DATE_FROM,
+ _DATE_TO,
+ OpenApiParameter(
+ name="include_series",
+ type=OpenApiTypes.BOOL,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Set false to skip the chart series (cost_series, time_to_green_series, "
+ "success_rate_series, open_to_merge_series return empty) and their query cost — for "
+ "headline-only consumers like the weekly digest. Defaults to true.",
+ ),
+ _SOURCE_ID,
+ _REPO,
+ ],
+ responses={
+ 200: RepoOverviewSerializer,
+ 400: OpenApiResponse(description="Invalid date_from, date_to, or source_id, or a window over 366 days."),
+ },
+ description=(
+ "Repo-level headline aggregates over a window (default -30d): run count, success rate, re-run "
+ "cycles, merged-PR count (bots included), median PR open-to-merge (bots and drafts excluded; "
+ "coarse — draft and ready time fused), and billable minutes + estimated cost — each with its "
+ "equal-length previous-window twin so a caller can render honest deltas. Also carries the "
+ "detected default branch and its completed-run history series (skippable via include_series=false). "
+ "Cost figures are null until the job-level source is synced."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def repo_overview(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_repo_overview(
+ team=self.team,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ include_series=_bool_param(request, "include_series", default=True),
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date_from, date_to, include_series, or source_id")
+ return Response(RepoOverviewSerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_current_branch_health",
+ parameters=[_SOURCE_ID, _REPO],
+ responses={
+ 200: CurrentBranchHealthSerializer,
+ 400: OpenApiResponse(description="Invalid source_id."),
+ },
+ description=(
+ "Current default-branch CI verdict over the fixed last-24-hours window. Counts every workflow whose "
+ "latest completed run failed or timed out; failing workflow names are a bounded preview. The default "
+ "branch is detected from the same window, independently of analytics date filters."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def current_branch_health(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_current_branch_health(
+ team=self.team,
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid source_id")
+ return Response(CurrentBranchHealthSerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_repo_run_activity",
+ parameters=[
+ _DATE_FROM,
+ _DATE_TO,
+ # This endpoint never aggregates across branches, so the shared _BRANCH "omit to aggregate"
+ # wording would misdescribe the omit behavior in every generated client.
+ OpenApiParameter(
+ name="branch",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Optional exact git branch (head_branch) to chart, e.g. 'main'. "
+ "Omit or leave blank to use the repo's detected default branch.",
+ ),
+ _SOURCE_ID,
+ _REPO,
+ ],
+ responses={
+ 200: WorkflowRunActivitySerializer,
+ 400: OpenApiResponse(description="Invalid date_from, date_to, or source_id, or a window over 366 days."),
+ },
+ description=(
+ "Default-branch health as compact chart points over a window (default -30d), newest first, for the "
+ "repo-hub run-activity chart. All of a commit's workflow runs are collapsed into ONE point per commit "
+ "(head SHA): its earliest workflow start, wall-clock duration until the last workflow settled (null "
+ "while any is still running), and an overall conclusion that is 'failure' if any workflow decisively "
+ "failed, else 'success' when at least one passed, else 'neutral'. `branch` overrides the detected "
+ "default branch. `truncated` is true when more commits matched than the cap, so the chart covers only "
+ "the most recent commits."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def repo_run_activity(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_repo_run_activity(
+ team=self.team,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ branch=request.query_params.get("branch") or None,
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date_from, date_to, or source_id")
+ return Response(WorkflowRunActivitySerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_master_failures",
+ parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _SOURCE_ID, _REPO],
+ responses={
+ 200: MasterFailureGroupSerializer(many=True),
+ 400: OpenApiResponse(description="Invalid date_from, date_to, or source_id, or a window over 366 days."),
+ },
+ description=(
+ "Default-branch failures over a window (default -24h), grouped error-tracking style by "
+ "(workflow, de-sharded failing job) with a run count and first/last seen, newest group first. "
+ "`branch` overrides the detected default branch. PR-branch failures are deliberately excluded — "
+ "at monorepo volume a flat feed is a firehose; those surface per PR. Groups degrade to workflow "
+ "level (failed_job '') when the job-level source isn't synced."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def master_failures(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.list_master_failures(
+ team=self.team,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ branch=request.query_params.get("branch") or None,
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date_from, date_to, or source_id")
+ return Response(MasterFailureGroupSerializer(instance=result, many=True).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_run_failure_logs",
+ parameters=[
+ OpenApiParameter(
+ name="run_id",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Workflow run id whose failure logs to fetch.",
+ ),
+ _SOURCE_ID,
+ _REPO,
+ ],
+ responses={
+ 200: RunFailureLogsSerializer,
+ 400: OpenApiResponse(description="Missing or non-integer run_id, or invalid source_id."),
+ },
+ description=(
+ "The thinned CI failure logs of one workflow run, grouped by failed job — the run-scoped twin of "
+ "ci_failure_logs for surfaces that aren't PR-scoped (default-branch failures, the run page). "
+ "logs_available is false when the run didn't fail or its logs aged out of the short Logs retention."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def run_failure_logs(self, request: Request, **kwargs) -> Response:
+ try:
+ result = api.get_run_failure_logs(
+ team=self.team,
+ run_id=_require_int_param(request, "run_id"),
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid source_id")
+ return Response(RunFailureLogsSerializer(instance=result).data)
+
+ @extend_schema(
+ operation_id="engineering_analytics_job_aggregates",
+ parameters=[
+ OpenApiParameter(
+ name="workflow_name",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Workflow name to aggregate jobs for.",
+ ),
+ _DATE_FROM,
+ _DATE_TO,
+ _BRANCH,
+ _SOURCE_ID,
+ _REPO,
+ ],
+ responses={
+ 200: WorkflowJobAggregateSerializer(many=True),
+ 400: OpenApiResponse(description="Missing workflow_name, or invalid date or source_id."),
+ },
+ description=(
+ "Per-job aggregates for one workflow over a window (default -30d), one row per de-sharded job "
+ "name (matrix shards aggregate together), busiest first: queue p50, duration p50/p95, failure "
+ "rate, retry pressure, run share (below 1.0 = conditional job), and billable cost. Jobs always "
+ "need their run as context — this is the aggregate view; use workflow_jobs for one run's jobs. "
+ "Empty when the job-level source isn't synced."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def job_aggregates(self, request: Request, **kwargs) -> Response:
+ workflow_name = request.query_params.get("workflow_name")
+ if not workflow_name:
+ return Response({"detail": "workflow_name is required"}, status=status.HTTP_400_BAD_REQUEST)
+ try:
+ result = api.list_job_aggregates(
+ team=self.team,
+ workflow_name=workflow_name,
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ branch=request.query_params.get("branch") or None,
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date, workflow_name, or source_id")
+ return Response(WorkflowJobAggregateSerializer(instance=result, many=True).data)
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 1f3ffe3aff25..4b05d2685cc0 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -3,13 +3,29 @@ from datetime import UTC, datetime
from posthog.test.base import APIBaseTest
from unittest import mock
+from django.test import SimpleTestCase
+
from parameterized import parameterized
from rest_framework import status
from products.engineering_analytics.backend.facade import contracts
+from products.engineering_analytics.backend.presentation.views import EngineeringAnalyticsViewSet
from products.engineering_analytics.backend.tests.test_views import connect_github_source_without_data
-_VIEWS = "products.engineering_analytics.backend.presentation.views.api"
+
+class TestScopeEnrollment(SimpleTestCase):
+ def test_every_action_is_enrolled_in_a_scope_list(self) -> None:
+ actions = {a.__name__ for a in EngineeringAnalyticsViewSet.get_extra_actions()}
+ enrolled = set(EngineeringAnalyticsViewSet.scope_object_read_actions) | set(
+ EngineeringAnalyticsViewSet.scope_object_write_actions
+ )
+ assert actions == enrolled, (
+ f"unenrolled actions (personal API keys get 403): {sorted(actions - enrolled)}; "
+ f"stale scope entries: {sorted(enrolled - actions)}"
+ )
+
+
+_VIEWS = "products.engineering_analytics.backend.facade.api"
def _pr_lifecycle() -> contracts.PRLifecycle:
diff --git a/products/engineering_analytics/backend/tests/test_quarantine.py b/products/engineering_analytics/backend/tests/test_quarantine.py
index f547477b07f2..e56fe7eea551 100644
--- a/products/engineering_analytics/backend/tests/test_quarantine.py
+++ b/products/engineering_analytics/backend/tests/test_quarantine.py
@@ -34,7 +34,7 @@ _TODAY = date(2026, 6, 12)
_REQUESTS_GET = "products.engineering_analytics.backend.logic.quarantine.requests.get"
_MAX_BYTES = "products.engineering_analytics.backend.logic.quarantine._MAX_QUARANTINE_BYTES"
_FOR_TEAM = "products.engineering_analytics.backend.logic.queries._curated.CuratedGitHubSource.for_team"
-_VIEWS = "products.engineering_analytics.backend.presentation.views.api"
+_VIEWS = "products.engineering_analytics.backend.facade.api"
_Q = "products.engineering_analytics.backend.logic.quarantine"
# The exact bytes core.render (and therefore `hogli test:quarantine add`) writes for one