Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(eng-analytics): read depot ci runs and jobs (#106074)

Raúl Negrón-Otero75e6f7a67780
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 73b1415013a1..0aedaf19e5b8 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -100,7 +100,7 @@ The endpoint catalog is `presentation/views.py`; the agent-facing descriptions l
Per-team managed views (`DataWarehouseSavedQuery`, kind `engineering_analytics`) expose the curated CI substrate to insights, subscriptions, other products, and `execute-sql`: the only surface where the read layer is reachable as data rather than through the named endpoints.
One gate for the three per-job views: a team gets them only when a GitHub source has **both** `workflow_runs` and `workflow_jobs` synced, so they appear together or not at all.
-They are non-materialized: the rendered SQL is persisted per team and re-synced on every runs/jobs load, so a builder change reaches active teams within one sync cycle.
+They are non-materialized: the rendered SQL is persisted per team and re-synced on every runs/jobs load and every Depot job-attempts load, so a builder change reaches active teams within one sync cycle.
The per-PR friction view is the exception, below: it also needs the `pull_requests` snapshot, and it is materialized.
#### `engineering_analytics_job_costs`
@@ -191,6 +191,10 @@ Warehouse tables (GitHub source):
- `github_reviews`: submitted pull request reviews (approvals, change requests, comments), fanned out per PR with `pr_number` injected. Backs the approval split and the review states on the author page. Optional at the source, so reads must degrade gracefully when unsynced.
- `github_issue_events`: immutable issue/PR state transitions, landed raw with every event type kept (a source-side filter would pin the desc-walk watermark). The draft/ready transitions in them back `ready_to_merge_seconds` and the lifecycle timeline. Team review requests (`review_requested` events that carry `requested_team`) pick the team an author's delivery comparison uses: the repository's owner resolution asks the teams that own the changed files, so the teams an author's pull requests ask most often are the teams the author works for. GitHub adds that column only for a team request, so a repository where no pull request asked a team has no such column, and the source resolver checks for it before the read uses it. GitHub caps the endpoint's history walk, so rows cover a bounded recent window growing forward from the first sync; optional, and reads must degrade gracefully when unsynced.
+Warehouse table (Depot source):
+
+- `depot_job_attempts`: one row per Depot CI job attempt, for the repository the Depot source names. Reads keep only that repository's rows, because a source moved to another repository keeps what it synced before. Depot CI is its own engine, so these runs never reach the GitHub tables. `logic/views/depot_ci.py` reshapes the attempts into rows of the GitHub runs and jobs contracts and unions them onto those tables, so every builder reads both engines. Each Depot workflow is one runs row. A run with one workflow decodes its id to the integer `GITHUB_RUN_ID` Depot CI gives its jobs, which joins them to the CI test spans; a run with several workflows keys each by its own decoded workflow id, so no join fans out. The PR number comes from the run's `refs/pull/<n>/merge` ref, and the run's branch from that PR's snapshot; job rows carry no branch, because every branch filter reads the run's. Depot's API reports no `runs-on`, so every attempt is costed as the default `depot-ubuntu-24.04` sandbox. Optional, and reads degrade to GitHub-only CI when unsynced.
+
Other products read as sources:
- Logs: the thinned CI failure lines this product's job-logs pipeline emits (`service.name = github-ci-logs`), keyed by `run_id`.
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index 5cbab5c1a242..b639fb921538 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -33,12 +33,14 @@ from products.engineering_analytics.backend.logic.queries._workflow_filters impo
from products.engineering_analytics.backend.logic.sources import (
GitHubTables,
TrunkQuarantineSource,
+ resolve_depot_job_attempts_tables,
resolve_github_tables,
resolve_trunk_merge_queue_table,
resolve_trunk_quarantined_tests_source,
)
from products.engineering_analytics.backend.logic.views import (
deployments,
+ depot_ci,
issue_events,
job_costs,
pull_requests,
@@ -168,6 +170,8 @@ class CuratedGitHubSource:
self._trunk_table_resolved = False
self._trunk_quarantine_source: TrunkQuarantineSource | None = None
self._trunk_quarantine_resolved = False
+ self._depot_job_attempts_table: depot_ci.DepotJobAttempts | None = None
+ self._depot_job_attempts_resolved = False
@property
def team(self) -> Team:
@@ -216,9 +220,7 @@ class CuratedGitHubSource:
adds the raw-string scan floor — callers must register {run_started_floor} (see
run_started_floor_constant)."""
query = workflow_runs.build_query(
- self._tables.workflow_runs,
- pull_requests_table=self._tables.pull_requests,
- started_floor=started_floor,
+ self._runs_table(), pull_requests_table=self._tables.pull_requests, started_floor=started_floor
)
return f"({query})"
@@ -230,7 +232,26 @@ class CuratedGitHubSource:
``is_rerun_copy`` duplicate scan reads no ``created_at_raw``, so only the floor bounds it."""
if not self._tables.workflow_jobs:
return None
- return f"({workflow_jobs.build_query(self._tables.workflow_jobs, created_floor=created_floor)})"
+ return (
+ f"({workflow_jobs.build_query(self._jobs_table(self._tables.workflow_jobs), created_floor=created_floor)})"
+ )
+
+ def _depot_job_attempts(self) -> depot_ci.DepotJobAttempts | None:
+ """The repository's synced Depot CI job attempts, or None. Resolved lazily and cached like the
+ Trunk tables, so a read that never touches CI pays no lookup."""
+ if not self._depot_job_attempts_resolved:
+ depot_tables = resolve_depot_job_attempts_tables(self._team, self._user_access_control)
+ self._depot_job_attempts_table = depot_tables.get(self.repository.casefold())
+ self._depot_job_attempts_resolved = True
+ return self._depot_job_attempts_table
+
+ def _runs_table(self) -> str:
+ return depot_ci.with_depot_runs(
+ self._tables.workflow_runs, self._depot_job_attempts(), self._tables.pull_requests
+ )
+
+ def _jobs_table(self, workflow_jobs_table: str) -> str:
+ return depot_ci.with_depot_jobs(workflow_jobs_table, self._depot_job_attempts())
def trunk_merge_queue_source(self) -> str | None:
"""Curated Trunk merge-queue ``SELECT`` subquery, or None when no TrunkIo source has the
@@ -381,8 +402,8 @@ class CuratedGitHubSource:
if not self._tables.workflow_jobs:
return None
query = job_costs.build_query(
- jobs_table=self._tables.workflow_jobs,
- runs_table=self._tables.workflow_runs,
+ jobs_table=self._jobs_table(self._tables.workflow_jobs),
+ runs_table=self._runs_table(),
include_run_columns=True,
created_floor=created_floor,
)
diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.py
index b2539af03636..f66499e00a87 100644
--- a/products/engineering_analytics/backend/logic/sources.py
+++ b/products/engineering_analytics/backend/logic/sources.py
@@ -31,6 +31,7 @@ from posthog.dataclasses import frozen
from posthog.models.team import Team
from products.engineering_analytics.backend.facade.contracts import GitHubSource, GitHubSourceNotConnectedError
+from products.engineering_analytics.backend.logic.views import depot_ci
from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
from products.warehouse_sources.backend.facade.sources import github_schema_repo_endpoint
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
@@ -62,6 +63,10 @@ DEPLOYMENT_STATUSES_SCHEMA = "deployment_statuses"
# at the source, so reads must degrade gracefully (no review data) exactly like issue_events.
REVIEWS_SCHEMA = "reviews"
+# The Depot source's one table: a row per Depot CI job attempt. Optional, and resolved from a Depot
+# source rather than the GitHub one, so reads degrade to GitHub-only CI exactly like workflow_jobs.
+DEPOT_JOB_ATTEMPTS_SCHEMA = "job_attempts"
+
# GitHub adds this column to an issue event only for a team review request, so it lands only once some
# pull request in the repo requested a team, and a read of it fails before that.
REQUESTED_TEAM_COLUMN = "requested_team"
@@ -210,6 +215,17 @@ class JobSourceTables:
issue_events: str | None = None
reviews: str | None = None
source_id: str = ""
+ depot_job_attempts: depot_ci.DepotJobAttempts | None = None
+
+ @property
+ def 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.workflow_runs, self.depot_job_attempts, self.pull_requests)
+
+ @property
+ def jobs_source(self) -> str:
+ """The jobs to read: the GitHub jobs table plus this repo's Depot CI job attempts when synced."""
+ return depot_ci.with_depot_jobs(self.workflow_jobs, self.depot_job_attempts)
def resolve_job_source_tables(team: Team) -> list[JobSourceTables]:
@@ -224,8 +240,9 @@ def resolve_job_source_tables(team: Team) -> list[JobSourceTables]:
team scoping is the boundary.
"""
resolved: list[JobSourceTables] = []
+ depot_tables = resolve_depot_job_attempts_tables(team)
for source in _github_sources(team):
- for repo_tables in _synced_tables_by_repo(team=team, source=source).values():
+ for repository, repo_tables in _synced_tables_by_repo(team=team, source=source).items():
tables = repo_tables.names
runs = tables.get(WORKFLOW_RUNS_SCHEMA)
jobs = tables.get(WORKFLOW_JOBS_SCHEMA)
@@ -238,6 +255,10 @@ 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),
+ # The views union every entry, so a repository that two GitHub sources sync
+ # takes its Depot table on the first entry only. Otherwise every Depot job
+ # and its cost would count twice.
+ depot_job_attempts=depot_tables.pop(repository, None),
)
)
return resolved
@@ -292,12 +313,9 @@ def resolve_trunk_merge_queue_table(team: Team, user_access_control: "UserAccess
proxy exactly like the unsynced state.
"""
for source in _accessible_sources(team, ExternalDataSourceType.TRUNKIO, user_access_control):
- for schema in _synced_schemas(team=team, source=source):
- if schema.name != TRUNK_MERGE_QUEUE_SCHEMA:
- continue
- table = schema.table
- if table is not None and not table.deleted and _IDENTIFIER.match(table.name):
- return table.name
+ table = _synced_table_name(team, source, TRUNK_MERGE_QUEUE_SCHEMA)
+ if table:
+ return table
return None
@@ -505,6 +523,35 @@ def _as_source_uuid(source_id: str) -> UUID:
raise ValueError(f"source_id must be a UUID, got: {source_id!r}") from err
+def resolve_depot_job_attempts_tables(
+ team: Team, user_access_control: "UserAccessControl | None" = None
+) -> dict[str, depot_ci.DepotJobAttempts]:
+ """The team's synced Depot CI job attempts, keyed by the casefolded ``owner/repo`` the way
+ ``_synced_tables_by_repo`` keys GitHub repos.
+
+ A Depot source syncs only the repository its ``repository`` input names, so that input decides
+ which GitHub repository its runs join. The oldest source wins, like every other resolver here.
+ """
+ tables: dict[str, depot_ci.DepotJobAttempts] = {}
+ for source in _accessible_sources(team, ExternalDataSourceType.DEPOT, user_access_control):
+ repository = _source_repository(source).casefold()
+ table = _synced_table_name(team, source, DEPOT_JOB_ATTEMPTS_SCHEMA) if repository else None
+ attempts = depot_ci.DepotJobAttempts.for_repository(table, repository) if table else None
+ if attempts:
+ tables.setdefault(repository, attempts)
+ return tables
+
+
+def _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 identifier
+ qualifies, because callers interpolate the name into HogQL."""
+ for schema in _synced_schemas(team=team, source=source):
+ table = schema.table
+ if schema.name == schema_name and table is not None and not table.deleted and _IDENTIFIER.match(table.name):
+ return table.name
+ return None
+
+
def _synced_schemas(*, team: Team, source: ExternalDataSource) -> QuerySet[ExternalDataSchema]:
return (
ExternalDataSchema.objects.filter(team_id=team.pk, source_id=source.id, should_sync=True)
diff --git a/products/engineering_analytics/backend/logic/views/ci_job_history.py b/products/engineering_analytics/backend/logic/views/ci_job_history.py
index 4b61e46be265..39fb4eae04c9 100644
--- a/products/engineering_analytics/backend/logic/views/ci_job_history.py
+++ b/products/engineering_analytics/backend/logic/views/ci_job_history.py
@@ -116,7 +116,13 @@ def _head_commit_query(runs_table: str) -> str:
"""
-def build_query(*, jobs_table: str, runs_table: str, pull_requests_table: str | None = None) -> str:
+def build_query(
+ *,
+ jobs_table: str,
+ runs_table: str,
+ pull_requests_table: str | None = None,
+ head_commit_runs_table: str | None = None,
+) -> str:
"""The per-job-attempt history SELECT for one GitHub source: curated jobs LEFT JOIN curated runs,
plus the run's commit attribution.
@@ -124,10 +130,13 @@ def build_query(*, jobs_table: str, runs_table: str, pull_requests_table: str |
merged PR's ``merge_commit_sha`` instead of the head commit's message. It is optional because
this view qualifies on jobs + runs alone (see ``resolve_job_source_tables``), so a repo can
reach it without a PR snapshot; without one, attribution falls back to the message suffix.
+
+ ``head_commit_runs_table`` names the plain GitHub runs table when ``runs_table`` also holds Depot
+ CI runs, which carry no commit object, so the attribution scan skips them.
"""
jobs = workflow_jobs.build_query(jobs_table)
runs = workflow_runs.build_query(runs_table, pull_requests_table=pull_requests_table)
- head_commits = _head_commit_query(runs_table)
+ head_commits = _head_commit_query(head_commit_runs_table or runs_table)
return f"""
SELECT
@@ -174,9 +183,10 @@ def build_team_view(team: "Team") -> str | None:
return None
selects = [
build_query(
- jobs_table=source.workflow_jobs,
- runs_table=source.workflow_runs,
+ jobs_table=source.jobs_source,
+ runs_table=source.runs_source,
pull_requests_table=source.pull_requests,
+ head_commit_runs_table=source.workflow_runs,
)
for source in sources
]
diff --git a/products/engineering_analytics/backend/logic/views/depot_ci.py b/products/engineering_analytics/backend/logic/views/depot_ci.py
new file mode 100644
index 000000000000..3028a4229da7
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/views/depot_ci.py
@@ -0,0 +1,196 @@
+"""Depot CI job attempts, rendered as rows of the raw GitHub runs and jobs tables.
+
+Depot CI is its own CI engine, not Depot runners under GitHub Actions, so the runs it executes never
+reach the GitHub source. The Depot source syncs them to a ``job_attempts`` table instead. The
+functions here reshape that table into ``WORKFLOW_RUNS_COLUMNS`` and ``WORKFLOW_JOBS_COLUMNS`` rows
+and union them onto the GitHub tables, so every builder derives durations, PR numbers and cost for
+both engines with one set of rules.
+
+A Depot workflow is the counterpart of a GitHub workflow run, so it becomes one runs row. Depot ids
+are strings. Depot CI sets ``GITHUB_RUN_ID`` to the run id read as a base-30 number over
+``_ID_ALPHABET``, which the per-test traces its jobs emit confirm. A run with one workflow therefore
+takes its decoded run id, which joins those traces to its jobs. A run with several workflows takes
+each workflow's decoded id instead, because one shared id would fan every join on it out.
+"""
+
+import re
+
+from posthog.dataclasses import frozen
+
+from products.engineering_analytics.backend.logic.views.source_schema import (
+ WORKFLOW_JOBS_COLUMNS,
+ WORKFLOW_RUNS_COLUMNS,
+)
+
+_ID_ALPHABET = "0123456789bcdfghjklmnpqrstvwxz"
+
+# The repository is written into HogQL as a string literal, so only a plain owner/name qualifies.
+_PLAIN_REPOSITORY = re.compile(r"\A[A-Za-z0-9._-]+/[A-Za-z0-9._-]+\Z")
+
+
+@frozen
+class DepotJobAttempts:
+ """A synced Depot ``job_attempts`` table and the repository whose rows it contributes.
+
+ Reads keep only that repository's rows, because a Depot source moved to another repository keeps
+ the rows it synced before the move.
+ """
+
+ table: str
+ repository: str
+
+ def __post_init__(self) -> None:
+ if not _PLAIN_REPOSITORY.match(self.repository):
+ raise ValueError(f"Not a plain owner/name repository: {self.repository!r}")
+
+ @classmethod
+ def for_repository(cls, table: str, repository: str) -> "DepotJobAttempts | None":
+ """The attempts of ``repository``, or None when it is not a plain owner/name."""
+ return cls(table=table, repository=repository) if _PLAIN_REPOSITORY.match(repository) else None
+
+
+# Depot ids are 10 characters. Ten base-30 digits stay below 2^53, so the Float64 powers sum exactly.
+_MAX_ID_LENGTH = 10
+
+# Depot's API does not report a job's runs-on, so every attempt is costed as the default sandbox.
+_DEFAULT_SANDBOX_LABELS = '["depot-ubuntu-24.04"]'
+
+# Depot reports no repository id. Any positive id on both sides lets the runs builder accept the
+# pull request association as the run's own.
+_REPOSITORY_ID = 1
+
+
+def _is_id(column: str) -> str:
+ return f"match(ifNull({column}, ''), '^[{_ID_ALPHABET}]{{1,{_MAX_ID_LENGTH}}}$')"
+
+
+def _id_to_int(column: str) -> str:
+ # ClickHouse cannot sum an array of Nullable values, so the Nullable column is unwrapped first.
+ value = f"ifNull({column}, '')"
+ chars = f"splitByString('', {value})"
+ digits = f"arrayMap((c, i) -> (position('{_ID_ALPHABET}', c) - 1) * pow(30, length({value}) - i), {chars}, arrayEnumerate({chars}))"
+ return f"toInt(arraySum({digits}))"
+
+
+def _conclusion(status: str) -> str:
+ # Depot's terminal statuses in GitHub's conclusion vocabulary. `cancelled` and `skipped` are
+ # already the same word in both.
+ return f"multiIf({status} = 'finished', 'success', {status} = 'failed', 'failure', {status})"
+
+
+def _attempts(depot: DepotJobAttempts, pull_requests_table: str | None) -> str:
+ # Depot reports no branch, so a PR run takes its head branch from the PR snapshot, and branch
+ # filters then match it like a GitHub run of the same PR.
+ pr_number = "ifNull(toInt(extract(a.ref, '^refs/pull/([0-9]+)/')), 0)"
+ if pull_requests_table:
+ head_branch = "nullIf(pr.head_branch, '')"
+ branch_join = f"""
+ LEFT JOIN (
+ SELECT number, any(JSONExtractString(ifNull(head, '{{}}'), 'ref')) AS head_branch
+ FROM {pull_requests_table}
+ GROUP BY number
+ ) AS pr ON {pr_number} = pr.number"""
+ else:
+ head_branch = "NULL"
+ branch_join = ""
+ # A push run's id carries a prefix outside the alphabet, and such a run holds no workflows.
+ return f"""(
+ SELECT
+ {_id_to_int("if(a.run_workflow_count = 1, a.run_id, a.workflow_id)")} AS github_run_id,
+ {_id_to_int("a.attempt_id")} AS github_job_id,
+ {pr_number} AS pr_number,
+ {head_branch} AS head_branch,
+ a.repo AS repo,
+ a.head_sha AS head_sha,
+ a.workflow_name AS workflow_name,
+ a.workflow_status AS workflow_status,
+ a.workflow_created_at AS workflow_created_at,
+ a.workflow_started_at AS workflow_started_at,
+ a.workflow_finished_at AS workflow_finished_at,
+ a.job_key AS job_key,
+ a.job_display_name AS job_display_name,
+ a.attempt AS attempt,
+ a.attempt_status AS attempt_status,
+ a.attempt_started_at AS attempt_started_at,
+ a.attempt_finished_at AS attempt_finished_at,
+ a.sandbox_id AS sandbox_id
+ FROM {depot.table} AS a
+ {branch_join}
+ WHERE lower(ifNull(a.repo, '')) = '{depot.repository.lower()}'
+ AND {_is_id("a.run_id")} AND {_is_id("a.workflow_id")} AND {_is_id("a.attempt_id")}
+ )"""
+
+
+def _runs(attempts: str) -> str:
+ return f"""
+ SELECT
+ github_run_id AS id,
+ any(workflow_name) AS name,
+ any(head_sha) AS head_sha,
+ any(head_branch) AS head_branch,
+ 'completed' AS status,
+ {_conclusion("any(workflow_status)")} AS conclusion,
+ any(workflow_created_at) AS created_at,
+ any(workflow_started_at) AS run_started_at,
+ any(workflow_finished_at) AS updated_at,
+ max(attempt) AS run_attempt,
+ if(
+ any(pr_number) > 0,
+ concat('[{{"number":', toString(any(pr_number)), ',"base":{{"repo":{{"id":{_REPOSITORY_ID}}}}}}}]'),
+ '[]'
+ ) AS pull_requests,
+ concat('{{"id":{_REPOSITORY_ID},"full_name":"', any(repo), '"}}') AS repository,
+ NULL AS head_commit,
+ NULL AS actor
+ FROM {attempts}
+ GROUP BY github_run_id
+ """
+
+
+def _jobs(attempts: str) -> str:
+ return f"""
+ SELECT
+ github_job_id AS id,
+ github_run_id AS run_id,
+ attempt AS run_attempt,
+ if(ifNull(job_display_name, '') != '', job_display_name, job_key) AS name,
+ workflow_name,
+ if(ifNull(attempt_finished_at, '') != '', 'completed', 'in_progress') AS status,
+ {_conclusion("attempt_status")} AS conclusion,
+ head_sha,
+ head_branch,
+ '{_DEFAULT_SANDBOX_LABELS}' AS labels,
+ sandbox_id AS runner_name,
+ NULL AS runner_group_name,
+ -- Depot reports no queue time for an attempt, so it counts as created when it starts.
+ attempt_started_at AS created_at,
+ attempt_started_at AS started_at,
+ attempt_finished_at AS completed_at,
+ NULL AS steps
+ FROM {attempts}
+ """
+
+
+def _union(github_table: str, columns: dict[str, dict[str, str]], depot_select: str) -> str:
+ # UNION ALL matches columns by position, so the GitHub side names them in the contract order the
+ # Depot side follows.
+ return f"(SELECT {', '.join(columns)} FROM {github_table} UNION ALL {depot_select})"
+
+
+def with_depot_runs(runs_table: str, depot: DepotJobAttempts | None, pull_requests_table: str | None = None) -> str:
+ """The GitHub runs table, or a subquery that also holds the Depot CI runs when they are synced."""
+ if depot is None:
+ return runs_table
+ return _union(runs_table, WORKFLOW_RUNS_COLUMNS, _runs(_attempts(depot, pull_requests_table)))
+
+
+def with_depot_jobs(jobs_table: str, depot: DepotJobAttempts | None) -> str:
+ """The GitHub jobs table, or a subquery that also holds the Depot CI job attempts when they are synced.
+
+ Depot job rows carry no branch: branch filters read the run's branch, and the jobs builder scans
+ its source twice, so a PR snapshot lookup here would cost two full PR scans for a column no
+ filter reads.
+ """
+ if depot is None:
+ return jobs_table
+ return _union(jobs_table, WORKFLOW_JOBS_COLUMNS, _jobs(_attempts(depot, pull_requests_table=None)))
diff --git a/products/engineering_analytics/backend/logic/views/job_costs.py b/products/engineering_analytics/backend/logic/views/job_costs.py
index 53085eea7277..273c11d18620 100644
--- a/products/engineering_analytics/backend/logic/views/job_costs.py
+++ b/products/engineering_analytics/backend/logic/views/job_costs.py
@@ -301,5 +301,5 @@ def build_team_view(team: "Team") -> str | None:
sources = resolve_job_source_tables(team)
if not sources:
return None
- selects = [build_query(jobs_table=source.workflow_jobs, runs_table=source.workflow_runs) for source in sources]
+ selects = [build_query(jobs_table=source.jobs_source, runs_table=source.runs_source) for source in sources]
return "\nUNION ALL\n".join(selects)
diff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.py
index ed88d908be7f..6f429b5cecfa 100644
--- a/products/engineering_analytics/backend/logic/views/source_schema.py
+++ b/products/engineering_analytics/backend/logic/views/source_schema.py
@@ -87,6 +87,35 @@ WORKFLOW_JOBS_COLUMNS: dict[str, dict[str, str]] = {
"steps": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},
}
+# Contract for the Depot source's ``job_attempts`` table: one row per Depot CI job attempt, the
+# columns ``views.depot_ci`` reshapes into the two GitHub contracts above. Ids are Depot's strings.
+DEPOT_JOB_ATTEMPTS_COLUMNS: dict[str, dict[str, str]] = {
+ **{
+ name: {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"}
+ for name in (
+ "run_id",
+ "repo",
+ "ref",
+ "head_sha",
+ "workflow_id",
+ "workflow_name",
+ "workflow_status",
+ "workflow_created_at",
+ "workflow_started_at",
+ "workflow_finished_at",
+ "job_key",
+ "job_display_name",
+ "attempt_id",
+ "attempt_status",
+ "attempt_started_at",
+ "attempt_finished_at",
+ "sandbox_id",
+ )
+ },
+ "attempt": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},
+ "run_workflow_count": {"clickhouse": "Nullable(Int64)", "hogql": "IntegerDatabaseField"},
+}
+
# Contract for the ``github_issue_events`` warehouse source: immutable issue/PR events, every
# type kept (a source-side filter would pin the desc-walk watermark). ``actor`` / ``issue`` are
# the nested GitHub objects verbatim as JSON. Same Nullable/string discipline as above.
diff --git a/products/engineering_analytics/backend/tests/_github_fixtures.py b/products/engineering_analytics/backend/tests/_github_fixtures.py
index 2e4aa3a9e9d6..32ecdbe0839a 100644
--- a/products/engineering_analytics/backend/tests/_github_fixtures.py
+++ b/products/engineering_analytics/backend/tests/_github_fixtures.py
@@ -76,6 +76,18 @@ def create_trunk_source(
)
+def create_depot_source(team: Team, *, prefix: str = "depot_", repository: str = "") -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team=team,
+ source_id="depot-source",
+ connection_id="depot-source",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=ExternalDataSourceType.DEPOT,
+ prefix=prefix,
+ job_inputs={"repository": repository} if repository else {},
+ )
+
+
def _quarantined_row(*, file: str, name: str, classname: str, parent: str) -> dict[str, Any]:
return {
"file": file,
diff --git a/products/engineering_analytics/backend/tests/test_logic_sources.py b/products/engineering_analytics/backend/tests/test_logic_sources.py
index fc052a37ba28..1969a28d40f8 100644
--- a/products/engineering_analytics/backend/tests/test_logic_sources.py
+++ b/products/engineering_analytics/backend/tests/test_logic_sources.py
@@ -9,6 +9,7 @@ from posthog.models.team import Team
from products.engineering_analytics.backend.facade import api
from products.engineering_analytics.backend.facade.contracts import GitHubSource, GitHubSourceNotConnectedError
from products.engineering_analytics.backend.logic.sources import (
+ DEPOT_JOB_ATTEMPTS_SCHEMA,
ISSUE_EVENTS_SCHEMA,
PULL_REQUESTS_SCHEMA,
TEAM_MEMBERS_SCHEMA,
@@ -22,12 +23,14 @@ from products.engineering_analytics.backend.logic.sources import (
resolve_job_source_tables,
resolve_team_membership_table,
)
+from products.engineering_analytics.backend.logic.views.depot_ci import DepotJobAttempts
from products.engineering_analytics.backend.logic.views.source_schema import (
PULL_REQUESTS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
)
from products.engineering_analytics.backend.tests._github_fixtures import (
_pr_row,
+ create_depot_source,
create_warehouse_table_row,
link_schema,
)
@@ -487,6 +490,14 @@ class TestMultiRepoGitHubResolution(BaseTest):
"posthog/other": [(WORKFLOW_RUNS_SCHEMA, True)],
},
)
+ # A Depot source joins only the repository it syncs, matched case-insensitively.
+ depot = create_depot_source(self.team, prefix="ci", repository="posthog/PostHog")
+ link_schema(
+ self.team,
+ depot,
+ name=DEPOT_JOB_ATTEMPTS_SCHEMA,
+ table=create_warehouse_table_row(self.team, name="cidepot_job_attempts", source=depot),
+ )
# pull_requests stays None here: these views qualify on jobs + runs, so a repo reaches them
# with no PR snapshot and the run builder's PR attribution degrades to the message suffix.
assert set(resolve_job_source_tables(self.team)) == {
@@ -495,6 +506,7 @@ class TestMultiRepoGitHubResolution(BaseTest):
workflow_runs="costgithub_posthog_posthog_workflow_runs",
pull_requests=None,
source_id=str(source.id),
+ depot_job_attempts=DepotJobAttempts(table="cidepot_job_attempts", repository="posthog/posthog"),
),
JobSourceTables(
workflow_jobs="costgithub_posthog_posthog_com_workflow_jobs",
diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.py
index 314feac55986..0ee6dfa687bc 100644
--- a/products/engineering_analytics/backend/tests/test_views.py
+++ b/products/engineering_analytics/backend/tests/test_views.py
@@ -14,10 +14,19 @@ from products.engineering_analytics.backend.logic.sources import (
list_github_sources,
resolve_trunk_merge_queue_table,
)
-from products.engineering_analytics.backend.logic.views import pull_requests, trunk_quarantined_tests, workflow_runs
+from products.engineering_analytics.backend.logic.views import (
+ depot_ci,
+ job_costs,
+ pull_requests,
+ trunk_quarantined_tests,
+ workflow_jobs,
+ workflow_runs,
+)
from products.engineering_analytics.backend.logic.views.source_schema import (
+ DEPOT_JOB_ATTEMPTS_COLUMNS,
PULL_REQUESTS_COLUMNS,
TRUNK_QUARANTINED_TESTS_COLUMNS,
+ WORKFLOW_JOBS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
)
from products.engineering_analytics.backend.tests._github_fixtures import (
@@ -229,6 +238,126 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
# Spoofed shape without the queue actor: attribution stays on the run's own association.
assert rows[4][6:] == (9002, 0)
+ def test_depot_ci_attempts_read_as_runs_jobs_and_cost(self) -> None:
+ runs_table = self._create_table("github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [])
+ jobs_table = self._create_table("github_workflow_jobs", WORKFLOW_JOBS_COLUMNS, [])
+
+ prs_table = self._create_table(
+ "github_pull_requests",
+ PULL_REQUESTS_COLUMNS,
+ [_pr_row(101991, "octocat", "open", 0, "2026-09-24T14:00:00Z", head_ref="feature/depot")],
+ )
+
+ def attempt(
+ attempt_id: str,
+ attempt: int,
+ status: str,
+ started: str,
+ finished: str,
+ *,
+ run_id: str = "427q556wmn",
+ run_workflow_count: int = 1,
+ workflow_id: str = "6n4tghls33",
+ workflow_name: str = "Backend CI on Depot",
+ workflow_status: str = "failed",
+ ref: str = "refs/pull/101991/merge",
+ display_name: str = "Product tests (experiments)",
+ repo: str = "PostHog/posthog",
+ ) -> dict[str, str | int]:
+ return {
+ "run_id": run_id,
+ "run_workflow_count": run_workflow_count,
+ "repo": repo,
+ "ref": ref,
+ "head_sha": "abc123",
+ "workflow_id": workflow_id,
+ "workflow_name": workflow_name,
+ "workflow_status": workflow_status,
+ "workflow_created_at": "2026-09-24T14:51:17.948Z",
+ "workflow_started_at": "2026-09-24T14:51:18.000Z",
+ "workflow_finished_at": "2026-09-24T15:01:18.000Z",
+ "job_key": "ci-backend.yml:turbo-tests:matrix-38",
+ "job_display_name": display_name,
+ "attempt_id": attempt_id,
+ "attempt": attempt,
+ "attempt_status": status,
+ "attempt_started_at": started,
+ "attempt_finished_at": finished,
+ "sandbox_id": "sandbox",
+ }
+
+ schedule: dict[str, Any] = {"run_id": "bbbbbbbbbb", "run_workflow_count": 2, "ref": "refs/heads/master"}
+ depot_table = self._create_table(
+ "depot_job_attempts",
+ DEPOT_JOB_ATTEMPTS_COLUMNS,
+ [
+ attempt("zf6sbbn2wh", 1, "failed", "2026-09-24T14:53:00.000Z", "2026-09-24T14:55:00.000Z"),
+ attempt("3v4pbsqvfc", 2, "finished", "2026-09-24T14:56:00.000Z", "2026-09-24T14:59:00.000Z"),
+ # A job with no display name falls back to its key.
+ attempt(
+ "b82nsv77wl", 1, "finished", "2026-09-24T14:52:00.000Z", "2026-09-24T14:52:30.000Z", display_name=""
+ ),
+ # A run with two workflows keys each one by its own id, so no join on the id fans out.
+ attempt(
+ "q28m5dl5rg",
+ 1,
+ "finished",
+ "2026-09-24T14:52:00.000Z",
+ "2026-09-24T14:53:00.000Z",
+ workflow_id="cccccccccc",
+ workflow_name="Monitor",
+ workflow_status="finished",
+ **schedule,
+ ),
+ attempt(
+ "h8qn5x801q",
+ 1,
+ "failed",
+ "2026-09-24T14:52:00.000Z",
+ "2026-09-24T14:53:00.000Z",
+ workflow_id="dddddddddd",
+ workflow_name="Timing",
+ workflow_status="failed",
+ **schedule,
+ ),
+ # Synced before the source moved to another repository, so no read of this one keeps it.
+ attempt(
+ "k3w9v2rq8b",
+ 1,
+ "finished",
+ "2026-09-24T14:52:00.000Z",
+ "2026-09-24T14:53:00.000Z",
+ run_id="zzzzzzzzzz",
+ repo="PostHog/other",
+ ),
+ ],
+ )
+ depot = depot_ci.DepotJobAttempts(table=depot_table, repository="PostHog/posthog")
+ runs = depot_ci.with_depot_runs(runs_table, depot, prs_table)
+ jobs = depot_ci.with_depot_jobs(jobs_table, depot)
+
+ # 80213453736890 is the GITHUB_RUN_ID Depot CI gave run 427q556wmn, as its per-test traces report it.
+ assert self._select(
+ "SELECT id, workflow_name, conclusion, pr_number, head_branch, duration_seconds, repo_owner, run_attempt "
+ f"FROM ({workflow_runs.build_query(runs)}) AS r ORDER BY id"
+ ) == [
+ (80213453736890, "Backend CI on Depot", "failure", 101991, "feature/depot", 600, "PostHog", 2),
+ (223978965517241, "Monitor", "success", 0, None, 600, "PostHog", 1),
+ (244340689655172, "Timing", "failure", 0, None, 600, "PostHog", 1),
+ ]
+ assert self._select(
+ "SELECT run_id, run_attempt, name, conclusion, duration_seconds, is_rerun_copy "
+ f"FROM ({workflow_jobs.build_query(jobs)}) AS j WHERE run_id = 80213453736890 ORDER BY started_at"
+ ) == [
+ (80213453736890, 1, "ci-backend.yml:turbo-tests:matrix-38", "success", 30, 0),
+ (80213453736890, 1, "Product tests (experiments)", "failure", 120, 0),
+ (80213453736890, 2, "Product tests (experiments)", "success", 180, 0),
+ ]
+ assert self._select(
+ "SELECT DISTINCT provider, vcpu, estimated_cost_usd > 0 "
+ f"FROM ({job_costs.build_query(jobs_table=jobs, runs_table=runs)}) AS c"
+ ) == [("depot", 2, 1)]
+
def test_pull_requests_view_handles_null_user(self) -> None:
# The real source lands user as Nullable(String), NULL for a PR by a deleted GitHub account.
# JSONExtractString over a NULL Nullable returns NULL, so the builder must ifNull-guard it to
diff --git a/products/engineering_analytics/backend/tests/test_warehouse_view_sync.py b/products/engineering_analytics/backend/tests/test_warehouse_view_sync.py
index d2c8f06ca40a..47d5c94be148 100644
--- a/products/engineering_analytics/backend/tests/test_warehouse_view_sync.py
+++ b/products/engineering_analytics/backend/tests/test_warehouse_view_sync.py
@@ -1,12 +1,17 @@
from posthog.test.base import BaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.db import InterfaceError, OperationalError
from parameterized import parameterized
from products.data_modeling.backend.facade.models import DataWarehouseManagedViewSet
-from products.engineering_analytics.backend.logic.sources import WORKFLOW_JOBS_SCHEMA, WORKFLOW_RUNS_SCHEMA
+from products.engineering_analytics.backend.logic.sources import (
+ DEPOT_JOB_ATTEMPTS_SCHEMA,
+ WORKFLOW_JOBS_SCHEMA,
+ WORKFLOW_RUNS_SCHEMA,
+)
+from products.engineering_analytics.backend.tests._github_fixtures import create_depot_source
from products.engineering_analytics.backend.warehouse_view_sync import sync_engineering_analytics_views
from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource
from products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKind, ExternalDataSourceType
@@ -85,10 +90,17 @@ class TestSyncEngineeringAnalyticsViews(BaseTest):
mock_sync.assert_not_called()
assert not self._has_viewset()
+ @parameterized.expand([("github_jobs", False), ("depot_attempts", True)])
@patch.object(DataWarehouseManagedViewSet, "sync_views")
- def test_creates_viewset_and_syncs_for_qualifying_source(self, mock_sync) -> None:
+ def test_creates_viewset_and_syncs_for_qualifying_source(
+ self, _name: str, from_depot: bool, mock_sync: MagicMock
+ ) -> None:
source = self._qualifying_source()
schema = ExternalDataSchema.objects.get(source=source, name=WORKFLOW_JOBS_SCHEMA)
+ if from_depot:
+ # A Depot load adds its attempts to the views' SQL, so it must re-sync them too.
+ source = create_depot_source(self.team, prefix=PREFIX)
+ schema = self._schema(source, DEPOT_JOB_ATTEMPTS_SCHEMA, self._table(f"{PREFIX}depot_job_attempts", source))
sync_engineering_analytics_views(schema, source)
diff --git a/products/engineering_analytics/backend/warehouse_view_sync.py b/products/engineering_analytics/backend/warehouse_view_sync.py
index aabc579dbc66..812148c6de32 100644
--- a/products/engineering_analytics/backend/warehouse_view_sync.py
+++ b/products/engineering_analytics/backend/warehouse_view_sync.py
@@ -17,7 +17,11 @@ from posthog.exceptions_capture import capture_exception
from products.data_modeling.backend.facade.models import DataWarehouseManagedViewSet
from products.engineering_analytics.backend.facade.warehouse_views import get_expected_warehouse_views
-from products.engineering_analytics.backend.logic.sources import WORKFLOW_JOBS_SCHEMA, WORKFLOW_RUNS_SCHEMA
+from products.engineering_analytics.backend.logic.sources import (
+ DEPOT_JOB_ATTEMPTS_SCHEMA,
+ WORKFLOW_JOBS_SCHEMA,
+ WORKFLOW_RUNS_SCHEMA,
+)
from products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKind, ExternalDataSourceType
if TYPE_CHECKING:
@@ -25,9 +29,12 @@ if TYPE_CHECKING:
logger = structlog.get_logger(__name__)
-# The view joins both endpoints, so only a load of one of them can change its contents. Ignore
-# every other schema (pull_requests, and non-GitHub sources) so unrelated syncs stay cheap.
-_RELEVANT_SCHEMAS = (WORKFLOW_RUNS_SCHEMA, WORKFLOW_JOBS_SCHEMA)
+# The view joins both endpoints and the Depot CI attempts, so only a load of one of them can change
+# its contents. Ignore every other schema so unrelated syncs stay cheap.
+_RELEVANT_SCHEMAS: dict[str, tuple[str, ...]] = {
+ ExternalDataSourceType.GITHUB: (WORKFLOW_RUNS_SCHEMA, WORKFLOW_JOBS_SCHEMA),
+ ExternalDataSourceType.DEPOT: (DEPOT_JOB_ATTEMPTS_SCHEMA,),
+}
def sync_engineering_analytics_views(schema: ExternalDataSchema, source: ExternalDataSource) -> None:
@@ -39,7 +46,7 @@ def sync_engineering_analytics_views(schema: ExternalDataSchema, source: Externa
yet has no view to expose, so the viewset row isn't created until both endpoints exist.
"""
try:
- if source.source_type != ExternalDataSourceType.GITHUB or schema.name not in _RELEVANT_SCHEMAS:
+ if schema.name not in _RELEVANT_SCHEMAS.get(source.source_type, ()):
return
managed_viewset = DataWarehouseManagedViewSet.objects.filter(