:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(eng-analytics): read cache outcomes from job logs (#111995)
Raúl Negrón-Otero0d2d8a8bed4f
diff --git a/posthog/egress/github/README.md b/posthog/egress/github/README.mdindex c66c3d3ff1e5..d9a3291005f4 100644--- a/posthog/egress/github/README.md+++ b/posthog/egress/github/README.md@@ -28,6 +28,7 @@ A shed sweep stops for the cycle and resumes on the next scheduled run.A caller that walks pages, such as the warehouse source, paces with `github_installation_pace_seconds` instead of getting denied.The warehouse source's page fetches run on `BATCH`, while its repository validation and webhook management run on `NORMAL`, because a person waits on them. Customer Analytics feature-request link and resume lookups also run on `NORMAL` because an editor waits for the current issue state. Signals refreshes the stored pull request review decision from GitHub webhooks on `BATCH`; the inbox can keep the last known value when the lane is shed and update it after a retry.The ownership file reader (`posthog/ownership/`, source `ownership_github_api`) runs on `NORMAL` where a person waits for a board or a snapshot list, and on `BATCH` for the scheduled digests and report generation. Its GraphQL reads charge `core`, as every GraphQL call does, and so does the one compare call per new head commit that lets it reuse cached files.+Engineering analytics downloads one job's log (source `job_logs`) on `NORMAL` when a person opens that job in the CI explorer, and on `BATCH` in the scheduled failed-job log collection.Stamphog reads the author-familiarity blame and history (GraphQL) and the pull request's commit messages on `BATCH`, because both signals are advisory: a shed call leaves them out of that review.Its merge base read (compare) stays on the default lane, because the review checkout needs it.The Tasks infrastructure admin reads the sandbox version pin and recent image build runs on `NORMAL`, using a regional cache. When the GitHub App is configured, it discovers the `PostHog/posthog` installation and mints an ephemeral token restricted to that repository with Contents and Actions read permissions. Calls share the installation budget. Deployments without App credentials retain the shared-token behavior.diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex 6777d5c7de9a..c085a5de5368 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -30,10 +30,13 @@ from products.engineering_analytics.backend.facade.contracts import (BranchPRMatch,BrokenTestsResult,CICardSummary,+ CIDataFreshness,CIEngine,CIFailureLogs,CISignalsConfig,CITestRunner,+ CITimingContext,+ CITimingKind,CurrentBranchHealth,DeliveryComparison,DeliverySummary,@@ -41,6 +44,7 @@ from products.engineering_analytics.backend.facade.contracts import (FlakyTestList,GitHubSource,GitHubTeamRoster,+ JobLogInsights,MasterFailureGroup,MergedPullRequest,PRCostSummary,@@ -67,6 +71,7 @@ from products.engineering_analytics.backend.facade.contracts import ()if TYPE_CHECKING:+ from collections.abc import Sequencefrom datetime import datetimefrom products.access_control.backend.facade.user_access_control import UserAccessControl@@ -422,6 +427,59 @@ def list_workflow_jobs()+def get_job_log_insights(+ *,+ team: Team,+ repo: str,+ run_id: int,+ job_id: int,+ ci_engine: CIEngine | None = None,+ source_id: str | None = None,+ user_access_control: "UserAccessControl | None" = None,+) -> JobLogInsights:+ return logic.build_job_log_insights(+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),+ run_id=run_id,+ job_id=job_id,+ ci_engine=ci_engine,+ )+++def get_ci_data_freshness(+ *,+ team: Team,+ repo: str,+ source_id: str | None = None,+ user_access_control: "UserAccessControl | None" = None,+) -> CIDataFreshness:+ return logic.build_ci_data_freshness(curated=_authorized_source(team, source_id, user_access_control, repo=repo))+++def get_ci_timing_context(+ *,+ team: Team,+ repo: str,+ ci_engine: CIEngine,+ run_id: int,+ run_attempt: int,+ kind: CITimingKind,+ job_ids: "Sequence[int]" = (),+ step_number: int | None = None,+ source_id: str | None = None,+ user_access_control: "UserAccessControl | None" = None,+) -> CITimingContext:+ return logic.build_ci_timing_context(+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),+ repo=repo,+ ci_engine=ci_engine,+ run_id=run_id,+ run_attempt=run_attempt,+ kind=kind,+ job_ids=job_ids,+ step_number=step_number,+ )++def get_ci_cards(*,team: Team,diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex ada987e9322a..73b03f85bc43 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -395,6 +395,11 @@ class WorkflowRunDetail:ci_engine: CIEngine | None = Nonenative_run_id: str | None = Nonenative_workflow_run_id: str | None = None+ # GitHub's numeric workflow id, which a rename of the workflow keeps. None for a Depot CI run and+ # for a run whose source table does not carry the id.+ workflow_id: int | None = None+ # The event that triggered the run ('push', 'pull_request', 'schedule', ...). None when unknown.+ event: str | None = None@dataclass(frozen=True)@@ -482,6 +487,138 @@ class WorkflowJob:steps: list[WorkflowJobStep] = field(default_factory=list)+class JobLogBadgeKind(LabeledStrEnum):+ CACHE = "cache", "Cache"+ MIGRATIONS = "migrations", "Migrations"+++class JobLogBadgeState(LabeledStrEnum):+ HIT = "hit", "Cache hit"+ PARTIAL = "partial", "Older cache"+ MISS = "miss", "Cache miss"+ FAILED = "failed", "Cache restore failed"+ NONE = "none", "No migrations"+ APPLIED = "applied", "Migrations applied"+++@dataclass(frozen=True)+class JobLogBadge:+ """One thing a job's log says happened, with how often. ``detail`` names each occurrence+ (a cache key, a migration), capped, and may hold fewer entries than ``count``."""++ kind: JobLogBadgeKind+ state: JobLogBadgeState+ count: int+ detail: list[str]+++@dataclass(frozen=True)+class JobStepLogBadges:+ number: int+ badges: list[JobLogBadge]+++@dataclass(frozen=True)+class JobLogInsights:+ """What one job's log says it did with caches and migrations.++ ``log_read`` is False when there is no log to read: a Depot CI job, an unknown job, or a failed+ fetch. ``attributed_to_steps`` is False when the log's step markers did not match the job's steps,+ and then ``steps`` is empty and ``job`` alone carries the badges. ``log_truncated`` is True when+ only part of the log was parsed, so an outcome in the missing part is not reported.+ """++ log_read: bool+ attributed_to_steps: bool+ job: list[JobLogBadge]+ steps: list[JobStepLogBadges]+ log_truncated: bool = False+++@dataclass(frozen=True)+class CIDataFreshness:+ """When the stored CI data was last synced from its source.++ Each time is when the last completed sync of the table started, so every stored row is at least+ that fresh. For a repository that also syncs Depot CI, it is the older of the GitHub and the Depot+ time. None when a table never synced, or when the jobs table is not synced at all.+ """++ runs_synced_at: datetime | None+ jobs_synced_at: datetime | None+++# A matrix selection names its jobs one by one, and the largest matrices hold fewer jobs than this.+CI_TIMING_MAX_JOB_IDS = 200+++class CITimingKind(LabeledStrEnum):+ WORKFLOW = "workflow", "Workflow"+ MATRIX = "matrix", "Matrix"+ JOB = "job", "Job"+ STEP = "step", "Step"+++class CITimingIdentity(LabeledStrEnum):+ WORKFLOW_ID = "workflow_id", "Workflow id"+ WORKFLOW_NAME = "workflow_name", "Workflow name"+++class CITimingSampleStatus(LabeledStrEnum):+ SUCCESS = "success", "Success"+ FAILURE = "failure", "Failure"+++class CITimingUnavailableReason(LabeledStrEnum):+ DEFAULT_BRANCH_UNKNOWN = "default_branch_unknown", "Default branch unknown"+ JOBS_NOT_SYNCED = "jobs_not_synced", "Jobs not synced"+ NOT_EXECUTED = "not_executed", "Not executed"+++@dataclass(frozen=True)+class CITimingSample:+ """One default-branch run that ran the same work as the selection, and how long that work took."""++ run_id: int+ run_attempt: int+ # None for a workflow or matrix selection, which spans several jobs.+ job_id: int | None+ # None unless the selection is a step. Steps match by name, so this can differ from the selected number.+ step_number: int | None+ ci_engine: CIEngine+ native_run_id: str | None+ native_workflow_run_id: str | None+ native_job_id: str | None+ native_attempt_id: str | None+ status: CITimingSampleStatus+ duration_seconds: float+ completed_at: datetime+ head_sha: str+++@dataclass(frozen=True)+class CITimingContext:+ """How long a selected workflow, matrix, job or step took on the default branch in the last days.++ ``sample_count`` and ``average_seconds`` cover the successful samples only. ``recent`` holds the+ newest matched samples of any status. No sample is ever taken from a different workflow, job or+ runner, so sparse history reads as a null average and never as a looser comparison.+ """++ default_branch: str | None+ window_days: int+ identity: CITimingIdentity+ runs_scanned: int+ # True when more eligible runs existed in the window than were scanned.+ sampled: bool+ sample_count: int+ average_seconds: float | None+ recent: list[CITimingSample]+ runs_synced_at: datetime | None+ jobs_synced_at: datetime | None+ unavailable_reason: CITimingUnavailableReason | None++@dataclass(frozen=True)class WorkflowRunnerCost:"""One runner tier's share of a workflow's CI spend — for the single-workflow "where the spenddiff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.pyindex 5de342e7ed0b..535bbc1786a9 100644--- a/products/engineering_analytics/backend/logic/__init__.py+++ b/products/engineering_analytics/backend/logic/__init__.py@@ -18,6 +18,9 @@ from products.engineering_analytics.backend.logic.ci_signals_config import (get_ci_signals_config as get_ci_signals_config,update_ci_signals_config as update_ci_signals_config,)+from products.engineering_analytics.backend.logic.ci_timing_context import (+ build_ci_timing_context as build_ci_timing_context,+)from products.engineering_analytics.backend.logic.delivery import (build_delivery_comparison as build_delivery_comparison,build_delivery_summary as build_delivery_summary,@@ -36,6 +39,9 @@ from products.engineering_analytics.backend.logic.friction import (from products.engineering_analytics.backend.logic.github_teams import (build_github_team_roster as build_github_team_roster,)+from products.engineering_analytics.backend.logic.job_log_insights import (+ build_job_log_insights as build_job_log_insights,+)from products.engineering_analytics.backend.logic.pull_requests import (build_attention_pull_requests as build_attention_pull_requests,build_author_workflow_costs as build_author_workflow_costs,@@ -65,6 +71,7 @@ from products.engineering_analytics.backend.logic.teams import (build_team_merge_trend as build_team_merge_trend,)from products.engineering_analytics.backend.logic.workflows import (+ build_ci_data_freshness as build_ci_data_freshness,build_current_branch_health as build_current_branch_health,build_job_aggregates as build_job_aggregates,build_master_failures as build_master_failures,diff --git a/products/engineering_analytics/backend/logic/ci_timing_context.py b/products/engineering_analytics/backend/logic/ci_timing_context.pynew file mode 100644index 000000000000..63fde30129bb--- /dev/null+++ b/products/engineering_analytics/backend/logic/ci_timing_context.py@@ -0,0 +1,345 @@+"""Compare a selected workflow, matrix, job or step with the same work on the default branch.++The comparison reads stored runs and jobs only. A default-branch run gives a sample only when it ran+the same jobs on the same runners as the selection, so a sample is never taken from a different+workflow, job or runner. Sparse history therefore yields few samples or none, not a looser match.+"""++import hashlib+from collections import Counter+from collections.abc import Sequence+from dataclasses import asdict+from datetime import UTC, datetime, timedelta+from statistics import mean++from django.core.cache import cache++import structlog++from posthog.dataclasses import frozen++from products.engineering_analytics.backend.facade.contracts import (+ CI_TIMING_MAX_JOB_IDS,+ CIDataFreshness,+ CIEngine,+ CITimingContext,+ CITimingIdentity,+ CITimingKind,+ CITimingSample,+ CITimingSampleStatus,+ CITimingUnavailableReason,+ RepoRef,+ WorkflowJob,+)+from products.engineering_analytics.backend.logic._shared import _require_repo+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource+from products.engineering_analytics.backend.logic.queries.default_branches import query_default_branches+from products.engineering_analytics.backend.logic.queries.timing_candidates import (+ TimingCandidateRun,+ query_timing_candidates,+)+from products.engineering_analytics.backend.logic.queries.workflow_jobs import query_jobs_by_run, query_workflow_jobs+from products.engineering_analytics.backend.logic.queries.workflow_run import query_workflow_run++logger = structlog.get_logger(__name__)++WINDOW_DAYS = 7+_RECENT_SAMPLES = 3+# The answer changes only when a new default-branch run syncs, and a person can open the same+# selection many times in a row.+_CACHE_SECONDS = 5 * 60+# A repository's default branch almost never changes, and reading it scans the pull request snapshot.+_DEFAULT_BRANCH_CACHE_SECONDS = 60 * 60+# Part of the cache key. Raise it when the matching rules or the cached shape change.+_CACHE_VERSION = 1++# A skipped or neutral job did no work, so it is not part of the workload that a run executed.+_NOT_EXECUTED_CONCLUSIONS = frozenset({"skipped", "neutral"})+# A cancelled job stopped early, so its duration says nothing about how long the work takes.+_NOT_SAMPLED_CONCLUSIONS = _NOT_EXECUTED_CONCLUSIONS | {"cancelled"}+_STEP_VERDICTS = frozenset({"success", "failure", "timed_out"})+_SPANS_JOBS = frozenset({CITimingKind.WORKFLOW, CITimingKind.MATRIX})+++@frozen+class _JobSignature:+ """What makes two jobs the same work: the job name and the runner tier it ran on."""++ name: str+ runner_label: str+++@frozen+class TimingSelection:+ kind: CITimingKind+ # Every job the current run attempt executed. A workflow or matrix sample must repeat this set.+ executed: list[WorkflowJob]+ selected: list[WorkflowJob]+ # Set for a step selection only. Steps match by name, because a workflow edit renumbers them.+ step_name: str | None = None+++def select_timing_jobs(+ jobs: Sequence[WorkflowJob], *, kind: CITimingKind, job_ids: Sequence[int], step_number: int | None+) -> TimingSelection | None:+ """The selection among one run attempt's ``jobs``, or None when none of the selected jobs ran.+ Raises ValueError when a job id is not in the attempt, when a job or step selection does not name+ exactly one job, or when the job has no such step."""+ if kind is CITimingKind.WORKFLOW:+ named = list(jobs)+ else:+ jobs_by_id = {job.id: job for job in jobs}+ wanted_ids = sorted(set(job_ids))+ if not wanted_ids or any(job_id not in jobs_by_id for job_id in wanted_ids):+ raise ValueError("Every job id must be a job of this run attempt.")+ if kind not in _SPANS_JOBS and len(wanted_ids) != 1:+ raise ValueError("A job or step comparison needs exactly one job id.")+ named = [jobs_by_id[job_id] for job_id in wanted_ids]+ executed = [job for job in jobs if job.conclusion not in _NOT_EXECUTED_CONCLUSIONS]+ selected = [job for job in named if job.conclusion not in _NOT_EXECUTED_CONCLUSIONS]+ if not selected:+ return None+ if kind is not CITimingKind.STEP:+ return TimingSelection(kind=kind, executed=executed, selected=selected)+ step = next((step for step in selected[0].steps if step.number == step_number), None)+ if step is None:+ raise ValueError("The selected job has no step with that number.")+ return TimingSelection(kind=kind, executed=executed, selected=selected, step_name=step.name)+++def match_timing_sample(+ run: TimingCandidateRun, jobs: Sequence[WorkflowJob], selection: TimingSelection+) -> CITimingSample | None:+ """The sample that ``run`` gives for ``selection``, or None when it did not run the same work.+ ``jobs`` is the job list of the run's latest attempt."""+ sampled = [+ job+ for job in jobs+ if job.conclusion not in _NOT_SAMPLED_CONCLUSIONS+ and job.started_at is not None+ and job.completed_at is not None+ ]+ if selection.kind in _SPANS_JOBS and _signatures(sampled) != _signatures(selection.executed):+ return None+ wanted = _signatures(selection.selected)+ matched = [job for job in sampled if _signature(job) in wanted]+ if not matched or _signatures(matched) != wanted:+ return None+ first_job = matched[0]+ completed_at = max(job.completed_at for job in matched if job.completed_at is not None)+ step_number: int | None = None+ if selection.kind is CITimingKind.STEP:+ steps = [+ step+ for step in first_job.steps+ if step.name == selection.step_name+ and step.started_at is not None+ and step.completed_at is not None+ and step.conclusion in _STEP_VERDICTS+ ]+ # Two steps with one name cannot be told apart, so neither is a sample.+ if len(steps) != 1 or steps[0].started_at is None or steps[0].completed_at is None:+ return None+ duration = steps[0].completed_at - steps[0].started_at+ succeeded = steps[0].conclusion == "success"+ step_number = steps[0].number+ else:+ duration = completed_at - min(job.started_at for job in matched if job.started_at is not None)+ succeeded = all(job.conclusion == "success" for job in matched)+ if duration < timedelta(0):+ return None+ one_job = selection.kind not in _SPANS_JOBS+ return CITimingSample(+ run_id=run.run_id,+ run_attempt=run.run_attempt,+ job_id=first_job.id if one_job else None,+ step_number=step_number,+ ci_engine=run.ci_engine,+ native_run_id=run.native_run_id,+ native_workflow_run_id=run.native_workflow_run_id,+ native_job_id=first_job.native_job_id if one_job else None,+ native_attempt_id=first_job.native_attempt_id if one_job else None,+ status=CITimingSampleStatus.SUCCESS if succeeded else CITimingSampleStatus.FAILURE,+ duration_seconds=duration.total_seconds(),+ completed_at=completed_at,+ head_sha=run.head_sha,+ )+++def _signature(job: WorkflowJob) -> _JobSignature:+ return _JobSignature(name=job.name, runner_label=job.runner_label)+++def _signatures(jobs: Sequence[WorkflowJob]) -> Counter[_JobSignature]:+ return Counter(_signature(job) for job in jobs)+++def build_ci_timing_context(+ *,+ curated: CuratedGitHubSource,+ repo: str,+ ci_engine: CIEngine,+ run_id: int,+ run_attempt: int,+ kind: CITimingKind,+ job_ids: Sequence[int] = (),+ step_number: int | None = None,+) -> CITimingContext:+ owner, name = _require_repo(repo)+ # A workflow selection reads no job ids, so they must not split its cache entries.+ job_ids = () if kind is CITimingKind.WORKFLOW else sorted(set(job_ids))+ if len(job_ids) > CI_TIMING_MAX_JOB_IDS:+ raise ValueError(f"Give at most {CI_TIMING_MAX_JOB_IDS} job ids.")+ selection_key = (+ f"{ci_engine.value}:{run_id}:{run_attempt}:{kind.value}:{','.join(map(str, job_ids))}"+ f":{step_number if kind is CITimingKind.STEP else ''}"+ )+ cache_key = (+ f"{_cache_prefix(curated, owner, name)}:ci_timing_context:{_CACHE_VERSION}"+ f":{hashlib.sha256(selection_key.encode()).hexdigest()}"+ )+ cached = _cache_get(curated, cache_key)+ if isinstance(cached, dict):+ return CITimingContext(**cached)+ context = _timing_context(+ curated=curated,+ ci_engine=ci_engine,+ run_id=run_id,+ run_attempt=run_attempt,+ kind=kind,+ job_ids=job_ids,+ step_number=step_number,+ )+ _cache_set(cache_key, asdict(context), _CACHE_SECONDS)+ return context+++def _timing_context(+ *,+ curated: CuratedGitHubSource,+ ci_engine: CIEngine,+ run_id: int,+ run_attempt: int,+ kind: CITimingKind,+ job_ids: Sequence[int],+ step_number: int | None,+) -> CITimingContext:+ run = query_workflow_run(curated=curated, run_id=run_id, ci_engine=ci_engine)+ if run is None:+ raise ValueError("The source holds no such run.")+ freshness = curated.ci_data_freshness()+ identity = CITimingIdentity.WORKFLOW_ID if run.workflow_id is not None else CITimingIdentity.WORKFLOW_NAME+ if curated.jobs_source() is None:+ return _without_samples(identity, freshness, unavailable_reason=CITimingUnavailableReason.JOBS_NOT_SYNCED)++ jobs = query_workflow_jobs(curated=curated, run_id=run_id, run_attempt=run_attempt, ci_engine=ci_engine)+ selection = select_timing_jobs(jobs, kind=kind, job_ids=job_ids, step_number=step_number)+ if selection is None:+ return _without_samples(identity, freshness, unavailable_reason=CITimingUnavailableReason.NOT_EXECUTED)+ default_branch = _default_branch(curated, run.repo)+ if default_branch is None:+ return _without_samples(+ identity, freshness, unavailable_reason=CITimingUnavailableReason.DEFAULT_BRANCH_UNKNOWN+ )++ candidates = query_timing_candidates(+ curated=curated,+ run=run,+ ci_engine=ci_engine,+ default_branch=default_branch,+ window_start=datetime.now(UTC) - timedelta(days=WINDOW_DAYS),+ )+ if not candidates.runs:+ return _without_samples(identity, freshness, default_branch=default_branch)+ one_job = kind not in _SPANS_JOBS+ jobs_by_run = query_jobs_by_run(+ curated=curated,+ ci_engine=ci_engine,+ run_attempts={candidate.run_id: candidate.run_attempt for candidate in candidates.runs},+ earliest_run_started_at=min(candidate.run_started_at for candidate in candidates.runs),+ # A job or step sample reads one job of each run, so the other jobs and their steps stay unread.+ job_name=selection.selected[0].name if one_job else None,+ include_steps=kind is CITimingKind.STEP,+ )+ samples = [+ sample+ for candidate in candidates.runs+ if (sample := match_timing_sample(candidate, jobs_by_run.get(candidate.run_id, []), selection)) is not None+ ]+ samples.sort(key=lambda sample: sample.completed_at, reverse=True)+ passed = [sample.duration_seconds for sample in samples if sample.status is CITimingSampleStatus.SUCCESS]+ return CITimingContext(+ default_branch=default_branch,+ window_days=WINDOW_DAYS,+ identity=identity,+ runs_scanned=len(candidates.runs),+ sampled=candidates.sampled,+ sample_count=len(passed),+ average_seconds=mean(passed) if passed else None,+ recent=samples[:_RECENT_SAMPLES],+ runs_synced_at=freshness.runs_synced_at,+ jobs_synced_at=freshness.jobs_synced_at,+ unavailable_reason=None,+ )+++def _without_samples(+ identity: CITimingIdentity,+ freshness: CIDataFreshness,+ *,+ default_branch: str | None = None,+ unavailable_reason: CITimingUnavailableReason | None = None,+) -> CITimingContext:+ return CITimingContext(+ default_branch=default_branch,+ window_days=WINDOW_DAYS,+ identity=identity,+ runs_scanned=0,+ sampled=False,+ sample_count=0,+ average_seconds=None,+ recent=[],+ runs_synced_at=freshness.runs_synced_at,+ jobs_synced_at=freshness.jobs_synced_at,+ unavailable_reason=unavailable_reason,+ )+++def _default_branch(curated: CuratedGitHubSource, repo: RepoRef) -> str | None:+ cache_key = f"{_cache_prefix(curated, repo.owner, repo.name)}:default_branch"+ cached = _cache_get(curated, cache_key)+ if isinstance(cached, str):+ return cached+ wanted = (repo.owner.casefold(), repo.name.casefold())+ for (owner, name), branch in query_default_branches(curated=curated).items():+ if (owner.casefold(), name.casefold()) == wanted:+ _cache_set(cache_key, branch, _DEFAULT_BRANCH_CACHE_SECONDS)+ return branch+ return None+++def _cache_prefix(curated: CuratedGitHubSource, owner: str, name: str) -> str:+ # The key holds what the handle resolved for this caller, not only what the request named. Two callers+ # share an entry only when they read the same repository through the same tables.+ scope = hashlib.sha256(+ f"{curated.repository.casefold()}|{curated.ci_read_scope()}|{owner.casefold()}/{name.casefold()}".encode()+ ).hexdigest()+ return f"engineering_analytics:{curated.team.pk}:{curated.source_id}:{scope}"+++def _cache_get(curated: CuratedGitHubSource, cache_key: str) -> object:+ # A cached answer skips the queries that apply table permissions, so the reader's access is checked here.+ if not curated.may_read_ci_tables():+ return None+ try:+ return cache.get(cache_key)+ except Exception:+ logger.warning("engineering_analytics_cache_read_failed", exc_info=True)+ return None+++def _cache_set(cache_key: str, value: object, timeout: int) -> None:+ try:+ cache.set(cache_key, value, timeout=timeout)+ except Exception:+ logger.warning("engineering_analytics_cache_write_failed", exc_info=True)diff --git a/products/engineering_analytics/backend/logic/job_log_insights.py b/products/engineering_analytics/backend/logic/job_log_insights.pynew file mode 100644index 000000000000..7de98b08fdb8--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_log_insights.py@@ -0,0 +1,136 @@+"""Read one GitHub Actions job's log and report what its steps did with caches and migrations.++The job is looked up in the caller's own source on every call, so a reader who cannot read that+source never reaches the log or a cached answer. The log comes from GitHub with the credential of+that same source only: its personal access token, or the GitHub integration it is linked to. A source+with neither gives no log, because any other credential of the team belongs to a source this reader+may not be allowed to use.+"""++from dataclasses import asdict, field, replace++from django.core.cache import cache++import structlog++from posthog.dataclasses import frozen+from posthog.egress.github.limiter import consume_github_installation_sync+from posthog.egress.limiter.policies import Priority+from posthog.models.integration import GitHubIntegration, Integration+from posthog.models.team import Team++from products.engineering_analytics.backend.facade.contracts import CIEngine, JobLogInsights+from products.engineering_analytics.backend.logic.job_logs.badges import parse_job_log+from products.engineering_analytics.backend.logic.job_logs.fetcher import FetchedJobLog, fetch_bounded_job_log+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource+from products.engineering_analytics.backend.logic.queries.workflow_jobs import query_workflow_job+from products.warehouse_sources.backend.facade import api as warehouse_sources++logger = structlog.get_logger(__name__)++_EGRESS_SOURCE = "job_logs"+# A person is waiting on the page, so the fetch must not hold the request as long as a worker may. The+# read timeout bounds one read of the response, and the deadline bounds the whole download.+_FETCH_READ_TIMEOUT_SECONDS = 10+_FETCH_DEADLINE_SECONDS = 20+# The log is held in a web worker's memory, and many requests can run at once. A log cut to this size+# can lose step markers, and the parser then reports for the job as a whole.+_MAX_LOG_BYTES = 4 * 1024 * 1024+# The download goes on past the kept size to reach the end of the log, where the cleanup steps are.+_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024+# A completed job's log never changes.+_CACHE_SECONDS = 7 * 24 * 60 * 60+# An answer from part of a log can miss outcomes, and a later read can get more of the log.+_TRUNCATED_CACHE_SECONDS = 5 * 60+# Part of the cache key. Raise it when the parser's rules or the cached shape change.+_CACHE_VERSION = 2++_LOG_NOT_READ = JobLogInsights(log_read=False, attributed_to_steps=False, job=[], steps=[])+++@frozen+class _LogCredential:+ token: str = field(repr=False)+ # None for a personal access token, which draws on the customer's own GitHub budget.+ installation_id: str | None+++def build_job_log_insights(+ *, curated: CuratedGitHubSource, run_id: int, job_id: int, ci_engine: CIEngine | None = None+) -> JobLogInsights:+ job = query_workflow_job(curated=curated, run_id=run_id, job_id=job_id, ci_engine=ci_engine)+ if job is None or job.ci_engine is not CIEngine.GITHUB_ACTIONS:+ return _LOG_NOT_READ+ completed = job.status == "completed"+ cache_key = (+ f"engineering_analytics:{curated.team.pk}:job_log_insights:{_CACHE_VERSION}"+ f":{curated.source_id}:{curated.repository.casefold()}:{job_id}"+ )+ if completed:+ cached = _cached(cache_key)+ if cached is not None:+ return cached+ try:+ log = _fetch_log(curated.team, curated.repository, curated.source_id, job_id)+ except Exception as error:+ # GitHub serves a log from a signed URL, and an HTTP error carries that URL, so only its type is logged.+ logger.warning("engineering_analytics_job_log_fetch_failed", job_id=job_id, error_type=type(error).__name__)+ return _LOG_NOT_READ+ if log is None:+ return _LOG_NOT_READ+ insights = replace(parse_job_log(log.text, job.steps), log_truncated=log.truncated)+ if completed:+ try:+ cache.set(+ cache_key,+ asdict(insights),+ timeout=_TRUNCATED_CACHE_SECONDS if log.truncated else _CACHE_SECONDS,+ )+ except Exception:+ logger.warning("engineering_analytics_cache_write_failed", exc_info=True)+ return insights+++def _cached(cache_key: str) -> JobLogInsights | None:+ try:+ value = cache.get(cache_key)+ return JobLogInsights(**value) if isinstance(value, dict) else None+ except Exception:+ logger.warning("engineering_analytics_cache_read_failed", exc_info=True)+ return None+++def _fetch_log(team: Team, repository: str, source_id: str, job_id: int) -> FetchedJobLog | None:+ credential = _log_credential(team, source_id)+ if credential is None:+ return None+ if credential.installation_id is not None and not consume_github_installation_sync(+ credential.installation_id, priority=Priority.NORMAL, source=_EGRESS_SOURCE+ ):+ return None+ return fetch_bounded_job_log(+ repository,+ job_id,+ credential.token,+ timeout=_FETCH_READ_TIMEOUT_SECONDS,+ max_bytes=_MAX_LOG_BYTES,+ max_read_bytes=_MAX_DOWNLOAD_BYTES,+ deadline_seconds=_FETCH_DEADLINE_SECONDS,+ )+++def _log_credential(team: Team, source_id: str) -> _LogCredential | None:+ credential = warehouse_sources.github_source_credential(team_id=team.pk, source_id=source_id) if source_id else None+ if credential is None:+ return None+ if credential.personal_access_token:+ return _LogCredential(token=credential.personal_access_token, installation_id=None)+ if credential.integration_id is None:+ return None+ integration = Integration.objects.filter(team_id=team.pk, id=credential.integration_id, kind="github").first()+ if integration is None:+ return None+ github = GitHubIntegration(integration, source=_EGRESS_SOURCE, priority=Priority.NORMAL)+ if not github.github_installation_id:+ return None+ return _LogCredential(token=github.get_access_token(), installation_id=str(github.github_installation_id))diff --git a/products/engineering_analytics/backend/logic/job_logs/badges.py b/products/engineering_analytics/backend/logic/job_logs/badges.pynew file mode 100644index 000000000000..a9c8f13ad6f5--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/badges.py@@ -0,0 +1,163 @@+"""What a GitHub Actions job log says its steps did with caches and migrations.++Pure text parsing. A job log has no step numbers. Each declared step opens with a ``##[group]Run``+line, each cleanup step with ``Post job cleanup.``, and the steps inside a composite action sit+between ``start-action`` and ``end-action``. Counting the openers outside composite actions gives+the step a line belongs to. When that count differs from the steps the job reports, no line is+attributed to a step and the badges are reported for the job as a whole only.+"""++import io+import re+from collections.abc import Sequence++from products.engineering_analytics.backend.facade.contracts import (+ JobLogBadge,+ JobLogBadgeKind,+ JobLogBadgeState,+ JobLogInsights,+ JobStepLogBadges,+ WorkflowJobStep,+)++_ANSI = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")+_TIMESTAMP = re.compile(r"^?\d{4}-\d\d-\d\dT[\d:.]+Z ")+_MAX_DETAILS = 20+_MAX_DETAIL_CHARS = 300++_Rule = tuple[JobLogBadgeKind, JobLogBadgeState, re.Pattern[str]]+# Matched at the start of a line. The pattern's group, when it has one, is the badge's detail.+_RULES: tuple[_Rule, ...] = (+ (JobLogBadgeKind.CACHE, JobLogBadgeState.HIT, re.compile(r"Cache hit for: (.+)")),+ (JobLogBadgeKind.CACHE, JobLogBadgeState.PARTIAL, re.compile(r"Cache hit for restore-key: (.+)")),+ (JobLogBadgeKind.CACHE, JobLogBadgeState.MISS, re.compile(r"Cache not found for input keys: (.+)")),+ (JobLogBadgeKind.CACHE, JobLogBadgeState.FAILED, re.compile(r"##\[warning\]Failed to restore: (.+)")),+ (JobLogBadgeKind.MIGRATIONS, JobLogBadgeState.NONE, re.compile(r"\s*No migrations to apply\.")),+ (JobLogBadgeKind.MIGRATIONS, JobLogBadgeState.APPLIED, re.compile(r"\s*Applying (\S+?)\.\.\.")),+)+# A line without one of these cannot match a rule, which spares most lines the regexes. A new rule needs its hint here.+_RULE_HINTS = ("Cache ", "Failed to restore", "igrations to apply", "Applying ")+# The runner adds these around the declared steps, and they do not open with a "Run" group.+_RUNNER_STEPS = ("Set up job", "Complete job")+_POST_PREFIX = "Post "++_BadgeKey = tuple[JobLogBadgeKind, JobLogBadgeState]+_HIT: _BadgeKey = (JobLogBadgeKind.CACHE, JobLogBadgeState.HIT)+_MISS: _BadgeKey = (JobLogBadgeKind.CACHE, JobLogBadgeState.MISS)+_FAILED: _BadgeKey = (JobLogBadgeKind.CACHE, JobLogBadgeState.FAILED)+++class _Found:+ """The matches of one job or one step. The pull request's author writes the log, so what is kept+ of it is bounded while it is read: every match is counted, and only the first few details are held.++ A restore that fails logs a hit, then the failure, then a miss. Only the failure is worth showing,+ so the failure removes the hit logged just before it and drops the miss logged just after it. The+ hits and misses of other restores stay."""++ def __init__(self) -> None:+ self.counts: dict[_BadgeKey, int] = {}+ self.details: dict[_BadgeKey, list[str]] = {}+ # Set while the last cache line was a hit. The value says whether the hit's detail was kept.+ self._last_hit_detail_kept: bool | None = None+ self._miss_belongs_to_failure = False++ def add(self, key: _BadgeKey, detail: str) -> None:+ if key[0] is JobLogBadgeKind.CACHE:+ if key == _FAILED:+ self._remove_last_hit()+ self._miss_belongs_to_failure = True+ elif key == _MISS and self._miss_belongs_to_failure:+ self._miss_belongs_to_failure = False+ return+ else:+ self._miss_belongs_to_failure = False+ self.counts[key] = self.counts.get(key, 0) + 1+ details = self.details.setdefault(key, [])+ detail_kept = len(details) < _MAX_DETAILS+ if detail_kept:+ details.append(detail[:_MAX_DETAIL_CHARS])+ if key[0] is JobLogBadgeKind.CACHE:+ self._last_hit_detail_kept = detail_kept if key == _HIT else None++ def _remove_last_hit(self) -> None:+ if self._last_hit_detail_kept is None:+ return+ if self._last_hit_detail_kept:+ self.details[_HIT].pop()+ self.counts[_HIT] -= 1+ if not self.counts[_HIT]:+ del self.counts[_HIT]+ del self.details[_HIT]+++def parse_job_log(log_text: str, steps: Sequence[WorkflowJobStep]) -> JobLogInsights:+ assigner = _StepAssigner(steps)+ whole = _Found()+ by_step: dict[int, _Found] = {}+ # StringIO yields one line at a time, where splitlines would hold a second copy of the whole log.+ for raw_line in io.StringIO(log_text):+ line = _ANSI.sub("", _TIMESTAMP.sub("", raw_line.rstrip("\r\n")))+ step = assigner.step_of(line)+ if not any(hint in line for hint in _RULE_HINTS):+ continue+ for kind, state, pattern in _RULES:+ if match := pattern.match(line):+ detail = match.group(1) if match.groups() else ""+ whole.add((kind, state), detail)+ if step is not None:+ by_step.setdefault(step, _Found()).add((kind, state), detail)+ break+ attributed = assigner.matches_job_steps()+ return JobLogInsights(+ log_read=True,+ attributed_to_steps=attributed,+ job=_badges(whole),+ steps=(+ [JobStepLogBadges(number=number, badges=_badges(found)) for number, found in sorted(by_step.items())]+ if attributed+ else []+ ),+ )+++class _StepAssigner:+ """Gives each log line, fed in order, the number of the step that wrote it."""++ def __init__(self, steps: Sequence[WorkflowJobStep]) -> None:+ ran = sorted((step for step in steps if step.conclusion != "skipped"), key=lambda step: step.number)+ names = {step.name for step in ran}+ # The runner names a cleanup step "Post " plus the name of the step it cleans up after.+ self._post = [+ step.number+ for step in ran+ if step.name.startswith(_POST_PREFIX) and step.name.removeprefix(_POST_PREFIX) in names+ ]+ self._main = [step.number for step in ran if step.name not in _RUNNER_STEPS and step.number not in self._post]+ self._current = ran[0].number if ran else None+ self._composite_depth = 0+ self._opened = 0+ self._cleaned = 0++ def step_of(self, line: str) -> int | None:+ if line.startswith("##[start-action"):+ self._composite_depth += 1+ elif line.startswith("##[end-action"):+ self._composite_depth -= 1+ elif self._composite_depth == 0 and line.startswith("##[group]Run "):+ self._current = self._main[self._opened] if self._opened < len(self._main) else None+ self._opened += 1+ elif self._composite_depth == 0 and line.startswith("Post job cleanup."):+ self._current = self._post[self._cleaned] if self._cleaned < len(self._post) else None+ self._cleaned += 1+ return self._current++ def matches_job_steps(self) -> bool:+ return self._opened == len(self._main) and self._cleaned == len(self._post)+++def _badges(found: _Found) -> list[JobLogBadge]:+ return [+ JobLogBadge(kind=kind, state=state, count=count, detail=found.details[(kind, state)])+ for (kind, state), count in found.counts.items()+ ]diff --git a/products/engineering_analytics/backend/logic/job_logs/fetcher.py b/products/engineering_analytics/backend/logic/job_logs/fetcher.pyindex 2611252937e4..5d238bb31e73 100644--- a/products/engineering_analytics/backend/logic/job_logs/fetcher.py+++ b/products/engineering_analytics/backend/logic/job_logs/fetcher.py@@ -7,6 +7,7 @@ the Temporal retry honors the reset."""import json+import timeimport datetime as dtimport contextlibfrom typing import Any@@ -14,6 +15,7 @@ from typing import Anyimport requestsfrom temporalio.exceptions import ApplicationError+from posthog.dataclasses import frozenfrom posthog.egress.github.transport import github_request, raise_if_github_rate_limitedfrom posthog.models.integration.github import _is_safe_github_repo_path@@ -49,15 +51,48 @@ class _HeadAndTail:self._truncated = Truedel self._tail[: -self._half] # keep only the most recent `half` bytes+ @property+ def truncated(self) -> bool:+ return self._truncated+def text(self) -> str:middle = b"\n... [log truncated] ...\n" if self._truncated else b""return (bytes(self._head) + middle + bytes(self._tail)).decode("utf-8", errors="replace")+@frozen+class FetchedJobLog:+ text: str+ # True when ``text`` is not the whole log, because the log passed the kept size or the download stopped early.+ truncated: bool++def fetch_job_log(repo: str, job_id: int, access_token: str, *, timeout: int = 60, max_bytes: int = _MAX_LOG_BYTES) -> str | None:"""Return the job's log text (capped at ``max_bytes``), or None if GitHub purged it (404)."""+ fetched = fetch_bounded_job_log(repo, job_id, access_token, timeout=timeout, max_bytes=max_bytes)+ return fetched.text if fetched is not None else None+++def fetch_bounded_job_log(+ repo: str,+ job_id: int,+ access_token: str,+ *,+ timeout: int = 60,+ max_bytes: int = _MAX_LOG_BYTES,+ max_read_bytes: int | None = None,+ deadline_seconds: float | None = None,+) -> FetchedJobLog | None:+ """The job's log, or None if GitHub purged it (404). The text keeps at most ``max_bytes``.++ ``timeout`` bounds each read of the response and not the whole download, so a log that arrives+ slowly can hold the caller without end. ``max_read_bytes`` and ``deadline_seconds`` bound the whole+ download. When either stops it, the response is closed and the log read so far is returned as+ truncated. The deadline is checked between chunks, so the download can pass it by one ``timeout``.+ """+ deadline = time.monotonic() + deadline_seconds if deadline_seconds is not None else Noneif not _is_safe_github_repo_path(repo):# repo is team-writable source config; reject anything but plain owner/repo so a crafted# value can't steer this authenticated request to a different GitHub endpoint.@@ -81,9 +116,17 @@ def fetch_job_log(return Noneresponse.raise_for_status()log = _HeadAndTail(max_bytes)+ read_bytes = 0+ stopped_early = Falsefor chunk in response.iter_content(chunk_size=65536):log.extend(chunk)- return log.text()+ read_bytes += len(chunk)+ if (max_read_bytes is not None and read_bytes > max_read_bytes) or (+ deadline is not None and time.monotonic() >= deadline+ ):+ stopped_early = True+ break+ return FetchedJobLog(text=log.text(), truncated=log.truncated or stopped_early)def _depot_line_text(line: dict[str, Any]) -> str:diff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_badges.py b/products/engineering_analytics/backend/logic/job_logs/test/test_badges.pynew file mode 100644index 000000000000..998e8c84a1f5--- /dev/null+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_badges.py@@ -0,0 +1,125 @@+from parameterized import parameterized++from products.engineering_analytics.backend.facade.contracts import WorkflowJobStep+from products.engineering_analytics.backend.logic.job_logs.badges import parse_job_log++_STEP_NAMES = [+ "Set up job",+ "Fetch code",+ "Restore packages",+ "Prepare database",+ "Post Restore packages",+ "Complete job",+]+_RESTORE, _DATABASE = 3, 4+++def _steps(skipped: tuple[int, ...] = ()) -> list[WorkflowJobStep]:+ return [+ WorkflowJobStep(+ number=number,+ name=name,+ status="completed",+ conclusion="skipped" if number in skipped else "success",+ started_at=None,+ completed_at=None,+ duration_seconds=None,+ )+ for number, name in enumerate(_STEP_NAMES, start=1)+ ]+++def _log(restore: list[str], database: list[str] | None = None) -> str:+ lines = [+ "2026-01-05T10:00:00.0000000Z Runner image ready",+ "2026-01-05T10:00:01.0000000Z ##[group]Run example/fetch-code@v1",+ "##[group]Run example/restore-packages@v1",+ # A composite action's inner steps are not steps of the job.+ "##[start-action display=Inner;id=inner]",+ "##[group]Run echo inner",+ "##[end-action id=inner]",+ *restore,+ *(["##[group]Run ./bin/prepare-database", *database] if database is not None else []),+ "Post job cleanup.",+ ]+ return "\n".join(lines)+++def _flat(badges: list) -> list[tuple[str, str, int, list[str]]]:+ return [(badge.kind.value, badge.state.value, badge.count, badge.detail) for badge in badges]+++class TestParseJobLog:+ @parameterized.expand(+ [+ ("hit", ["\x1b[36mCache hit for: packages-a1\x1b[0m"], [("cache", "hit", 1, ["packages-a1"])]),+ ("older_cache", ["Cache hit for restore-key: packages-"], [("cache", "partial", 1, ["packages-"])]),+ (+ "miss",+ ["2026-01-05T10:00:02.0000000Z Cache not found for input keys: packages-a1, packages-"],+ [("cache", "miss", 1, ["packages-a1, packages-"])],+ ),+ (+ "restore_failed_hides_its_own_hit_and_miss",+ [+ "Cache hit for: packages-a1",+ "##[warning]Failed to restore: download stopped",+ "Cache not found for input keys: packages-a1",+ ],+ [("cache", "failed", 1, ["download stopped"])],+ ),+ (+ "restore_failed_keeps_the_hit_of_another_restore",+ [+ "Cache hit for: tools-b2",+ "Cache not found for input keys: docs-c3",+ "Cache hit for: packages-a1",+ "##[warning]Failed to restore: download stopped",+ "Cache not found for input keys: packages-a1",+ ],+ [+ ("cache", "hit", 1, ["tools-b2"]),+ ("cache", "miss", 1, ["docs-c3"]),+ ("cache", "failed", 1, ["download stopped"]),+ ],+ ),+ (+ "restore_failed_without_a_hit_keeps_the_earlier_miss",+ ["Cache not found for input keys: docs-c3", "##[warning]Failed to restore: download stopped"],+ [("cache", "miss", 1, ["docs-c3"]), ("cache", "failed", 1, ["download stopped"])],+ ),+ ]+ )+ def test_cache_outcome_lands_on_the_restoring_step(+ self, _name: str, restore: list[str], expected: list[tuple[str, str, int, list[str]]]+ ) -> None:+ insights = parse_job_log(_log(restore, database=[" No migrations to apply."]), _steps())++ assert insights.log_read and insights.attributed_to_steps+ by_step = {step.number: _flat(step.badges) for step in insights.steps}+ assert by_step == {_RESTORE: expected, _DATABASE: [("migrations", "none", 1, [""])]}+ assert _flat(insights.job) == [*expected, ("migrations", "none", 1, [""])]++ def test_counts_applied_migrations(self) -> None:+ applied = [" Applying shop.0002_widget... OK", " Applying shop.0003_widget_color... OK"]++ insights = parse_job_log(_log([], database=applied), _steps())++ assert [(step.number, _flat(step.badges)) for step in insights.steps] == [+ (_DATABASE, [("migrations", "applied", 2, ["shop.0002_widget", "shop.0003_widget_color"])])+ ]++ @parameterized.expand(+ [+ ("log_opens_fewer_steps_than_the_job_ran", None, ()),+ ("log_opens_a_step_the_job_reports_skipped", [" No migrations to apply."], (_DATABASE,)),+ ]+ )+ def test_reports_job_level_badges_only_when_markers_and_steps_disagree(+ self, _name: str, database: list[str] | None, skipped: tuple[int, ...]+ ) -> None:+ insights = parse_job_log(_log(["Cache hit for: packages-a1"], database=database), _steps(skipped))++ assert insights.log_read and not insights.attributed_to_steps+ assert insights.steps == []+ assert ("cache", "hit", 1, ["packages-a1"]) in _flat(insights.job)diff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_fetcher.py b/products/engineering_analytics/backend/logic/job_logs/test/test_fetcher.pyindex 0ba2f654982d..9f1ead48d6af 100644--- a/products/engineering_analytics/backend/logic/job_logs/test/test_fetcher.py+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_fetcher.py@@ -7,7 +7,11 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.egress.github.transport import GitHubRateLimitError-from products.engineering_analytics.backend.logic.job_logs.fetcher import fetch_depot_job_log, fetch_job_log+from products.engineering_analytics.backend.logic.job_logs.fetcher import (+ fetch_bounded_job_log,+ fetch_depot_job_log,+ fetch_job_log,+)_URL = "https://api.github.com/repos/PostHog/posthog/actions/jobs/123/logs"_DEPOT_URL = "https://api.depot.dev/depot.ci.v1.CIService/GetJobAttemptLogs"@@ -59,6 +63,26 @@ def test_caps_log_but_keeps_failure_tail(requests_mock):assert len(result.encode()) < len(body.encode())+ "bounds, truncated",+ [+ ({}, False),+ ({"max_read_bytes": 1000}, True),+ ({"deadline_seconds": 0}, True),+ ],+)+def test_bounded_fetch_stops_the_download_and_reports_a_partial_log(requests_mock, bounds, truncated):+ # A person waits on this read, so a large or slow log must stop early and say that it is partial.+ body = "noise line\n" * 20_000+ requests_mock.get(_URL, status_code=200, text=body)++ log = fetch_bounded_job_log("PostHog/posthog", 123, "tok", **bounds)++ assert log is not None+ assert log.truncated is truncated+ assert (len(log.text) < len(body)) is truncated++@pytest.mark.parametrize("bad_repo",[diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.pyindex 4d04396c0f4e..a6760fe8f3f5 100644--- a/products/engineering_analytics/backend/logic/queries/_curated.py+++ b/products/engineering_analytics/backend/logic/queries/_curated.py@@ -45,11 +45,12 @@ from posthog.dataclasses import frozenfrom posthog.hogql_queries.utils.parallel import run_in_parallel_threadsfrom posthog.models.team import Team-from products.engineering_analytics.backend.facade.contracts import QueryWorkLimitExceededError+from products.engineering_analytics.backend.facade.contracts import CIDataFreshness, QueryWorkLimitExceededErrorfrom products.engineering_analytics.backend.logic.queries._workflow_filters import DECISIVE_FAILURE_CONCLUSIONS_SQLfrom products.engineering_analytics.backend.logic.sources import (GitHubTables,TrunkQuarantineSource,+ resolve_ci_data_freshness,resolve_depot_job_attempts_tables,resolve_github_tables,resolve_trunk_merge_queue_table,@@ -281,6 +282,35 @@ class CuratedGitHubSource:self._depot_job_attempts(),self._tables.pull_requests,self._tables.workflow_jobs,+ optional_columns=self._tables.workflow_runs_optional_columns,+ )++ def ci_read_scope(self) -> str:+ """Names the tables a CI read of this handle uses, for a cache key.++ The Depot table is part of the answer only for a caller who may read the Depot source. A cache key+ without it would serve an answer built from Depot rows to a caller who has no access to them.+ """+ depot = self._depot_job_attempts()+ return f"{self._tables.workflow_runs}|{self._tables.workflow_jobs or ''}|{depot.table if depot else ''}"++ def may_read_ci_tables(self) -> bool:+ """Whether this reader's catalog grants every table a CI read uses.++ A cached CI answer skips the query that would have applied the table permissions, so a caller must+ ask this before it serves one.+ """+ depot = self._depot_job_attempts()+ tables = [self._tables.pull_requests, self._tables.workflow_runs, self._tables.workflow_jobs]+ if depot is not None:+ tables.append(depot.table)+ catalog = self._catalog()+ return all(catalog.has_table(table) and not catalog.is_table_access_denied(table) for table in tables if table)++ def ci_data_freshness(self) -> CIDataFreshness:+ """When the runs and jobs this handle reads were last synced from their sources."""+ return resolve_ci_data_freshness(+ team=self._team, tables=self._tables, user_access_control=self._user_access_control)def _jobs_table(self, workflow_jobs_table: str) -> workflow_jobs.JobsTable:diff --git a/products/engineering_analytics/backend/logic/queries/_run_detail.py b/products/engineering_analytics/backend/logic/queries/_run_detail.pyindex f3133220357d..5dcf76168aa5 100644--- a/products/engineering_analytics/backend/logic/queries/_run_detail.py+++ b/products/engineering_analytics/backend/logic/queries/_run_detail.py@@ -13,7 +13,8 @@ from products.engineering_analytics.backend.facade.contracts import CIEngine, ReRUN_DETAIL_COLUMNS = """id, workflow_name, head_sha, head_branch, status, conclusion,run_started_at, updated_at, duration_seconds, run_attempt, pr_number, commit_pr_number,- repo_owner, repo_name, is_merge_queue, ci_engine, native_run_id, native_workflow_run_id+ repo_owner, repo_name, is_merge_queue, ci_engine, native_run_id, native_workflow_run_id,+ workflow_id, event"""@@ -37,6 +38,8 @@ def to_run_detail(row: tuple[Any, ...]) -> WorkflowRunDetail:ci_engine,native_run_id,native_workflow_run_id,+ workflow_id,+ event,) = rowreturn WorkflowRunDetail(repo=RepoRef(provider="github", owner=repo_owner, name=repo_name),@@ -58,4 +61,6 @@ def to_run_detail(row: tuple[Any, ...]) -> WorkflowRunDetail:ci_engine=CIEngine(ci_engine),native_run_id=native_run_id,native_workflow_run_id=native_workflow_run_id,+ workflow_id=int(workflow_id) if workflow_id is not None else None,+ event=event or None,)diff --git a/products/engineering_analytics/backend/logic/queries/timing_candidates.py b/products/engineering_analytics/backend/logic/queries/timing_candidates.pynew file mode 100644index 000000000000..95b2c0295c05--- /dev/null+++ b/products/engineering_analytics/backend/logic/queries/timing_candidates.py@@ -0,0 +1,109 @@+"""The default-branch runs that a CI timing comparison may sample.++A candidate is a completed run of the same workflow, on the same engine, that a push or a schedule+started on the repository's default branch. The newest ``RUNS_SCANNED`` are returned, because the+caller reads every job of every candidate.+"""++from datetime import datetime++from posthog.hogql import ast++from posthog.dataclasses import frozen++from products.engineering_analytics.backend.facade.contracts import CIEngine, WorkflowRunDetail+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource+from products.engineering_analytics.backend.logic.queries._workflow_filters import run_started_floor_constant++RUNS_SCANNED = 40++# A pull request from a fork branch that has the default branch's name carries that name as its head+# branch, so the branch alone does not prove a default-branch run. The trigger event does. A run with+# no recorded event (a Depot CI run, or a table that lacks the column) qualifies only when no pull+# request is attributed to it.+_NOT_A_PULL_REQUEST_RUN = "if(ifNull(event, '') = '', pr_number = 0, NOT startsWith(event, 'pull_request'))"++# One row more than the scan reads, which tells the caller that more eligible runs existed.+_SELECT = f"""+ SELECT id, run_attempt, head_sha, run_started_at, native_run_id, native_workflow_run_id+ FROM __RUNS_SOURCE__ AS r+ WHERE repo_owner = {{repo_owner}} AND repo_name = {{repo_name}}+ AND ci_engine = {{ci_engine}}+ AND __WORKFLOW_IDENTITY__+ AND head_branch = {{default_branch}}+ AND {_NOT_A_PULL_REQUEST_RUN}+ AND NOT is_merge_queue+ AND status = 'completed'+ AND run_started_at >= {{date_from}}+ AND id != {{run_id}}+ ORDER BY run_started_at DESC, id DESC, run_attempt DESC+ LIMIT 1 BY id+ LIMIT {RUNS_SCANNED + 1}+"""+++@frozen+class TimingCandidateRun:+ run_id: int+ run_attempt: int+ ci_engine: CIEngine+ head_sha: str+ run_started_at: datetime+ native_run_id: str | None+ native_workflow_run_id: str | None+++@frozen+class TimingCandidates:+ # Newest first.+ runs: list[TimingCandidateRun]+ # True when more eligible runs existed in the window than ``runs`` holds.+ sampled: bool+++def query_timing_candidates(+ *,+ curated: CuratedGitHubSource,+ run: WorkflowRunDetail,+ ci_engine: CIEngine,+ default_branch: str,+ window_start: datetime,+) -> TimingCandidates:+ """Runs comparable to ``run``. The workflow id identifies the workflow when ``run`` has one, because+ it survives a rename. The workflow name is the fallback."""+ placeholders: dict[str, ast.Expr] = {+ "repo_owner": ast.Constant(value=run.repo.owner),+ "repo_name": ast.Constant(value=run.repo.name),+ "ci_engine": ast.Constant(value=ci_engine.value),+ "default_branch": ast.Constant(value=default_branch),+ "date_from": ast.Constant(value=window_start),+ "run_started_floor": run_started_floor_constant(window_start),+ "run_id": ast.Constant(value=run.id),+ }+ if run.workflow_id is not None:+ identity = "workflow_id = {workflow_id}"+ placeholders["workflow_id"] = ast.Constant(value=run.workflow_id)+ else:+ identity = "workflow_name = {workflow_name}"+ placeholders["workflow_name"] = ast.Constant(value=run.workflow_name)+ response = curated.run(+ _SELECT.replace("__RUNS_SOURCE__", curated.run_source(started_floor=True)).replace(+ "__WORKFLOW_IDENTITY__", identity+ ),+ query_type="engineering_analytics.ci_timing_candidates",+ placeholders=placeholders,+ )+ rows = list(response.results or [])+ runs = [+ TimingCandidateRun(+ run_id=int(run_id),+ run_attempt=int(run_attempt) if run_attempt is not None else 1,+ ci_engine=ci_engine,+ head_sha=head_sha or "",+ run_started_at=run_started_at,+ native_run_id=native_run_id,+ native_workflow_run_id=native_workflow_run_id,+ )+ for run_id, run_attempt, head_sha, run_started_at, native_run_id, native_workflow_run_id in rows[:RUNS_SCANNED]+ ]+ return TimingCandidates(runs=runs, sampled=len(rows) > RUNS_SCANNED)diff --git a/products/engineering_analytics/backend/logic/queries/workflow_jobs.py b/products/engineering_analytics/backend/logic/queries/workflow_jobs.pyindex 302ca2e798d6..21832868c495 100644--- a/products/engineering_analytics/backend/logic/queries/workflow_jobs.py+++ b/products/engineering_analytics/backend/logic/queries/workflow_jobs.py@@ -28,6 +28,10 @@ from products.engineering_analytics.backend.logic.cost import (runner_descriptor,)from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource+from products.engineering_analytics.backend.logic.queries._workflow_filters import (+ UNPAGED_SCAN_LIMIT,+ run_windowed_job_created_floor_constant,+)# Explicit high LIMIT: without it HogQL caps at DEFAULT_RETURNED_ROWS (100), and since the rows are ordered# by start, a run with >100 jobs (matrix builds, re-run attempts) would silently drop its latest-starting@@ -42,10 +46,25 @@ _SELECT = """ci_engine, native_run_id, native_workflow_run_id, native_job_id, native_attempt_id, stepsFROM __JOBS_SOURCE__ AS jWHERE run_id = {run_id} AND ({ci_engine} IS NULL OR ci_engine = {ci_engine})+ AND ({job_id} IS NULL OR id = {job_id})ORDER BY started_at ASC, id ASCLIMIT 1000000"""+# Reads several runs, so it takes the scan floor that the one-run read above does not need. Re-listed+# rows stay, as in the one-run read, so both reads give an attempt the same job list. A re-listed row+# can keep the creation time of the attempt that ran it, which is before its run's newest start. The+# floor is therefore the wide one, or it would cut those rows out of the attempt. The cut would leave+# a partial job list, and is_rerun_copy and the cost are not exact under a floor, so do not read them here.+_RUN_ATTEMPTS_SELECT = f"""+ SELECT id, run_id, run_attempt, name, status, conclusion, labels, runner_name, started_at, completed_at, duration_seconds, provisioning_seconds, is_rerun_copy,+ ci_engine, native_run_id, native_workflow_run_id, native_job_id, native_attempt_id, __STEPS__+ FROM __JOBS_SOURCE__ AS j+ WHERE run_id IN {{run_ids}} AND ci_engine = {{ci_engine}} __JOB_NAME__+ ORDER BY started_at ASC, id ASC+ LIMIT {UNPAGED_SCAN_LIMIT}+"""+_LATEST_ATTEMPT_SELECT = """SELECT ci_engine, max(run_attempt)FROM __RUNS_SOURCE__ AS r@@ -73,6 +92,7 @@ def query_workflow_jobs(placeholders={"run_id": ast.Constant(value=run_id),"ci_engine": ast.Constant(value=ci_engine.value if ci_engine is not None else None),+ "job_id": ast.Constant(value=None),},)rows = list(response.results or [])@@ -92,6 +112,70 @@ def query_workflow_jobs(return [_to_job(row) for row in rows]+def query_workflow_job(+ *, curated: CuratedGitHubSource, run_id: int, job_id: int, ci_engine: CIEngine | None = None+) -> WorkflowJob | None:+ """One job of a run, whichever attempt it belongs to, or None when the source has no such job."""+ jobs_source = curated.jobs_source(include_steps=True)+ if jobs_source is None:+ return None+ response = curated.run(+ _SELECT.replace("__JOBS_SOURCE__", jobs_source),+ query_type="engineering_analytics.workflow_job",+ placeholders={+ "run_id": ast.Constant(value=run_id),+ "ci_engine": ast.Constant(value=ci_engine.value if ci_engine is not None else None),+ "job_id": ast.Constant(value=job_id),+ },+ )+ rows = list(response.results or [])+ if len({row[13] for row in rows}) > 1:+ raise ValueError("Ambiguous job_id; specify ci_engine.")+ if not rows:+ return None+ # A Depot CI job that a later run attempt did not re-run is listed again under that attempt with the+ # same id. The row that ran sorts first, then the latest attempt.+ return _to_job(min(rows, key=lambda row: (bool(row[12]), -int(row[2] or 0))))+++def query_jobs_by_run(+ *,+ curated: CuratedGitHubSource,+ ci_engine: CIEngine,+ run_attempts: dict[int, int],+ earliest_run_started_at: datetime,+ job_name: str | None = None,+ include_steps: bool = False,+) -> dict[int, list[WorkflowJob]]:+ """The job list of one attempt of each run, keyed by run id. ``run_attempts`` maps each run id+ to the attempt to read, and ``earliest_run_started_at`` is the earliest start among those runs.+ ``job_name`` keeps one job name. Steps are the widest column, so they are read only on request."""+ jobs_source = curated.jobs_source(created_floor=True, include_steps=include_steps)+ if jobs_source is None or not run_attempts:+ return {}+ placeholders: dict[str, ast.Expr] = {+ "run_ids": ast.Constant(value=sorted(run_attempts)),+ "ci_engine": ast.Constant(value=ci_engine.value),+ "job_created_floor": run_windowed_job_created_floor_constant(earliest_run_started_at),+ }+ if job_name is not None:+ placeholders["job_name"] = ast.Constant(value=job_name)+ response = curated.run(+ _RUN_ATTEMPTS_SELECT.replace("__JOBS_SOURCE__", jobs_source)+ .replace("__STEPS__", "steps" if include_steps else "'' AS steps")+ .replace("__JOB_NAME__", "AND name = {job_name}" if job_name is not None else ""),+ query_type="engineering_analytics.workflow_jobs_by_run",+ placeholders=placeholders,+ )+ jobs_by_run: dict[int, list[WorkflowJob]] = {}+ for row in response.results or []:+ row_run_id, row_attempt = row[1], row[2]+ if row_run_id is None or row_attempt is None or run_attempts.get(int(row_run_id)) != int(row_attempt):+ continue+ jobs_by_run.setdefault(int(row_run_id), []).append(_to_job(row))+ return jobs_by_run++def _latest_run_attempt(*, curated: CuratedGitHubSource, run_id: int, ci_engine: CIEngine | None) -> int | None:response = curated.run(_LATEST_ATTEMPT_SELECT.replace("__RUNS_SOURCE__", curated.run_source()),diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.pyindex c4b12c67df00..3dbea7b27031 100644--- a/products/engineering_analytics/backend/logic/sources.py+++ b/products/engineering_analytics/backend/logic/sources.py@@ -22,6 +22,7 @@ to read a specific source; otherwise the oldest source's repos are tried first,import refrom collections.abc import Iterable, Iteratorfrom dataclasses import dataclass, replace+from datetime import datetimefrom typing import TYPE_CHECKING, NamedTuplefrom uuid import UUID@@ -30,8 +31,13 @@ from django.db.models import QuerySetfrom posthog.dataclasses import frozenfrom posthog.models.team import Team-from products.engineering_analytics.backend.facade.contracts import GitHubSource, GitHubSourceNotConnectedError+from products.engineering_analytics.backend.facade.contracts import (+ CIDataFreshness,+ GitHubSource,+ GitHubSourceNotConnectedError,+)from products.engineering_analytics.backend.logic.views import depot_ci, workflow_jobs+from products.engineering_analytics.backend.logic.views.source_schema import OPTIONAL_WORKFLOW_RUNS_COLUMNSfrom products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSourcefrom products.warehouse_sources.backend.facade.sources import github_schema_repo_endpointfrom products.warehouse_sources.backend.facade.types import ExternalDataSourceType@@ -118,6 +124,11 @@ class GitHubTables:reviews: str | None = None# True when the issue-events table has the requested_team column (see REQUESTED_TEAM_COLUMN).issue_events_team_requests: bool = False+ # The OPTIONAL_WORKFLOW_RUNS_COLUMNS that the runs table has. A read selects NULL for the others.+ workflow_runs_optional_columns: frozenset[str] = frozenset()+ # When the last completed sync of each CI table started. None when the table never synced.+ workflow_runs_synced_at: datetime | None = None+ workflow_jobs_synced_at: datetime | None = None# Used to scope cross-store reads such as CI traces to the selected source's repository.repository: str = ""# The source these tables came from, already filtered by the caller's per-source warehouse RBAC.@@ -195,6 +206,9 @@ def resolve_github_tables(deployment_statuses=tables.get(DEPLOYMENT_STATUSES_SCHEMA),reviews=tables.get(REVIEWS_SCHEMA),issue_events_team_requests=candidate.tables.issue_events_team_requests,+ workflow_runs_optional_columns=candidate.tables.workflow_runs_optional_columns,+ workflow_runs_synced_at=candidate.tables.synced_at.get(WORKFLOW_RUNS_SCHEMA),+ workflow_jobs_synced_at=candidate.tables.synced_at.get(WORKFLOW_JOBS_SCHEMA),repository=candidate.repository,source_id=candidate.source_id,)@@ -218,12 +232,17 @@ class JobSourceTables:reviews: str | None = Nonesource_id: str = ""depot_job_attempts: depot_ci.DepotJobAttempts | None = None+ workflow_runs_optional_columns: frozenset[str] = frozenset()@propertydef runs_source(self) -> str:"""The runs to read: the GitHub runs table plus this repo's Depot CI runs when synced."""return depot_ci.with_depot_runs(- self.github_workflow_runs, self.depot_job_attempts, self.pull_requests, self.github_workflow_jobs+ self.github_workflow_runs,+ self.depot_job_attempts,+ self.pull_requests,+ self.github_workflow_jobs,+ optional_columns=self.workflow_runs_optional_columns,)@property@@ -257,6 +276,7 @@ def resolve_job_source_tables(team: Team) -> list[JobSourceTables]:issue_events=tables.get(ISSUE_EVENTS_SCHEMA),reviews=tables.get(REVIEWS_SCHEMA),source_id=str(source.id),+ workflow_runs_optional_columns=repo_tables.workflow_runs_optional_columns,)entries.append((repository, entry))# The views union every entry, so a repository that two GitHub sources sync takes its Depot table on@@ -406,6 +426,9 @@ class _RepoTables(NamedTuple):# ``{endpoint: table name}`` for this one repo's synced curated schemas.names: dict[str, str]issue_events_team_requests: bool+ workflow_runs_optional_columns: frozenset[str]+ # ``{endpoint: last_synced_at}`` for the same schemas as ``names``.+ synced_at: dict[str, datetime | None]class _RepoCandidate(NamedTuple):@@ -535,14 +558,53 @@ def resolve_depot_job_attempts_tables(A Depot source syncs only the repository its ``repository`` input names, so that input decideswhich GitHub repository its runs join. The oldest source wins, like every other resolver here."""- tables: dict[str, depot_ci.DepotJobAttempts] = {}+ return {+ repository: depot.attempts+ for repository, depot in _depot_job_attempts_by_repo(team, user_access_control).items()+ }+++@frozen+class _SyncedDepotJobAttempts:+ attempts: depot_ci.DepotJobAttempts+ synced_at: datetime | None+++def _depot_job_attempts_by_repo(+ team: Team, user_access_control: "UserAccessControl | None"+) -> dict[str, _SyncedDepotJobAttempts]:+ by_repo: dict[str, _SyncedDepotJobAttempts] = {}for source in _accessible_sources(team, ExternalDataSourceType.DEPOT, user_access_control):repository = _source_repository(source).casefold()- table = depot_source_job_attempts_table(team, source) if repository else None- attempts = depot_ci.DepotJobAttempts.for_repository(table, repository) if table else None- if attempts:- tables.setdefault(repository, attempts)- return tables+ schema = _synced_schema(team, source, DEPOT_JOB_ATTEMPTS_SCHEMA) if repository else None+ table = schema.table if schema is not None else None+ attempts = depot_ci.DepotJobAttempts.for_repository(table.name, repository) if table is not None else None+ if schema is not None and attempts is not None:+ by_repo.setdefault(repository, _SyncedDepotJobAttempts(attempts=attempts, synced_at=schema.last_synced_at))+ return by_repo+++def resolve_ci_data_freshness(+ *, team: Team, tables: GitHubTables, user_access_control: "UserAccessControl | None" = None+) -> CIDataFreshness:+ """When the CI data that ``tables`` reads was last synced from its source.++ Runs and jobs of a repository with synced Depot CI job attempts come from two tables each, so each+ time is the older of the two. Every row a read returns is then at least that fresh.+ """+ depot = _depot_job_attempts_by_repo(team, user_access_control).get(tables.repository.casefold())++ def watermark(github_synced_at: datetime | None) -> datetime | None:+ if depot is None:+ return github_synced_at+ if github_synced_at is None or depot.synced_at is None:+ return None+ return min(github_synced_at, depot.synced_at)++ return CIDataFreshness(+ runs_synced_at=watermark(tables.workflow_runs_synced_at),+ jobs_synced_at=watermark(tables.workflow_jobs_synced_at) if tables.workflow_jobs else None,+ )def depot_source_api_token(team: Team, source_id: str) -> str | None:@@ -562,10 +624,15 @@ def depot_source_job_attempts_table(team: Team, source: ExternalDataSource) -> sdef _synced_table_name(team: Team, source: ExternalDataSource, schema_name: str) -> str | None:"""The warehouse table a source syncs for ``schema_name``, or None. Only a plain identifierqualifies, because callers interpolate the name into HogQL."""+ schema = _synced_schema(team, source, schema_name)+ return schema.table.name if schema is not None and schema.table is not None else None+++def _synced_schema(team: Team, source: ExternalDataSource, schema_name: str) -> ExternalDataSchema | None:for schema in _synced_schemas(team=team, source=source):table = schema.tableif schema.name == schema_name and table is not None and not table.deleted and _IDENTIFIER.match(table.name):- return table.name+ return schemareturn None@@ -590,6 +657,8 @@ def _synced_tables_by_repo(*, team: Team, source: ExternalDataSource) -> dict[stlegacy_repo = _source_repository(source) or Noneby_repo: dict[str, dict[str, str]] = {}team_requests_by_repo: dict[str, bool] = {}+ run_columns_by_repo: dict[str, frozenset[str]] = {}+ synced_at_by_repo: dict[str, dict[str, datetime | None]] = {}for schema in _synced_schemas(team=team, source=source):repository, endpoint = github_schema_repo_endpoint(schema.schema_metadata, schema.name, legacy_repo)if endpoint not in _CURATED_ENDPOINTS:@@ -597,10 +666,20 @@ def _synced_tables_by_repo(*, team: Team, source: ExternalDataSource) -> dict[sttable = schema.tableif table is not None and not table.deleted and _IDENTIFIER.match(table.name):by_repo.setdefault(repository or "", {})[endpoint] = table.name- # Set together with the table name, so a later schema row for the same endpoint replaces both.+ # Set together with the table name, so a later schema row for the same endpoint replaces all of them.+ synced_at_by_repo.setdefault(repository or "", {})[endpoint] = schema.last_synced_atif endpoint == ISSUE_EVENTS_SCHEMA:team_requests_by_repo[repository or ""] = REQUESTED_TEAM_COLUMN in (table.columns or {})+ if endpoint == WORKFLOW_RUNS_SCHEMA:+ run_columns_by_repo[repository or ""] = frozenset(OPTIONAL_WORKFLOW_RUNS_COLUMNS) & frozenset(+ table.columns or {}+ )return {- repository: _RepoTables(names=names, issue_events_team_requests=team_requests_by_repo.get(repository, False))+ repository: _RepoTables(+ names=names,+ issue_events_team_requests=team_requests_by_repo.get(repository, False),+ workflow_runs_optional_columns=run_columns_by_repo.get(repository, frozenset()),+ synced_at=synced_at_by_repo.get(repository, {}),+ )for repository, names in by_repo.items()}diff --git a/products/engineering_analytics/backend/logic/views/depot_ci.py b/products/engineering_analytics/backend/logic/views/depot_ci.pyindex 6f02ccc3e65d..61e25e9084eb 100644--- a/products/engineering_analytics/backend/logic/views/depot_ci.py+++ b/products/engineering_analytics/backend/logic/views/depot_ci.py@@ -31,6 +31,7 @@ from products.engineering_analytics.backend.logic.queries._workflow_filters impo)from products.engineering_analytics.backend.logic.views import workflow_jobs, workflow_runsfrom products.engineering_analytics.backend.logic.views.source_schema import (+ OPTIONAL_WORKFLOW_RUNS_COLUMNS,WORKFLOW_JOBS_COLUMNS,WORKFLOW_RUNS_COLUMNS,)@@ -181,6 +182,8 @@ def _runs(attempts: str) -> str:concat('{{"id":{_REPOSITORY_ID},"full_name":"', any(repo), '"}}') AS repository,NULL AS head_commit,NULL AS actor,+ {OPTIONAL_WORKFLOW_RUNS_COLUMNS["workflow_id"]} AS workflow_id,+ {OPTIONAL_WORKFLOW_RUNS_COLUMNS["event"]} AS event,'depot_ci' AS ci_engine,any(native_run_id) AS native_run_id,any(native_workflow_run_id) AS native_workflow_run_id@@ -291,8 +294,14 @@ def _github_shells(jobs_table: str, runs_table: str, handoffs: str) -> str:# UNION ALL matches columns by position, so the GitHub selects name them in the contract order the# Depot side follows.-def _github_runs(table: str, where: str = "1") -> str:- return f"""SELECT {", ".join(WORKFLOW_RUNS_COLUMNS)}, 'github_actions' AS ci_engine,+def _github_runs(table: str, where: str = "1", optional_columns: frozenset[str] = frozenset()) -> str:+ columns = [+ column+ if column not in OPTIONAL_WORKFLOW_RUNS_COLUMNS or column in optional_columns+ else f"{OPTIONAL_WORKFLOW_RUNS_COLUMNS[column]} AS {column}"+ for column in WORKFLOW_RUNS_COLUMNS+ ]+ return f"""SELECT {", ".join(columns)}, 'github_actions' AS ci_engine,toString(id) AS native_run_id, toString(id) AS native_workflow_run_idFROM {table} WHERE {where}"""@@ -305,18 +314,25 @@ def _github_jobs(table: str, where: str = "1") -> str:def with_depot_runs(- runs_table: str, depot: DepotJobAttempts | None, pull_requests_table: str | None, jobs_table: str | None+ runs_table: str,+ depot: DepotJobAttempts | None,+ pull_requests_table: str | None,+ jobs_table: str | None,+ *,+ optional_columns: frozenset[str] = frozenset(),) -> str:"""The GitHub runs table, or a subquery that also holds the Depot CI runs when they are synced.Successful hand-off shells are left out. Without ``jobs_table`` the GitHub shells stay.+ ``optional_columns`` names the ``OPTIONAL_WORKFLOW_RUNS_COLUMNS`` that ``runs_table`` has. The+ others read as NULL."""if depot is None:- return f"({_github_runs(runs_table)})"+ return f"({_github_runs(runs_table, optional_columns=optional_columns)})"handoffs = _handoff_workflows(depot)where = f"id NOT IN ({_github_shells(jobs_table, runs_table, handoffs)})" if jobs_table else "1"depot_runs = _runs(_executed_attempts(depot, handoffs, pull_requests_table))- return f"({_github_runs(runs_table, where)} UNION ALL {depot_runs})"+ return f"({_github_runs(runs_table, where, optional_columns)} UNION ALL {depot_runs})"def with_depot_jobs(jobs_table: str, depot: DepotJobAttempts | None, runs_table: str) -> workflow_jobs.JobsTable:diff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.pyindex 52ff270cc9af..3ed36f4b3883 100644--- a/products/engineering_analytics/backend/logic/views/source_schema.py+++ b/products/engineering_analytics/backend/logic/views/source_schema.py@@ -61,6 +61,20 @@ WORKFLOW_RUNS_COLUMNS: dict[str, dict[str, str]] = {# pushed the branch cannot, which is what makes it the corroboration a merge-queue gate branch# is checked against before its name is trusted for attribution (see logic/merge_queue.py)."actor": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ # GitHub's numeric id of the workflow. It stays the same when the workflow's display name changes,+ # so it identifies a workflow across a rename.+ "workflow_id": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},+ # The event that triggered the run: 'push', 'pull_request', 'schedule', and so on.+ "event": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+}++# Runs columns that a synced table can lack, each with the typed NULL a read selects in its place. A+# query that names a column the table does not have fails, so the source resolver probes for these+# and ``views.depot_ci`` selects the NULL when one is absent. The Depot runs rows select the same+# NULLs, so both sides of the union agree on the column types.+OPTIONAL_WORKFLOW_RUNS_COLUMNS: dict[str, str] = {+ "workflow_id": "toInt(NULL)",+ "event": "nullIf('', '')",}# Contract for the incoming ``github_workflow_jobs`` warehouse source (job-level CI: queuediff --git a/products/engineering_analytics/backend/logic/views/workflow_runs.py b/products/engineering_analytics/backend/logic/views/workflow_runs.pyindex d1505e04ed4a..4c9624a4ff58 100644--- a/products/engineering_analytics/backend/logic/views/workflow_runs.py+++ b/products/engineering_analytics/backend/logic/views/workflow_runs.py@@ -170,12 +170,16 @@ def build_query(table_name: str, *, pull_requests_table: str | None = None, star{STOPPED_REPORTING_SQL} AS stopped_reporting,arrayElement(repo_parts, 1) AS repo_owner,arrayElement(repo_parts, 2) AS repo_name,- ci_engine, native_run_id, native_workflow_run_id+ ci_engine, native_run_id, native_workflow_run_id,+ workflow_id,+ eventFROM (SELECTid,name AS workflow_name,ci_engine, native_run_id, native_workflow_run_id,+ workflow_id,+ event,head_sha,head_branch,status,diff --git a/products/engineering_analytics/backend/logic/workflows.py b/products/engineering_analytics/backend/logic/workflows.pyindex 5cb7c2ec6077..73f1141be605 100644--- a/products/engineering_analytics/backend/logic/workflows.py+++ b/products/engineering_analytics/backend/logic/workflows.py@@ -1,6 +1,7 @@"""Workflow/run/job-scoped orchestration: health, activity, jobs, costs, and repo-level state."""from products.engineering_analytics.backend.facade.contracts import (+ CIDataFreshness,CIEngine,CurrentBranchHealth,MasterFailureGroup,@@ -51,6 +52,10 @@ def build_workflow_jobs(return query_workflow_jobs(curated=curated, run_id=run_id, ci_engine=ci_engine, run_attempt=run_attempt)+def build_ci_data_freshness(*, curated: CuratedGitHubSource) -> CIDataFreshness:+ return curated.ci_data_freshness()++def _parse_run_scope(value: str | None) -> WorkflowHealthRunScope:"""Absent/blank selects 'all'; anything else must be an exact enum value (ValueError → 400)."""normalized = value.strip() if value else ""diff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.pyindex ae80d83d0124..ad10a05218d8 100644--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py@@ -119,6 +119,11 @@ def _synthetic_repo_id(full_name: str) -> int:return zlib.crc32(full_name.encode())+def _synthetic_event(head_branch: str) -> str:+ pushed = head_branch in ("master", "main") or head_branch.startswith("trunk-merge/")+ return "push" if pushed else "pull_request"++def _flatten_run(run: dict[str, Any]) -> dict[str, Any]:json_keys = ("repository", "pull_requests", "head_commit", "actor")scalar_keys = [key for key in WORKFLOW_RUNS_COLUMNS if key not in json_keys]@@ -135,6 +140,10 @@ def _flatten_run(run: dict[str, Any]) -> dict[str, Any]:return {# .get() tolerates a pre-existing fixture captured before run_attempt / pull_requests were added.**{key: run.get(key) for key in scalar_keys},+ # The fixture snapshot and the synthetic rows carry no workflow id or trigger event. A real run of+ # a branch push is a 'push', and a merge queue pushes its gate branches too.+ "workflow_id": run.get("workflow_id") or zlib.crc32(str(run.get("name") or "").encode()),+ "event": run.get("event") or _synthetic_event(str(run.get("head_branch") or "")),"repository": json.dumps(repository),"pull_requests": json.dumps(associations),"head_commit": json.dumps(run.get("head_commit", {})),diff --git a/products/engineering_analytics/backend/presentation/serializers/workflows.py b/products/engineering_analytics/backend/presentation/serializers/workflows.pyindex 9915e99cf92f..26008cfbcf23 100644--- a/products/engineering_analytics/backend/presentation/serializers/workflows.py+++ b/products/engineering_analytics/backend/presentation/serializers/workflows.py@@ -1,12 +1,24 @@"""Payloads for workflow/run/job-scoped reads: health, activity, jobs, costs, and master state."""+from typing import Any++from rest_framework import serializersfrom rest_framework_dataclasses.serializers import DataclassSerializerfrom products.engineering_analytics.backend.facade.contracts import (+ CI_TIMING_MAX_JOB_IDS,+ CIDataFreshness,+ CIEngine,+ CITimingContext,+ CITimingKind,+ CITimingSample,CostPerMergeBucket,CurrentBranchHealth,DeliveryPipeline,DeliveryStageTiming,+ JobLogBadge,+ JobLogInsights,+ JobStepLogBadges,MasterFailureGroup,OpenToMergeBucket,PassRateBucket,@@ -77,6 +89,17 @@ class WorkflowRunDetailSerializer(DataclassSerializer):"help_text": "True when a merge queue pushed this run to gate pr_number, rather than the author ""pushing it. Count it when measuring CI; drop it when counting what the author did."},+ "workflow_id": {+ "help_text": "GitHub's numeric id of the workflow. It stays the same when the workflow is renamed, "+ "so use it to follow one workflow over time. Null for a Depot CI run, and for a run whose source "+ "does not carry the id.",+ "allow_null": True,+ },+ "event": {+ "help_text": "Event that triggered the run, such as 'push', 'pull_request' or 'schedule'. Null when "+ "unknown, as for a Depot CI run.",+ "allow_null": True,+ },}@@ -185,6 +208,229 @@ class WorkflowJobSerializer(DataclassSerializer):}+class JobLogInsightsQuerySerializer(serializers.Serializer):+ repo = serializers.CharField(help_text="'owner/name' repository the job ran in.")+ run_id = serializers.IntegerField(help_text="Workflow run id the job belongs to.")+ job_id = serializers.IntegerField(help_text="Job id to read the log of; a row id from workflow_jobs.")+ ci_engine = serializers.ChoiceField(+ choices=CIEngine.choices,+ required=False,+ help_text="CI engine. Required when job_id exists in both engines. Only GitHub Actions job logs are read.",+ )+ source_id = serializers.UUIDField(+ required=False,+ help_text="Connected GitHub data warehouse source to read from. Defaults to the source connected for `repo`.",+ )+++class JobLogBadgeSerializer(DataclassSerializer):+ class Meta:+ dataclass = JobLogBadge+ extra_kwargs = {+ "kind": {"help_text": "What the badge is about: a dependency cache, or migrations."},+ "state": {+ "help_text": "What happened. For a cache: 'hit' (exact key restored), 'partial' (an older cache "+ "restored from a restore key), 'miss' (nothing restored), 'failed' (the restore itself failed). For "+ "migrations: 'none' (nothing to apply) or 'applied'.",+ },+ "count": {"help_text": "How many times the log reports this outcome."},+ "detail": {+ "help_text": "What each occurrence was about: a cache key or a migration name. Capped, so it can "+ "hold fewer entries than `count`.",+ },+ }+++class JobStepLogBadgesSerializer(DataclassSerializer):+ badges = JobLogBadgeSerializer(many=True, help_text="What the log says this step did.")++ class Meta:+ dataclass = JobStepLogBadges+ extra_kwargs = {+ "number": {"help_text": "The step's number in the job, matching `number` of the job's steps."},+ }+++class JobLogInsightsSerializer(DataclassSerializer):+ job = JobLogBadgeSerializer(many=True, help_text="Every badge found in the log, for the job as a whole.")+ steps = JobStepLogBadgesSerializer(+ many=True,+ help_text="The same badges per step. Only steps with a badge are listed. Empty when `attributed_to_steps` "+ "is false.",+ )++ class Meta:+ dataclass = JobLogInsights+ extra_kwargs = {+ "log_read": {+ "help_text": "False when no log was read: a Depot CI job, a job the source does not hold, a log "+ "GitHub no longer keeps, or a failed fetch. Empty badges then mean 'unknown', not 'nothing found'.",+ },+ "attributed_to_steps": {+ "help_text": "False when the log's step markers did not line up with the job's steps, so the "+ "badges are reported for the job only.",+ },+ "log_truncated": {+ "help_text": "True when only part of the log was parsed, because the log is too large or its "+ "download took too long. The badges are then a lower bound: an outcome in the part that was not "+ "parsed is missing.",+ },+ }+++class CIDataFreshnessQuerySerializer(serializers.Serializer):+ repo = serializers.CharField(help_text="'owner/name' repository to report on.")+ source_id = serializers.UUIDField(+ required=False,+ help_text="Connected GitHub data warehouse source to read from. Defaults to the source connected for `repo`.",+ )+++class CIDataFreshnessSerializer(DataclassSerializer):+ class Meta:+ dataclass = CIDataFreshness+ extra_kwargs = {+ "runs_synced_at": {+ "help_text": "When the last completed sync of the stored workflow runs started. Every stored run is "+ "at least this fresh. The older of the GitHub and Depot CI times when the repository syncs both. "+ "Null when a runs table has never synced.",+ "allow_null": True,+ },+ "jobs_synced_at": {+ "help_text": "The same time for the stored workflow jobs. Null when jobs are not synced.",+ "allow_null": True,+ },+ }+++class CITimingContextQuerySerializer(serializers.Serializer):+ repo = serializers.CharField(help_text="'owner/name' repository the run belongs to.")+ source_id = serializers.UUIDField(+ required=False,+ help_text="Connected GitHub data warehouse source to read from. Defaults to the source connected for `repo`.",+ )+ ci_engine = serializers.ChoiceField(choices=CIEngine.choices, help_text="CI engine that ran the run.")+ run_id = serializers.IntegerField(help_text="Integer run id of the run that holds the selection.")+ run_attempt = serializers.IntegerField(min_value=1, help_text="Run attempt that holds the selection.")+ kind = serializers.ChoiceField(+ choices=CITimingKind.choices,+ help_text="What to compare: the whole 'workflow', a 'matrix' (several jobs of the run), one 'job', or one "+ "'step' of a job.",+ )+ job_ids = serializers.CharField(+ required=False,+ help_text=f"Comma-separated job ids from workflow_jobs, at most {CI_TIMING_MAX_JOB_IDS}. Required for 'matrix', 'job' "+ "and 'step'. Give exactly one id for 'job' and 'step'. Ignored for 'workflow'.",+ )+ step_number = serializers.IntegerField(+ required=False, help_text="Number of the step within the job. Required when kind is 'step'."+ )++ def validate_job_ids(self, value: str) -> list[int]:+ parts = [part.strip() for part in value.split(",") if part.strip()]+ if len(parts) > CI_TIMING_MAX_JOB_IDS:+ raise serializers.ValidationError(f"Give at most {CI_TIMING_MAX_JOB_IDS} job ids.")+ try:+ return [int(part) for part in parts]+ except ValueError:+ raise serializers.ValidationError("Give job ids as comma-separated integers.") from None++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ kind = attrs["kind"]+ job_ids = attrs.get("job_ids") or []+ if kind != CITimingKind.WORKFLOW and not job_ids:+ raise serializers.ValidationError({"job_ids": f"Give at least one job id when kind is '{kind}'."})+ if kind in (CITimingKind.JOB, CITimingKind.STEP) and len(job_ids) != 1:+ raise serializers.ValidationError({"job_ids": f"Give exactly one job id when kind is '{kind}'."})+ if kind == CITimingKind.STEP and attrs.get("step_number") is None:+ raise serializers.ValidationError({"step_number": "Give a step number when kind is 'step'."})+ return attrs+++class CITimingSampleSerializer(DataclassSerializer):+ class Meta:+ dataclass = CITimingSample+ extra_kwargs = {+ "ci_engine": {"help_text": "CI engine that ran the sampled run."},+ "status": {+ "help_text": "'success' when every matched job succeeded, or the matched step did. Otherwise "+ "'failure'.",+ },+ "run_id": {"help_text": "Integer run id of the sampled run; unique only together with ci_engine."},+ "run_attempt": {"help_text": "Run attempt the sample was taken from, which is the run's latest."},+ "job_id": {+ "help_text": "Job id of the matched job. Null for a workflow or matrix sample, which spans jobs.",+ "allow_null": True,+ },+ "step_number": {+ "help_text": "Number of the matched step in the sampled job. Steps match by name, so it can differ "+ "from the selected step's number. Null unless kind is 'step'.",+ "allow_null": True,+ },+ "native_run_id": {"help_text": "Source-native run id; use with ci_engine to link to the run."},+ "native_workflow_run_id": {+ "help_text": "Source-native workflow run id; use with ci_engine to link to the run."+ },+ "native_job_id": {+ "help_text": "Source-native job id of the matched job. Null for a workflow or matrix sample."+ },+ "native_attempt_id": {+ "help_text": "Source-native job attempt id of the matched job. Null for a workflow or matrix sample."+ },+ "duration_seconds": {+ "help_text": "For a workflow, matrix or job: seconds from the first matched job's start to the last "+ "one's end. For a step: the step's own duration."+ },+ "completed_at": {"help_text": "When the last matched job finished."},+ "head_sha": {"help_text": "Commit SHA the sampled run ran on."},+ }+++class CITimingContextSerializer(DataclassSerializer):+ recent = CITimingSampleSerializer(+ many=True, help_text="The newest matched samples of any status, newest first. At most three."+ )++ class Meta:+ dataclass = CITimingContext+ extra_kwargs = {+ "identity": {+ "help_text": "How runs of the same workflow were found: by 'workflow_id', which a rename keeps, or "+ "by 'workflow_name' when the run has no workflow id.",+ },+ "unavailable_reason": {+ "help_text": "Why no comparison was made: 'default_branch_unknown' (no synced pull request names the "+ "repository's default branch), 'jobs_not_synced', or 'not_executed' (every selected job was skipped, "+ "so there is no duration to compare). Null when the comparison ran, even if it found no samples.",+ "allow_null": True,+ },+ "default_branch": {+ "help_text": "The repository's default branch, which the samples ran on. Null when unknown.",+ "allow_null": True,+ },+ "window_days": {"help_text": "How many days back the comparison looks."},+ "runs_scanned": {"help_text": "How many default-branch runs of the workflow were checked for a match."},+ "sampled": {+ "help_text": "True when the window held more eligible runs than were checked, so the figures cover "+ "the newest runs only."+ },+ "sample_count": {"help_text": "How many checked runs matched the selection and succeeded."},+ "average_seconds": {+ "help_text": "Mean duration of the successful samples, in seconds. Null when there are none. A run "+ "counts only when it ran the same jobs on the same runners, so a null means no comparable run.",+ "allow_null": True,+ },+ "runs_synced_at": {+ "help_text": "When the last completed sync of the stored workflow runs started. Null when unknown.",+ "allow_null": True,+ },+ "jobs_synced_at": {+ "help_text": "When the last completed sync of the stored workflow jobs started. Null when unknown.",+ "allow_null": True,+ },+ }++class WorkflowRunnerCostSerializer(DataclassSerializer):class Meta:dataclass = WorkflowRunnerCostdiff --git a/products/engineering_analytics/backend/presentation/views/workflows.py b/products/engineering_analytics/backend/presentation/views/workflows.pyindex 0f068088f2f6..2b6755889aa0 100644--- a/products/engineering_analytics/backend/presentation/views/workflows.py+++ b/products/engineering_analytics/backend/presentation/views/workflows.py@@ -7,10 +7,18 @@ from rest_framework.decorators import actionfrom rest_framework.request import Requestfrom rest_framework.response import Response+from posthog.api.mixins import ValidatedRequest, validated_request+from products.engineering_analytics.backend.facade import api-from products.engineering_analytics.backend.facade.contracts import CIEngine+from products.engineering_analytics.backend.facade.contracts import CIEngine, CITimingKindfrom products.engineering_analytics.backend.presentation.serializers.workflows import (+ CIDataFreshnessQuerySerializer,+ CIDataFreshnessSerializer,+ CITimingContextQuerySerializer,+ CITimingContextSerializer,CurrentBranchHealthSerializer,+ JobLogInsightsQuerySerializer,+ JobLogInsightsSerializer,MasterFailureGroupSerializer,RepoOverviewSerializer,RunFailureLogsSerializer,@@ -55,6 +63,9 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):"workflow_run_activity","workflow_runner_costs","workflow_jobs",+ "job_log_insights",+ "ci_data_freshness",+ "ci_timing_context","repo_overview","current_branch_health","repo_run_activity",@@ -367,6 +378,111 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):return _bad_request(exc, fallback="Invalid source_id")return Response(WorkflowJobSerializer(instance=jobs, many=True).data)+ @validated_request(+ query_serializer=JobLogInsightsQuerySerializer,+ operation_id="engineering_analytics_job_log_insights",+ responses={+ 200: OpenApiResponse(response=JobLogInsightsSerializer),+ 400: OpenApiResponse(+ description="Missing or invalid repo, run_id, job_id, ci_engine or source_id, or an ambiguous job_id."+ ),+ },+ description=(+ "What one GitHub Actions job's log says it did: cache restores (hit, older cache, miss, restore failed) "+ "and migrations applied, for the job and per step. Reads the log from GitHub on demand. Only a completed "+ "job's answer is cached. `log_read` is false, never an error, when there is no log to read: a Depot CI "+ "job, a job the source does not hold, an expired log, or a failed fetch."+ ),+ )+ @action(detail=False, methods=["get"], pagination_class=None)+ def job_log_insights(self, request: ValidatedRequest, **kwargs) -> Response:+ query = request.validated_query_data+ source_id = query.get("source_id")+ try:+ insights = api.get_job_log_insights(+ team=self.team,+ repo=query["repo"],+ run_id=query["run_id"],+ job_id=query["job_id"],+ ci_engine=CIEngine(query["ci_engine"]) if query.get("ci_engine") else None,+ source_id=str(source_id) if source_id else None,+ user_access_control=self.user_access_control,+ )+ except ValueError as exc:+ return _bad_request(exc, fallback="Invalid repo or source_id")+ return Response(JobLogInsightsSerializer(instance=insights).data)++ @validated_request(+ query_serializer=CIDataFreshnessQuerySerializer,+ operation_id="engineering_analytics_ci_data_freshness",+ responses={+ 200: OpenApiResponse(response=CIDataFreshnessSerializer),+ 400: OpenApiResponse(description="Missing or invalid repo or source_id."),+ },+ description=(+ "When the stored CI data of a repository was last synced from its source: one time for workflow runs "+ "and one for workflow jobs. Every stored row is at least that fresh, so use these times, not the time "+ "of the request, to say how current a CI answer is. Each time is when the last completed sync started. "+ "For a repository that also syncs Depot CI, it is the older of the GitHub and the Depot CI time."+ ),+ )+ @action(detail=False, methods=["get"], pagination_class=None)+ def ci_data_freshness(self, request: ValidatedRequest, **kwargs) -> Response:+ query = request.validated_query_data+ source_id = query.get("source_id")+ try:+ freshness = api.get_ci_data_freshness(+ team=self.team,+ repo=query["repo"],+ source_id=str(source_id) if source_id else None,+ user_access_control=self.user_access_control,+ )+ except ValueError as exc:+ return _bad_request(exc, fallback="Invalid repo or source_id")+ return Response(CIDataFreshnessSerializer(instance=freshness).data)++ @validated_request(+ query_serializer=CITimingContextQuerySerializer,+ operation_id="engineering_analytics_ci_timing_context",+ responses={+ 200: OpenApiResponse(response=CITimingContextSerializer),+ 400: OpenApiResponse(+ description="Missing or invalid parameters, a run the source does not hold, a job id that is not "+ "in the run attempt, or a step number the job does not have."+ ),+ },+ description=(+ "How long a selected workflow, matrix, job or step usually takes: compares it with runs of the same "+ "workflow on the repository's default branch over the last 7 days, from stored data only. A run "+ "counts only when it ran the same jobs on the same runner tiers, so the answer never mixes in a "+ "different workflow, job or runner. Pull request runs and merge queue runs are left out. At most the "+ "newest 40 default-branch runs are checked, and `sampled` is true when more existed. `average_seconds` "+ "and `sample_count` cover successful samples only, and `recent` lists the newest three matches of any "+ "status. `average_seconds` is null when no comparable run exists. `unavailable_reason` says why no "+ "comparison was made. Answers are cached for 5 minutes."+ ),+ )+ @action(detail=False, methods=["get"], pagination_class=None)+ def ci_timing_context(self, request: ValidatedRequest, **kwargs) -> Response:+ query = request.validated_query_data+ source_id = query.get("source_id")+ try:+ context = api.get_ci_timing_context(+ team=self.team,+ repo=query["repo"],+ ci_engine=CIEngine(query["ci_engine"]),+ run_id=query["run_id"],+ run_attempt=query["run_attempt"],+ kind=CITimingKind(query["kind"]),+ job_ids=query.get("job_ids") or [],+ step_number=query.get("step_number"),+ source_id=str(source_id) if source_id else None,+ user_access_control=self.user_access_control,+ )+ except ValueError as exc:+ return _bad_request(exc, fallback="Invalid repo, source_id or selection")+ return Response(CITimingContextSerializer(instance=context).data)+@extend_schema(operation_id="engineering_analytics_repo_overview",parameters=[diff --git a/products/engineering_analytics/backend/tests/_github_fixtures.py b/products/engineering_analytics/backend/tests/_github_fixtures.pyindex 088180eb9e0d..0f8e69a10b10 100644--- a/products/engineering_analytics/backend/tests/_github_fixtures.py+++ b/products/engineering_analytics/backend/tests/_github_fixtures.py@@ -296,10 +296,14 @@ def _run_row(head_branch: str = "main",commit_message: str | None = None,actor: str = "alice",+ workflow_id: int | None = None,+ event: str | None = None,) -> dict[str, Any]:return {"id": run_id,"name": name,+ "workflow_id": workflow_id,+ "event": event,"head_sha": head_sha,"head_branch": head_branch,"status": status,diff --git a/products/engineering_analytics/backend/tests/test_ci_timing_context.py b/products/engineering_analytics/backend/tests/test_ci_timing_context.pynew file mode 100644index 000000000000..c139525471d9--- /dev/null+++ b/products/engineering_analytics/backend/tests/test_ci_timing_context.py@@ -0,0 +1,131 @@+from datetime import UTC, datetime, timedelta++from django.test import SimpleTestCase++from parameterized import parameterized++from products.engineering_analytics.backend.facade.contracts import (+ CIEngine,+ CITimingKind,+ CITimingSampleStatus,+ WorkflowJob,+ WorkflowJobStep,+)+from products.engineering_analytics.backend.logic.ci_timing_context import match_timing_sample, select_timing_jobs+from products.engineering_analytics.backend.logic.queries.timing_candidates import TimingCandidateRun++_START = datetime(2026, 3, 2, 12, tzinfo=UTC)+++def _step(number: int, name: str, seconds: int, conclusion: str = "success") -> WorkflowJobStep:+ return WorkflowJobStep(+ number=number,+ name=name,+ status="completed",+ conclusion=conclusion,+ started_at=_START,+ completed_at=_START + timedelta(seconds=seconds),+ duration_seconds=seconds,+ )+++def _job(+ job_id: int,+ name: str,+ *,+ seconds: int = 120,+ conclusion: str = "success",+ runner_label: str = "4-core",+ steps: list[WorkflowJobStep] | None = None,+) -> WorkflowJob:+ return WorkflowJob(+ id=job_id,+ run_id=1,+ name=name,+ status="completed",+ conclusion=conclusion,+ started_at=_START,+ completed_at=_START + timedelta(seconds=seconds),+ duration_seconds=seconds,+ runner_provider="self_hosted",+ runner_label=runner_label,+ estimated_cost_usd=None,+ steps=steps or [],+ )+++_CURRENT_JOBS = [_job(1, "build", steps=[_step(1, "Set up job", 5), _step(2, "Run tests", 90)]), _job(2, "lint")]+_CANDIDATE_RUN = TimingCandidateRun(+ run_id=900,+ run_attempt=1,+ ci_engine=CIEngine.GITHUB_ACTIONS,+ head_sha="sha900",+ run_started_at=_START,+ native_run_id="900",+ native_workflow_run_id="900",+)+_SUCCESS = CITimingSampleStatus.SUCCESS+_FAILURE = CITimingSampleStatus.FAILURE+++class TestMatchTimingSample(SimpleTestCase):+ @parameterized.expand(+ [+ ("job_same_runner", CITimingKind.JOB, [_job(11, "build", seconds=100)], (100.0, _SUCCESS, 11, None)),+ ("job_failed", CITimingKind.JOB, [_job(11, "build", conclusion="failure")], (120.0, _FAILURE, 11, None)),+ ("job_other_runner", CITimingKind.JOB, [_job(11, "build", runner_label="16-core")], None),+ (+ "workflow_same_job_set",+ CITimingKind.WORKFLOW,+ [_job(11, "build", seconds=100), _job(12, "lint", seconds=300)],+ (300.0, _SUCCESS, None, None),+ ),+ ("workflow_changed_job_set", CITimingKind.WORKFLOW, [_job(11, "build")], None),+ ("matrix_changed_job_set", CITimingKind.MATRIX, [_job(11, "build")], None),+ ("job_in_changed_job_set", CITimingKind.JOB, [_job(11, "build")], (120.0, _SUCCESS, 11, None)),+ (+ "workflow_ignores_cancelled_and_skipped_jobs",+ CITimingKind.WORKFLOW,+ [+ _job(11, "build"),+ _job(12, "lint"),+ _job(13, "deploy", conclusion="skipped"),+ _job(14, "build", conclusion="cancelled", seconds=3),+ ],+ (120.0, _SUCCESS, None, None),+ ),+ (+ "step_by_name_at_another_number",+ CITimingKind.STEP,+ [+ _job(+ 11,+ "build",+ steps=[_step(1, "Set up job", 5), _step(2, "Checkout", 3), _step(3, "Run tests", 70)],+ )+ ],+ (70.0, _SUCCESS, 11, 3),+ ),+ (+ "step_name_twice_in_job",+ CITimingKind.STEP,+ [_job(11, "build", steps=[_step(2, "Run tests", 70), _step(3, "Run tests", 80)])],+ None,+ ),+ ]+ )+ def test_samples_only_the_same_work(+ self,+ _name: str,+ kind: CITimingKind,+ candidate_jobs: list[WorkflowJob],+ expected: tuple[float, CITimingSampleStatus, int | None, int | None] | None,+ ) -> None:+ selection = select_timing_jobs(+ _CURRENT_JOBS, kind=kind, job_ids=[1], step_number=2 if kind is CITimingKind.STEP else None+ )+ assert selection is not None++ sample = match_timing_sample(_CANDIDATE_RUN, candidate_jobs, selection)++ assert (sample and (sample.duration_seconds, sample.status, sample.job_id, sample.step_number)) == expecteddiff --git a/products/engineering_analytics/backend/tests/test_logic_sources.py b/products/engineering_analytics/backend/tests/test_logic_sources.pyindex ce3cc1d47e97..e9a68f6d7962 100644--- a/products/engineering_analytics/backend/tests/test_logic_sources.py+++ b/products/engineering_analytics/backend/tests/test_logic_sources.py@@ -1,3 +1,4 @@+from datetime import UTC, datetime, timedeltafrom typing import Anyfrom posthog.test.base import BaseTest@@ -19,6 +20,7 @@ from products.engineering_analytics.backend.logic.sources import (JobSourceTables,TeamMembershipTable,list_github_sources,+ resolve_ci_data_freshness,resolve_github_tables,resolve_job_source_tables,resolve_team_membership_table,@@ -38,6 +40,8 @@ from products.engineering_analytics.backend.tests._logic_helpers import _ago, _Wfrom products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSourcefrom products.warehouse_sources.backend.facade.types import ExternalDataSourceType+_SYNCED_AT = datetime(2026, 3, 2, 12, tzinfo=UTC)+class TestResolveGitHubTables(BaseTest):"""The per-team table resolver over the warehouse models (ORM only, no object storage).@@ -50,6 +54,7 @@ class TestResolveGitHubTables(BaseTest):schemas: list[tuple[str, bool, bool]],source_type: ExternalDataSourceType = ExternalDataSourceType.GITHUB,team: Team | None = None,+ repository: str = "",) -> ExternalDataSource:# schemas: (endpoint name, should_sync, has a backing table)team = team or self.team@@ -60,6 +65,7 @@ class TestResolveGitHubTables(BaseTest):status=ExternalDataSource.Status.COMPLETED,source_type=source_type,prefix=prefix,+ job_inputs={"repository": repository} if repository else None,)for name, should_sync, has_table in schemas:table = (@@ -95,6 +101,37 @@ class TestResolveGitHubTables(BaseTest):assert (tables.issue_events, tables.issue_events_team_requests) == ("flaggithub_issue_events", expected)+ @parameterized.expand(+ [+ ("github_only", None, False, _SYNCED_AT),+ ("depot_synced_earlier", _SYNCED_AT - timedelta(hours=2), True, _SYNCED_AT - timedelta(hours=2)),+ ("depot_synced_later", _SYNCED_AT + timedelta(hours=2), True, _SYNCED_AT),+ ("depot_never_synced", None, True, None),+ ]+ )+ def test_ci_data_freshness_is_the_older_of_the_github_and_depot_syncs(+ self, _name: str, depot_synced_at: datetime | None, has_depot: bool, expected: datetime | None+ ) -> None:+ source = self._connect(+ prefix="fresh",+ schemas=[*self._BOTH_SYNCED, (WORKFLOW_JOBS_SCHEMA, True, True)],+ repository="PostHog/posthog",+ )+ ExternalDataSchema.objects.filter(source=source).update(last_synced_at=_SYNCED_AT)+ if has_depot:+ depot = create_depot_source(self.team, prefix="ci", repository="posthog/PostHog")+ schema = link_schema(+ self.team,+ depot,+ name=DEPOT_JOB_ATTEMPTS_SCHEMA,+ table=create_warehouse_table_row(self.team, name="cidepot_job_attempts", source=depot),+ )+ ExternalDataSchema.objects.filter(id=schema.id).update(last_synced_at=depot_synced_at)++ freshness = resolve_ci_data_freshness(team=self.team, tables=resolve_github_tables(team=self.team))++ assert (freshness.runs_synced_at, freshness.jobs_synced_at) == (expected, expected)+@parameterized.expand([# GitHub's documented member object omits role, so probing keeps the roster read off adiff --git a/products/engineering_analytics/backend/tests/test_logic_workflows.py b/products/engineering_analytics/backend/tests/test_logic_workflows.pyindex 29c3d3399938..384b7545ebdd 100644--- a/products/engineering_analytics/backend/tests/test_logic_workflows.py+++ b/products/engineering_analytics/backend/tests/test_logic_workflows.py@@ -13,12 +13,19 @@ from parameterized import parameterizedfrom posthog.hogql.database.database import Databasefrom products.engineering_analytics.backend.facade import api-from products.engineering_analytics.backend.facade.contracts import CIEngine, DeliveryStage+from products.engineering_analytics.backend.facade.contracts import (+ CIEngine,+ CITimingContext,+ CITimingKind,+ CITimingSample,+ DeliveryStage,+)from products.engineering_analytics.backend.logic import build_workflow_healthfrom products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSourcefrom products.engineering_analytics.backend.logic.queries._workflow_filters import UNPAGED_SCAN_LIMITfrom products.engineering_analytics.backend.logic.queries.pr_cost import query_cost_per_merge_series, query_pr_costfrom products.engineering_analytics.backend.logic.queries.workflow_flakiness import query_workflow_flakiness+from products.engineering_analytics.backend.logic.queries.workflow_jobs import query_workflow_jobfrom products.engineering_analytics.backend.logic.sources import GitHubTablesfrom products.engineering_analytics.backend.logic.views.source_schema import (ISSUE_EVENTS_COLUMNS,@@ -58,6 +65,37 @@ class TestWorkflowEndpointMapping(BaseTest):super().setUp()connect_github_source_without_data(self.team)+ @parameterized.expand(+ [+ # Depot CI lists a job that a later attempt did not re-run under that attempt too, with the same id.+ ("depot_job_listed_under_two_attempts", [(1, 0, "depot_ci"), (2, 1, "depot_ci")], "attempt-1"),+ ("one_id_in_two_engines", [(1, 0, "depot_ci"), (1, 0, "github_actions")], None),+ ]+ )+ def test_workflow_job_lookup_is_ambiguous_only_across_engines(+ self, _name: str, listings: list[tuple[int, int, str]], native_attempt_id: str | None+ ) -> None:+ started = _dt("2026-01-05T10:00:00")+ rows = [+ # Mirrors the SELECT column order of the jobs query.+ (+ *(91000, 9100, attempt, "build", "completed", "success", "[]", "", started, started, 0, None, is_copy),+ *(engine, "run", "workflow", "job", f"attempt-{attempt}", "[]"),+ )+ for attempt, is_copy, engine in listings+ ]+ curated = CuratedGitHubSource(+ team=self.team, tables=GitHubTables(pull_requests="prs", workflow_runs="runs", workflow_jobs="jobs")+ )++ with mock.patch(_RUN_QUERY, return_value=_resp(rows)):+ if native_attempt_id is None:+ with pytest.raises(ValueError, match="Ambiguous job_id"):+ query_workflow_job(curated=curated, run_id=9100, job_id=91000)+ else:+ job = query_workflow_job(curated=curated, run_id=9100, job_id=91000)+ assert job is not None and job.native_attempt_id == native_attempt_id+def test_current_branch_health_counts_every_workflow(self) -> None:workflow_rows = [(f"Workflow {index}", 1, 0) for index in range(100)]workflow_rows.extend((f"Low-volume failure {index:02d}", 1, 1) for index in range(21))@@ -907,7 +945,20 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):# The raw conclusion lets the UI retain the specific failure label while sharing the verdict.assert ci.latest_run_conclusion == conclusion- def test_workflow_run_detail_by_id(self) -> None:+ @parameterized.expand(+ [+ ("table_with_identity_columns", WORKFLOW_RUNS_COLUMNS, 4242, "pull_request"),+ (+ "table_synced_before_them",+ {key: value for key, value in WORKFLOW_RUNS_COLUMNS.items() if key not in ("workflow_id", "event")},+ None,+ None,+ ),+ ]+ )+ def test_workflow_run_detail_by_id(+ self, _name: str, run_columns: dict[str, dict[str, str]], workflow_id: int | None, event: str | None+ ) -> None:# The run detail page fetches one run by id; re-runs share the id, so the latest attempt wins.self._create_table("github_pull_requests",@@ -916,10 +967,20 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):)self._create_table("github_workflow_runs",- WORKFLOW_RUNS_COLUMNS,+ run_columns,[_run_row(- 7777, "CI", "sha42", "completed", "failure", _ago(2), _ago(2), head_branch="master", pr_number=42+ 7777,+ "CI",+ "sha42",+ "completed",+ "failure",+ _ago(2),+ _ago(2),+ head_branch="master",+ pr_number=42,+ workflow_id=4242,+ event="pull_request",),_run_row(7777,@@ -932,11 +993,14 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):head_branch="master",pr_number=42,run_attempt=2,+ workflow_id=4242,+ event="pull_request",),],)run = api.get_workflow_run(team=self.team, run_id=7777)assert run is not None+ assert (run.workflow_id, run.event) == (workflow_id, event)assert run.id == 7777assert run.workflow_name == "CI"assert run.run_attempt == 2 # latest attempt wins@@ -1170,6 +1234,111 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):main_activity = api.get_workflow_run_activity(team=self.team, repo=repo, workflow_name=workflow, branch="main")assert {p.run_id for p in main_activity.points} == {8501, 8502}+ @parameterized.expand(+ [+ ("job_not_rerun_in_the_latest_attempt", 1000, None, 1, 120.0, [201]),+ ("job_rerun_in_the_latest_attempt", 1001, None, 1, 40.0, [201]),+ ("job_no_default_branch_run_ran", 1002, None, 0, None, []),+ ("job_skipped_in_the_selected_run", 1003, "not_executed", 0, None, []),+ ]+ )+ def test_ci_timing_context_samples_only_default_branch_runs_of_the_workflow(+ self,+ _name: str,+ job_id: int,+ unavailable_reason: str | None,+ sample_count: int,+ average_seconds: float | None,+ recent_run_ids: list[int],+ ) -> None:+ self._create_table(+ "github_pull_requests",+ PULL_REQUESTS_COLUMNS,+ [_pr_row(70, "alice", "open", 0, _ago(1), head_sha="sha70", default_branch="master")],+ )++ def run(+ run_id: int,+ *,+ head_branch: str = "master",+ workflow_id: int = 11,+ event: str = "push",+ run_attempt: int = 1,+ ) -> dict:+ return _run_row(+ run_id,+ "CI",+ f"sha{run_id}",+ "completed",+ "success",+ _ago(1),+ _ago(1),+ head_branch=head_branch,+ workflow_id=workflow_id,+ event=event,+ run_attempt=run_attempt,+ )++ self._create_table(+ "github_workflow_runs",+ WORKFLOW_RUNS_COLUMNS,+ [+ run(100, head_branch="feature", event="pull_request"),+ run(201, run_attempt=2),+ # A fork pull request whose branch is named like the default branch.+ run(202, event="pull_request_target"),+ # Another workflow that has the same display name.+ run(203, workflow_id=22),+ ],+ )++ def job(+ job_id: int, run_id: int, name: str, seconds: int, *, conclusion: str = "success", run_attempt: int = 1+ ) -> dict:+ started, completed = _ago_with_duration(1, seconds)+ return _job_row(+ job_id, run_id, name, conclusion, started=started, completed=completed, run_attempt=run_attempt+ )++ self._create_table(+ "github_workflow_jobs",+ WORKFLOW_JOBS_COLUMNS,+ [+ job(1000, 100, "build", 300),+ job(1001, 100, "lint", 30),+ job(1002, 100, "docs", 30),+ job(1003, 100, "deploy", 0, conclusion="skipped"),+ job(2010, 201, "build", 120),+ job(2011, 201, "lint", 50, conclusion="failure"),+ # The second attempt re-ran lint only, and GitHub lists build under it again.+ job(2012, 201, "build", 120, run_attempt=2),+ job(2013, 201, "lint", 40, run_attempt=2),+ job(2020, 202, "build", 600),+ job(2030, 203, "build", 900),+ ],+ )++ def read() -> CITimingContext:+ return api.get_ci_timing_context(+ team=self.team,+ repo="PostHog/posthog",+ ci_engine=CIEngine.GITHUB_ACTIONS,+ run_id=100,+ run_attempt=1,+ kind=CITimingKind.JOB,+ job_ids=[job_id],+ )++ context = read()++ assert (context.identity, context.unavailable_reason) == ("workflow_id", unavailable_reason)+ assert (context.sample_count, context.average_seconds) == (sample_count, average_seconds)+ assert [sample.run_id for sample in context.recent] == recent_run_ids+ if unavailable_reason is None:+ assert (context.default_branch, context.runs_scanned, context.sampled) == ("master", 1, False)+ assert read() == context+ assert all(isinstance(sample, CITimingSample) for sample in read().recent)+def test_workflow_jobs_optional_and_costed(self) -> None:# Jobs are an optional source: absent → graceful empty; present → costed per runner tier.self._create_table(diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.pyindex 19a042ff2bf2..49364e965499 100644--- a/products/engineering_analytics/backend/tests/test_presentation.py+++ b/products/engineering_analytics/backend/tests/test_presentation.py@@ -1,10 +1,13 @@+import dataclassesfrom datetime import UTC, datetimefrom posthog.test.base import APIBaseTestfrom unittest import mock+from django.core.cache import cachefrom django.test import SimpleTestCase+import requestsfrom parameterized import parameterizedfrom rest_framework import status@@ -13,6 +16,7 @@ from products.engineering_analytics.backend.logic.ci_signals_config import (AUTHORIZED_SOURCES_CONFIG_KEY,CI_SIGNAL_SOURCE_TYPES,)+from products.engineering_analytics.backend.logic.job_logs.fetcher import FetchedJobLogfrom products.engineering_analytics.backend.logic.signals.contracts import SOURCE_PRODUCTfrom products.engineering_analytics.backend.presentation.views import EngineeringAnalyticsViewSetfrom products.engineering_analytics.backend.tests._github_fixtures import (@@ -20,6 +24,7 @@ from products.engineering_analytics.backend.tests._github_fixtures import (create_github_source,)from products.signals.backend.models import SignalSourceConfig+from products.warehouse_sources.backend.facade.contracts import GitHubSourceCredentialclass TestScopeEnrollment(SimpleTestCase):@@ -230,6 +235,11 @@ def _workflow_job() -> contracts.WorkflowJob:)+_LOG_INSIGHTS = "products.engineering_analytics.backend.logic.job_log_insights"+_PAT = GitHubSourceCredential(personal_access_token="invented-token")+_TIMING_PARAMS = {"repo": "PostHog/posthog", "ci_engine": "github_actions", "run_id": "9100", "run_attempt": "1"}++class TestEngineeringAnalyticsAPI(APIBaseTest):@classmethoddef setUpTestData(cls) -> None:@@ -591,6 +601,100 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):@parameterized.expand([+ ("fetch_fails", contracts.CIEngine.GITHUB_ACTIONS, _PAT, requests.ConnectionError("unreachable"), 1),+ ("log_expired", contracts.CIEngine.GITHUB_ACTIONS, _PAT, None, 1),+ ("depot_job", contracts.CIEngine.DEPOT_CI, _PAT, None, 0),+ # The team's other GitHub credentials belong to sources this reader may not be allowed to use.+ ("source_without_a_credential", contracts.CIEngine.GITHUB_ACTIONS, None, None, 0),+ ]+ )+ def test_job_log_insights_reports_log_not_read(+ self,+ _name: str,+ engine: contracts.CIEngine,+ credential: GitHubSourceCredential | None,+ fetched: Exception | None,+ fetches: int,+ ) -> None:+ job = dataclasses.replace(_workflow_job(), ci_engine=engine)+ with (+ mock.patch(f"{_LOG_INSIGHTS}.query_workflow_job", return_value=job),+ mock.patch(f"{_LOG_INSIGHTS}.warehouse_sources.github_source_credential", return_value=credential),+ mock.patch(f"{_LOG_INSIGHTS}.fetch_bounded_job_log", side_effect=[fetched]) as fetch,+ mock.patch(f"{_LOG_INSIGHTS}.GitHubIntegration.first_for_team_repository") as other_credential,+ ):+ response = self.client.get(+ self._url("job_log_insights"), {"repo": "PostHog/posthog", "run_id": "9100", "job_id": "91000"}+ )++ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {+ "log_read": False,+ "attributed_to_steps": False,+ "job": [],+ "steps": [],+ "log_truncated": False,+ }+ assert fetch.call_count == fetches+ other_credential.assert_not_called()++ @parameterized.expand([("whole_log", False), ("part_of_the_log", True)])+ def test_job_log_insights_serves_a_completed_job_from_one_fetch(self, _name: str, truncated: bool) -> None:+ cache.clear()+ steps = [+ contracts.WorkflowJobStep(+ number=number,+ name=name,+ status="completed",+ conclusion="success",+ started_at=None,+ completed_at=None,+ duration_seconds=None,+ )+ for number, name in enumerate(["Set up job", "Restore packages", "Complete job"], start=1)+ ]+ job = dataclasses.replace(_workflow_job(), ci_engine=contracts.CIEngine.GITHUB_ACTIONS, steps=steps)+ log = FetchedJobLog(text="##[group]Run example/restore@v1\nCache hit for: packages-a1\n", truncated=truncated)+ with (+ mock.patch(f"{_LOG_INSIGHTS}.query_workflow_job", return_value=job),+ mock.patch(f"{_LOG_INSIGHTS}.warehouse_sources.github_source_credential", return_value=_PAT),+ mock.patch(f"{_LOG_INSIGHTS}.fetch_bounded_job_log", return_value=log) as fetch,+ ):+ params = {"repo": "PostHog/posthog", "run_id": "9100", "job_id": "91000"}+ first = self.client.get(self._url("job_log_insights"), params).json()+ second = self.client.get(self._url("job_log_insights"), params).json()++ hit = {"kind": "cache", "state": "hit", "count": 1, "detail": ["packages-a1"]}+ assert first == {+ "log_read": True,+ "attributed_to_steps": True,+ "job": [hit],+ "steps": [{"number": 2, "badges": [hit]}],+ "log_truncated": truncated,+ }+ assert second == first+ assert fetch.call_count == 1++ @parameterized.expand(+ [+ ("job_log_insights_job_id_missing", "job_log_insights", {"repo": "PostHog/posthog", "run_id": "9100"}),+ ("ci_data_freshness_repo_missing", "ci_data_freshness", {}),+ ("ci_timing_context_job_without_job_ids", "ci_timing_context", {**_TIMING_PARAMS, "kind": "job"}),+ (+ "ci_timing_context_job_with_two_job_ids",+ "ci_timing_context",+ {**_TIMING_PARAMS, "kind": "job", "job_ids": "1,2"},+ ),+ (+ "ci_timing_context_step_without_step_number",+ "ci_timing_context",+ {**_TIMING_PARAMS, "kind": "step", "job_ids": "1"},+ ),+ (+ "ci_timing_context_run_attempt_zero",+ "ci_timing_context",+ {**_TIMING_PARAMS, "kind": "workflow", "run_attempt": "0"},+ ),("pr_lifecycle_pr_number_invalid", "pr_lifecycle", {"pr_number": "not-a-number"}),# repo is required (a PR number is repo-scoped), consistent with pr_runs/pr_cost.("pr_lifecycle_repo_missing", "pr_lifecycle", {"pr_number": "10"}),diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex e94097d2db2e..4b5d83dbec8d 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -393,6 +393,19 @@ export interface CICardSummaryApi {failing_ci: number}+export interface CIDataFreshnessApi {+ /**+ * When the last completed sync of the stored workflow runs started. Every stored run is at least this fresh. The older of the GitHub and Depot CI times when the repository syncs both. Null when a runs table has never synced.+ * @nullable+ */+ runs_synced_at: string | null+ /**+ * The same time for the stored workflow jobs. Null when jobs are not synced.+ * @nullable+ */+ jobs_synced_at: string | null+}+export interface CIFailureLogLineApi {/*** 1-based line number in the full pre-thinning job log, or null for a '... N lines omitted ...' marker. The gap between consecutive values is how many lines were elided.@@ -442,6 +455,139 @@ export interface CIFailureLogsApi {truncated: boolean}+/**+ * * `success` - Success+ * * `failure` - Failure+ */+export type CITimingSampleStatusEnumApi = (typeof CITimingSampleStatusEnumApi)[keyof typeof CITimingSampleStatusEnumApi]++export const CITimingSampleStatusEnumApi = {+ Success: 'success',+ Failure: 'failure',+} as const++export interface CITimingSampleApi {+ /** Integer run id of the sampled run; unique only together with ci_engine. */+ run_id: number+ /** Run attempt the sample was taken from, which is the run's latest. */+ run_attempt: number+ /**+ * Job id of the matched job. Null for a workflow or matrix sample, which spans jobs.+ * @nullable+ */+ job_id: number | null+ /**+ * Number of the matched step in the sampled job. Steps match by name, so it can differ from the selected step's number. Null unless kind is 'step'.+ * @nullable+ */+ step_number: number | null+ /** CI engine that ran the sampled run.+ *+ * * `github_actions` - GitHub Actions+ * * `depot_ci` - Depot CI */+ ci_engine: CIEngineEnumApi+ /**+ * Source-native run id; use with ci_engine to link to the run.+ * @nullable+ */+ native_run_id: string | null+ /**+ * Source-native workflow run id; use with ci_engine to link to the run.+ * @nullable+ */+ native_workflow_run_id: string | null+ /**+ * Source-native job id of the matched job. Null for a workflow or matrix sample.+ * @nullable+ */+ native_job_id: string | null+ /**+ * Source-native job attempt id of the matched job. Null for a workflow or matrix sample.+ * @nullable+ */+ native_attempt_id: string | null+ /** 'success' when every matched job succeeded, or the matched step did. Otherwise 'failure'.+ *+ * * `success` - Success+ * * `failure` - Failure */+ status: CITimingSampleStatusEnumApi+ /** For a workflow, matrix or job: seconds from the first matched job's start to the last one's end. For a step: the step's own duration. */+ duration_seconds: number+ /** When the last matched job finished. */+ completed_at: string+ /** Commit SHA the sampled run ran on. */+ head_sha: string+}++/**+ * * `workflow_id` - Workflow id+ * * `workflow_name` - Workflow name+ */+export type CITimingIdentityEnumApi = (typeof CITimingIdentityEnumApi)[keyof typeof CITimingIdentityEnumApi]++export const CITimingIdentityEnumApi = {+ WorkflowId: 'workflow_id',+ WorkflowName: 'workflow_name',+} as const++/**+ * * `default_branch_unknown` - Default branch unknown+ * * `jobs_not_synced` - Jobs not synced+ * * `not_executed` - Not executed+ */+export type CITimingUnavailableReasonEnumApi =+ (typeof CITimingUnavailableReasonEnumApi)[keyof typeof CITimingUnavailableReasonEnumApi]++export const CITimingUnavailableReasonEnumApi = {+ DefaultBranchUnknown: 'default_branch_unknown',+ JobsNotSynced: 'jobs_not_synced',+ NotExecuted: 'not_executed',+} as const++export interface CITimingContextApi {+ /** The newest matched samples of any status, newest first. At most three. */+ recent: CITimingSampleApi[]+ /**+ * The repository's default branch, which the samples ran on. Null when unknown.+ * @nullable+ */+ default_branch: string | null+ /** How many days back the comparison looks. */+ window_days: number+ /** How runs of the same workflow were found: by 'workflow_id', which a rename keeps, or by 'workflow_name' when the run has no workflow id.+ *+ * * `workflow_id` - Workflow id+ * * `workflow_name` - Workflow name */+ identity: CITimingIdentityEnumApi+ /** How many default-branch runs of the workflow were checked for a match. */+ runs_scanned: number+ /** True when the window held more eligible runs than were checked, so the figures cover the newest runs only. */+ sampled: boolean+ /** How many checked runs matched the selection and succeeded. */+ sample_count: number+ /**+ * Mean duration of the successful samples, in seconds. Null when there are none. A run counts only when it ran the same jobs on the same runners, so a null means no comparable run.+ * @nullable+ */+ average_seconds: number | null+ /**+ * When the last completed sync of the stored workflow runs started. Null when unknown.+ * @nullable+ */+ runs_synced_at: string | null+ /**+ * When the last completed sync of the stored workflow jobs started. Null when unknown.+ * @nullable+ */+ jobs_synced_at: string | null+ /** Why no comparison was made: 'default_branch_unknown' (no synced pull request names the repository's default branch), 'jobs_not_synced', or 'not_executed' (every selected job was skipped, so there is no duration to compare). Null when the comparison ran, even if it found no samples.+ *+ * * `default_branch_unknown` - Default branch unknown+ * * `jobs_not_synced` - Jobs not synced+ * * `not_executed` - Not executed */+ unavailable_reason: CITimingUnavailableReasonEnumApi | null+}+export interface CurrentBranchHealthApi {/** Detected default branch ('master' or 'main') from runs in the same 24-hour window. */default_branch: string@@ -982,6 +1128,77 @@ export interface WorkflowJobAggregateApi {estimated_cost_usd: number | null}+/**+ * * `cache` - Cache+ * * `migrations` - Migrations+ */+export type JobLogBadgeKindEnumApi = (typeof JobLogBadgeKindEnumApi)[keyof typeof JobLogBadgeKindEnumApi]++export const JobLogBadgeKindEnumApi = {+ Cache: 'cache',+ Migrations: 'migrations',+} as const++/**+ * * `hit` - Cache hit+ * * `partial` - Older cache+ * * `miss` - Cache miss+ * * `failed` - Cache restore failed+ * * `none` - No migrations+ * * `applied` - Migrations applied+ */+export type JobLogBadgeStateEnumApi = (typeof JobLogBadgeStateEnumApi)[keyof typeof JobLogBadgeStateEnumApi]++export const JobLogBadgeStateEnumApi = {+ Hit: 'hit',+ Partial: 'partial',+ Miss: 'miss',+ Failed: 'failed',+ None: 'none',+ Applied: 'applied',+} as const++export interface JobLogBadgeApi {+ /** What the badge is about: a dependency cache, or migrations.+ *+ * * `cache` - Cache+ * * `migrations` - Migrations */+ kind: JobLogBadgeKindEnumApi+ /** What happened. For a cache: 'hit' (exact key restored), 'partial' (an older cache restored from a restore key), 'miss' (nothing restored), 'failed' (the restore itself failed). For migrations: 'none' (nothing to apply) or 'applied'.+ *+ * * `hit` - Cache hit+ * * `partial` - Older cache+ * * `miss` - Cache miss+ * * `failed` - Cache restore failed+ * * `none` - No migrations+ * * `applied` - Migrations applied */+ state: JobLogBadgeStateEnumApi+ /** How many times the log reports this outcome. */+ count: number+ /** What each occurrence was about: a cache key or a migration name. Capped, so it can hold fewer entries than `count`. */+ detail: string[]+}++export interface JobStepLogBadgesApi {+ /** What the log says this step did. */+ badges: JobLogBadgeApi[]+ /** The step's number in the job, matching `number` of the job's steps. */+ number: number+}++export interface JobLogInsightsApi {+ /** Every badge found in the log, for the job as a whole. */+ job: JobLogBadgeApi[]+ /** The same badges per step. Only steps with a badge are listed. Empty when `attributed_to_steps` is false. */+ steps: JobStepLogBadgesApi[]+ /** False when no log was read: a Depot CI job, a job the source does not hold, a log GitHub no longer keeps, or a failed fetch. Empty badges then mean 'unknown', not 'nothing found'. */+ log_read: boolean+ /** False when the log's step markers did not line up with the job's steps, so the badges are reported for the job only. */+ attributed_to_steps: boolean+ /** True when only part of the log was parsed, because the log is too large or its download took too long. The badges are then a lower bound: an outcome in the part that was not parsed is missing. */+ log_truncated?: boolean+}+export interface MasterFailureGroupApi {/** Repository the failures occurred in. */repo: RepoRefApi@@ -1227,6 +1444,16 @@ export interface WorkflowRunDetailApi {* @nullable*/native_workflow_run_id?: string | null+ /**+ * GitHub's numeric id of the workflow. It stays the same when the workflow is renamed, so use it to follow one workflow over time. Null for a Depot CI run, and for a run whose source does not carry the id.+ * @nullable+ */+ workflow_id?: number | null+ /**+ * Event that triggered the run, such as 'push', 'pull_request' or 'schedule'. Null when unknown, as for a Depot CI run.+ * @nullable+ */+ event?: string | null}export interface PullRequestFrictionBreakdownApi {@@ -2467,6 +2694,18 @@ export type EngineeringAnalyticsCiCardsParams = {source_id?: string}+export type EngineeringAnalyticsCiDataFreshnessParams = {+ /**+ * 'owner/name' repository to report on.+ * @minLength 1+ */+ repo: string+ /**+ * Connected GitHub data warehouse source to read from. Defaults to the source connected for `repo`.+ */+ source_id?: string+}+export type EngineeringAnalyticsCiFailureLogsParams = {/*** Pull request number whose CI failure logs to fetch.@@ -2482,6 +2721,72 @@ export type EngineeringAnalyticsCiFailureLogsParams = {source_id?: string}+export type EngineeringAnalyticsCiTimingContextParams = {+ /**+ * CI engine that ran the run.+ *+ * * `github_actions` - GitHub Actions+ * * `depot_ci` - Depot CI+ * @minLength 1+ */+ ci_engine: EngineeringAnalyticsCiTimingContextCiEngine+ /**+ * Comma-separated job ids from workflow_jobs, at most 200. Required for 'matrix', 'job' and 'step'. Give exactly one id for 'job' and 'step'. Ignored for 'workflow'.+ * @minLength 1+ */+ job_ids?: string+ /**+ * What to compare: the whole 'workflow', a 'matrix' (several jobs of the run), one 'job', or one 'step' of a job.+ *+ * * `workflow` - Workflow+ * * `matrix` - Matrix+ * * `job` - Job+ * * `step` - Step+ * @minLength 1+ */+ kind: EngineeringAnalyticsCiTimingContextKind+ /**+ * 'owner/name' repository the run belongs to.+ * @minLength 1+ */+ repo: string+ /**+ * Run attempt that holds the selection.+ * @minimum 1+ */+ run_attempt: number+ /**+ * Integer run id of the run that holds the selection.+ */+ run_id: number+ /**+ * Connected GitHub data warehouse source to read from. Defaults to the source connected for `repo`.+ */+ source_id?: string+ /**+ * Number of the step within the job. Required when kind is 'step'.+ */+ step_number?: number+}++export type EngineeringAnalyticsCiTimingContextCiEngine =+ (typeof EngineeringAnalyticsCiTimingContextCiEngine)[keyof typeof EngineeringAnalyticsCiTimingContextCiEngine]++export const EngineeringAnalyticsCiTimingContextCiEngine = {+ GithubActions: 'github_actions',+ DepotCi: 'depot_ci',+} as const++export type EngineeringAnalyticsCiTimingContextKind =+ (typeof EngineeringAnalyticsCiTimingContextKind)[keyof typeof EngineeringAnalyticsCiTimingContextKind]++export const EngineeringAnalyticsCiTimingContextKind = {+ Workflow: 'workflow',+ Matrix: 'matrix',+ Job: 'job',+ Step: 'step',+} as const+export type EngineeringAnalyticsCurrentBranchHealthParams = {/*** 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.@@ -2667,6 +2972,42 @@ export const EngineeringAnalyticsJobAggregatesRunScope = {PullRequest: 'pull_request',} as const+export type EngineeringAnalyticsJobLogInsightsParams = {+ /**+ * CI engine. Required when job_id exists in both engines. Only GitHub Actions job logs are read.+ *+ * * `github_actions` - GitHub Actions+ * * `depot_ci` - Depot CI+ * @minLength 1+ */+ ci_engine?: EngineeringAnalyticsJobLogInsightsCiEngine+ /**+ * Job id to read the log of; a row id from workflow_jobs.+ */+ job_id: number+ /**+ * 'owner/name' repository the job ran in.+ * @minLength 1+ */+ repo: string+ /**+ * Workflow run id the job belongs to.+ */+ run_id: number+ /**+ * Connected GitHub data warehouse source to read from. Defaults to the source connected for `repo`.+ */+ source_id?: string+}++export type EngineeringAnalyticsJobLogInsightsCiEngine =+ (typeof EngineeringAnalyticsJobLogInsightsCiEngine)[keyof typeof EngineeringAnalyticsJobLogInsightsCiEngine]++export const EngineeringAnalyticsJobLogInsightsCiEngine = {+ GithubActions: 'github_actions',+ DepotCi: 'depot_ci',+} as const+export type EngineeringAnalyticsMasterFailuresParams = {/*** Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.tsindex 2ea60c25a5b6..27bbb93f06f8 100644--- a/products/engineering_analytics/frontend/generated/api.ts+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -15,9 +15,11 @@ import type {BranchPRMatchApi,BrokenTestsResultApi,CICardSummaryApi,+ CIDataFreshnessApi,CIFailureLogsApi,CISignalsConfigApi,CISignalsConfigUpdateApi,+ CITimingContextApi,CurrentBranchHealthApi,DeliveryComparisonApi,DeliverySummaryApi,@@ -28,13 +30,16 @@ import type {EngineeringAnalyticsAuthorWorkflowCostsParams,EngineeringAnalyticsBrokenTestsParams,EngineeringAnalyticsCiCardsParams,+ EngineeringAnalyticsCiDataFreshnessParams,EngineeringAnalyticsCiFailureLogsParams,+ EngineeringAnalyticsCiTimingContextParams,EngineeringAnalyticsCurrentBranchHealthParams,EngineeringAnalyticsDeliveryComparisonParams,EngineeringAnalyticsDeliverySummaryParams,EngineeringAnalyticsDoraParams,EngineeringAnalyticsFlakyTestsParams,EngineeringAnalyticsJobAggregatesParams,+ EngineeringAnalyticsJobLogInsightsParams,EngineeringAnalyticsMasterFailuresParams,EngineeringAnalyticsPrCostParams,EngineeringAnalyticsPrLifecycleParams,@@ -59,6 +64,7 @@ import type {EngineeringAnalyticsWorkflowRunsParams,FlakyTestListApi,GitHubSourceApi,+ JobLogInsightsApi,MasterFailureGroupApi,PRCostSummaryApi,PRLifecycleApi,@@ -315,6 +321,39 @@ export const engineeringAnalyticsCiCards = async (})}+export const getEngineeringAnalyticsCiDataFreshnessUrl = (+ projectId: string,+ params: EngineeringAnalyticsCiDataFreshnessParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/engineering_analytics/ci_data_freshness/?${stringifiedParams}`+ : `/api/projects/${projectId}/engineering_analytics/ci_data_freshness/`+}++/**+ * When the stored CI data of a repository was last synced from its source: one time for workflow runs and one for workflow jobs. Every stored row is at least that fresh, so use these times, not the time of the request, to say how current a CI answer is. Each time is when the last completed sync started. For a repository that also syncs Depot CI, it is the older of the GitHub and the Depot CI time.+ */+export const engineeringAnalyticsCiDataFreshness = async (+ projectId: string,+ params: EngineeringAnalyticsCiDataFreshnessParams,+ options?: RequestInit+): Promise<CIDataFreshnessApi> => {+ return apiMutator<CIDataFreshnessApi>(getEngineeringAnalyticsCiDataFreshnessUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getEngineeringAnalyticsCiFailureLogsUrl = (projectId: string,params: EngineeringAnalyticsCiFailureLogsParams@@ -348,6 +387,39 @@ export const engineeringAnalyticsCiFailureLogs = async (})}+export const getEngineeringAnalyticsCiTimingContextUrl = (+ projectId: string,+ params: EngineeringAnalyticsCiTimingContextParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/engineering_analytics/ci_timing_context/?${stringifiedParams}`+ : `/api/projects/${projectId}/engineering_analytics/ci_timing_context/`+}++/**+ * How long a selected workflow, matrix, job or step usually takes: compares it with runs of the same workflow on the repository's default branch over the last 7 days, from stored data only. A run counts only when it ran the same jobs on the same runner tiers, so the answer never mixes in a different workflow, job or runner. Pull request runs and merge queue runs are left out. At most the newest 40 default-branch runs are checked, and `sampled` is true when more existed. `average_seconds` and `sample_count` cover successful samples only, and `recent` lists the newest three matches of any status. `average_seconds` is null when no comparable run exists. `unavailable_reason` says why no comparison was made. Answers are cached for 5 minutes.+ */+export const engineeringAnalyticsCiTimingContext = async (+ projectId: string,+ params: EngineeringAnalyticsCiTimingContextParams,+ options?: RequestInit+): Promise<CITimingContextApi> => {+ return apiMutator<CITimingContextApi>(getEngineeringAnalyticsCiTimingContextUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getEngineeringAnalyticsCurrentBranchHealthUrl = (projectId: string,params?: EngineeringAnalyticsCurrentBranchHealthParams@@ -552,6 +624,39 @@ export const engineeringAnalyticsJobAggregates = async (})}+export const getEngineeringAnalyticsJobLogInsightsUrl = (+ projectId: string,+ params: EngineeringAnalyticsJobLogInsightsParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/engineering_analytics/job_log_insights/?${stringifiedParams}`+ : `/api/projects/${projectId}/engineering_analytics/job_log_insights/`+}++/**+ * What one GitHub Actions job's log says it did: cache restores (hit, older cache, miss, restore failed) and migrations applied, for the job and per step. Reads the log from GitHub on demand. Only a completed job's answer is cached. `log_read` is false, never an error, when there is no log to read: a Depot CI job, a job the source does not hold, an expired log, or a failed fetch.+ */+export const engineeringAnalyticsJobLogInsights = async (+ projectId: string,+ params: EngineeringAnalyticsJobLogInsightsParams,+ options?: RequestInit+): Promise<JobLogInsightsApi> => {+ return apiMutator<JobLogInsightsApi>(getEngineeringAnalyticsJobLogInsightsUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getEngineeringAnalyticsMasterFailuresUrl = (projectId: string,params?: EngineeringAnalyticsMasterFailuresParamsdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 471c3eb12bd3..b9b16721094d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -19490,6 +19490,19 @@ export namespace Schemas {failing_ci: number;}+ export interface CIDataFreshness {+ /**+ * When the last completed sync of the stored workflow runs started. Every stored run is at least this fresh. The older of the GitHub and Depot CI times when the repository syncs both. Null when a runs table has never synced.+ * @nullable+ */+ runs_synced_at: string | null;+ /**+ * The same time for the stored workflow jobs. Null when jobs are not synced.+ * @nullable+ */+ jobs_synced_at: string | null;+ }+export interface CIFailureLogLine {/*** 1-based line number in the full pre-thinning job log, or null for a '... N lines omitted ...' marker. The gap between consecutive values is how many lines were elided.@@ -19648,6 +19661,141 @@ export namespace Schemas {Jest: 'jest',} as const;+ /**+ * * `success` - Success+ * * `failure` - Failure+ */+ export type CITimingSampleStatusEnum = typeof CITimingSampleStatusEnum[keyof typeof CITimingSampleStatusEnum];+++ export const CITimingSampleStatusEnum = {+ Success: 'success',+ Failure: 'failure',+ } as const;++ export interface CITimingSample {+ /** Integer run id of the sampled run; unique only together with ci_engine. */+ run_id: number;+ /** Run attempt the sample was taken from, which is the run's latest. */+ run_attempt: number;+ /**+ * Job id of the matched job. Null for a workflow or matrix sample, which spans jobs.+ * @nullable+ */+ job_id: number | null;+ /**+ * Number of the matched step in the sampled job. Steps match by name, so it can differ from the selected step's number. Null unless kind is 'step'.+ * @nullable+ */+ step_number: number | null;+ /** CI engine that ran the sampled run.+ *+ * * `github_actions` - GitHub Actions+ * * `depot_ci` - Depot CI */+ ci_engine: CIEngineEnum;+ /**+ * Source-native run id; use with ci_engine to link to the run.+ * @nullable+ */+ native_run_id: string | null;+ /**+ * Source-native workflow run id; use with ci_engine to link to the run.+ * @nullable+ */+ native_workflow_run_id: string | null;+ /**+ * Source-native job id of the matched job. Null for a workflow or matrix sample.+ * @nullable+ */+ native_job_id: string | null;+ /**+ * Source-native job attempt id of the matched job. Null for a workflow or matrix sample.+ * @nullable+ */+ native_attempt_id: string | null;+ /** 'success' when every matched job succeeded, or the matched step did. Otherwise 'failure'.+ *+ * * `success` - Success+ * * `failure` - Failure */+ status: CITimingSampleStatusEnum;+ /** For a workflow, matrix or job: seconds from the first matched job's start to the last one's end. For a step: the step's own duration. */+ duration_seconds: number;+ /** When the last matched job finished. */+ completed_at: string;+ /** Commit SHA the sampled run ran on. */+ head_sha: string;+ }++ /**+ * * `workflow_id` - Workflow id+ * * `workflow_name` - Workflow name+ */+ export type CITimingIdentityEnum = typeof CITimingIdentityEnum[keyof typeof CITimingIdentityEnum];+++ export const CITimingIdentityEnum = {+ WorkflowId: 'workflow_id',+ WorkflowName: 'workflow_name',+ } as const;++ /**+ * * `default_branch_unknown` - Default branch unknown+ * * `jobs_not_synced` - Jobs not synced+ * * `not_executed` - Not executed+ */+ export type CITimingUnavailableReasonEnum = typeof CITimingUnavailableReasonEnum[keyof typeof CITimingUnavailableReasonEnum];+++ export const CITimingUnavailableReasonEnum = {+ DefaultBranchUnknown: 'default_branch_unknown',+ JobsNotSynced: 'jobs_not_synced',+ NotExecuted: 'not_executed',+ } as const;++ export interface CITimingContext {+ /** The newest matched samples of any status, newest first. At most three. */+ recent: CITimingSample[];+ /**+ * The repository's default branch, which the samples ran on. Null when unknown.+ * @nullable+ */+ default_branch: string | null;+ /** How many days back the comparison looks. */+ window_days: number;+ /** How runs of the same workflow were found: by 'workflow_id', which a rename keeps, or by 'workflow_name' when the run has no workflow id.+ *+ * * `workflow_id` - Workflow id+ * * `workflow_name` - Workflow name */+ identity: CITimingIdentityEnum;+ /** How many default-branch runs of the workflow were checked for a match. */+ runs_scanned: number;+ /** True when the window held more eligible runs than were checked, so the figures cover the newest runs only. */+ sampled: boolean;+ /** How many checked runs matched the selection and succeeded. */+ sample_count: number;+ /**+ * Mean duration of the successful samples, in seconds. Null when there are none. A run counts only when it ran the same jobs on the same runners, so a null means no comparable run.+ * @nullable+ */+ average_seconds: number | null;+ /**+ * When the last completed sync of the stored workflow runs started. Null when unknown.+ * @nullable+ */+ runs_synced_at: string | null;+ /**+ * When the last completed sync of the stored workflow jobs started. Null when unknown.+ * @nullable+ */+ jobs_synced_at: string | null;+ /** Why no comparison was made: 'default_branch_unknown' (no synced pull request names the repository's default branch), 'jobs_not_synced', or 'not_executed' (every selected job was skipped, so there is no duration to compare). Null when the comparison ran, even if it found no samples.+ *+ * * `default_branch_unknown` - Default branch unknown+ * * `jobs_not_synced` - Jobs not synced+ * * `not_executed` - Not executed */+ unavailable_reason: CITimingUnavailableReasonEnum | null;+ }+export interface EventsHeatMapColumnAggregationResult {column: number;value: number;@@ -59477,6 +59625,79 @@ export namespace Schemas {failed: number;}+ /**+ * * `cache` - Cache+ * * `migrations` - Migrations+ */+ export type JobLogBadgeKindEnum = typeof JobLogBadgeKindEnum[keyof typeof JobLogBadgeKindEnum];+++ export const JobLogBadgeKindEnum = {+ Cache: 'cache',+ Migrations: 'migrations',+ } as const;++ /**+ * * `hit` - Cache hit+ * * `partial` - Older cache+ * * `miss` - Cache miss+ * * `failed` - Cache restore failed+ * * `none` - No migrations+ * * `applied` - Migrations applied+ */+ export type JobLogBadgeStateEnum = typeof JobLogBadgeStateEnum[keyof typeof JobLogBadgeStateEnum];+++ export const JobLogBadgeStateEnum = {+ Hit: 'hit',+ Partial: 'partial',+ Miss: 'miss',+ Failed: 'failed',+ None: 'none',+ Applied: 'applied',+ } as const;++ export interface JobLogBadge {+ /** What the badge is about: a dependency cache, or migrations.+ *+ * * `cache` - Cache+ * * `migrations` - Migrations */+ kind: JobLogBadgeKindEnum;+ /** What happened. For a cache: 'hit' (exact key restored), 'partial' (an older cache restored from a restore key), 'miss' (nothing restored), 'failed' (the restore itself failed). For migrations: 'none' (nothing to apply) or 'applied'.+ *+ * * `hit` - Cache hit+ * * `partial` - Older cache+ * * `miss` - Cache miss+ * * `failed` - Cache restore failed+ * * `none` - No migrations+ * * `applied` - Migrations applied */+ state: JobLogBadgeStateEnum;+ /** How many times the log reports this outcome. */+ count: number;+ /** What each occurrence was about: a cache key or a migration name. Capped, so it can hold fewer entries than `count`. */+ detail: string[];+ }++ export interface JobStepLogBadges {+ /** What the log says this step did. */+ badges: JobLogBadge[];+ /** The step's number in the job, matching `number` of the job's steps. */+ number: number;+ }++ export interface JobLogInsights {+ /** Every badge found in the log, for the job as a whole. */+ job: JobLogBadge[];+ /** The same badges per step. Only steps with a badge are listed. Empty when `attributed_to_steps` is false. */+ steps: JobStepLogBadges[];+ /** False when no log was read: a Depot CI job, a job the source does not hold, a log GitHub no longer keeps, or a failed fetch. Empty badges then mean 'unknown', not 'nothing found'. */+ log_read: boolean;+ /** False when the log's step markers did not line up with the job's steps, so the badges are reported for the job only. */+ attributed_to_steps: boolean;+ /** True when only part of the log was parsed, because the log is too large or its download took too long. The badges are then a lower bound: an outcome in the part that was not parsed is missing. */+ log_truncated?: boolean;+ }+export interface JobStatsBucket {/** Runs that completed in this bucket. */successful: number;@@ -112439,6 +112660,16 @@ export namespace Schemas {* @nullable*/native_workflow_run_id?: string | null;+ /**+ * GitHub's numeric id of the workflow. It stays the same when the workflow is renamed, so use it to follow one workflow over time. Null for a Depot CI run, and for a run whose source does not carry the id.+ * @nullable+ */+ workflow_id?: number | null;+ /**+ * Event that triggered the run, such as 'push', 'pull_request' or 'schedule'. Null when unknown, as for a Depot CI run.+ * @nullable+ */+ event?: string | null;}export interface WorkflowRunnerCost {@@ -119670,6 +119901,18 @@ export namespace Schemas {source_id?: string;};+ export type EngineeringAnalyticsCiDataFreshnessParams = {+ /**+ * 'owner/name' repository to report on.+ * @minLength 1+ */+ repo: string;+ /**+ * Connected GitHub data warehouse source to read from. Defaults to the source connected for `repo`.+ */+ source_id?: string;+ };+export type EngineeringAnalyticsCiFailureLogsParams = {/*** Pull request number whose CI failure logs to fetch.@@ -119685,6 +119928,72 @@ export namespace Schemas {source_id?: string;};+ export type EngineeringAnalyticsCiTimingContextParams = {+ /**+ * CI engine that ran the run.+ *+ * * `github_actions` - GitHub Actions+ * * `depot_ci` - Depot CI+ * @minLength 1+ */+ ci_engine: EngineeringAnalyticsCiTimingContextCiEngine;+ /**+ * Comma-separated job ids from workflow_jobs, at most 200. Required for 'matrix', 'job' and 'step'. Give exactly one id for 'job' and 'step'. Ignored for 'workflow'.+ * @minLength 1+ */+ job_ids?: string;+ /**+ * What to compare: the whole 'workflow', a 'matrix' (several jobs of the run), one 'job', or one 'step' of a job.+ *+ * * `workflow` - Workflow+ * * `matrix` - Matrix+ * * `job` - Job+ * * `step` - Step+ * @minLength 1+ */+ kind: EngineeringAnalyticsCiTimingContextKind;+ /**+ * 'owner/name' repository the run belongs to.+ * @minLength 1+ */+ repo: string;+ /**+ * Run attempt that holds the selection.+ * @minimum 1+ */+ run_attempt: number;+ /**+ * Integer run id of the run that holds the selection.+ */+ run_id: number;+ /**+ * Connected GitHub data warehouse source to read from. Defaults to the source connected for `repo`.+ */+ source_id?: string;+ /**+ * Number of the step within the job. Required when kind is 'step'.+ */+ step_number?: number;+ };++ export type EngineeringAnalyticsCiTimingContextCiEngine = typeof EngineeringAnalyticsCiTimingContextCiEngine[keyof typeof EngineeringAnalyticsCiTimingContextCiEngine];+++ export const EngineeringAnalyticsCiTimingContextCiEngine = {+ GithubActions: 'github_actions',+ DepotCi: 'depot_ci',+ } as const;++ export type EngineeringAnalyticsCiTimingContextKind = typeof EngineeringAnalyticsCiTimingContextKind[keyof typeof EngineeringAnalyticsCiTimingContextKind];+++ export const EngineeringAnalyticsCiTimingContextKind = {+ Workflow: 'workflow',+ Matrix: 'matrix',+ Job: 'job',+ Step: 'step',+ } as const;+export type EngineeringAnalyticsCurrentBranchHealthParams = {/*** 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.@@ -119870,6 +120179,42 @@ export namespace Schemas {PullRequest: 'pull_request',} as const;+ export type EngineeringAnalyticsJobLogInsightsParams = {+ /**+ * CI engine. Required when job_id exists in both engines. Only GitHub Actions job logs are read.+ *+ * * `github_actions` - GitHub Actions+ * * `depot_ci` - Depot CI+ * @minLength 1+ */+ ci_engine?: EngineeringAnalyticsJobLogInsightsCiEngine;+ /**+ * Job id to read the log of; a row id from workflow_jobs.+ */+ job_id: number;+ /**+ * 'owner/name' repository the job ran in.+ * @minLength 1+ */+ repo: string;+ /**+ * Workflow run id the job belongs to.+ */+ run_id: number;+ /**+ * Connected GitHub data warehouse source to read from. Defaults to the source connected for `repo`.+ */+ source_id?: string;+ };++ export type EngineeringAnalyticsJobLogInsightsCiEngine = typeof EngineeringAnalyticsJobLogInsightsCiEngine[keyof typeof EngineeringAnalyticsJobLogInsightsCiEngine];+++ export const EngineeringAnalyticsJobLogInsightsCiEngine = {+ GithubActions: 'github_actions',+ DepotCi: 'depot_ci',+ } as const;+export type EngineeringAnalyticsMasterFailuresParams = {/*** Optional exact git branch (head_branch) to scope results to, e.g. 'main'. Omit or leave blank to aggregate across all branches.