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.

fix(warehouse): fix depot ci sync gaps and reads (#106828)

Raúl Negrón-Oterod9394c4ec577
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 9e665fd7d425..ca98455861e8 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -193,7 +193,7 @@ Warehouse tables (GitHub source):
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.
+- `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 a PR snapshot lookup in the jobs builder would add two full PR scans to every jobs read; a read that joins a job to its run takes the branch through `workflow_jobs.branch`, which falls back to the run's. Depot numbers attempts per job, not per run, so a job's last attempt is listed again under each later attempt of its run, as GitHub lists a job it did not re-run; the jobs builder flags those rows as `is_rerun_copy`. 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:
diff --git a/products/engineering_analytics/backend/logic/queries/job_aggregates.py b/products/engineering_analytics/backend/logic/queries/job_aggregates.py
index 62b1bd81942d..0fb8668f76ca 100644
--- a/products/engineering_analytics/backend/logic/queries/job_aggregates.py
+++ b/products/engineering_analytics/backend/logic/queries/job_aggregates.py
@@ -5,9 +5,8 @@ suffix stripped in SQL with the same rule the frontend's jobGroups uses), with q
p50 (created -> started, where runner-capacity problems hide), duration percentiles
(successful jobs only — the shared DURATION_PERCENTILE_CONDITION population),
failure rate, retry pressure, run share (conditional jobs skip — "runs in 31% of
-runs"), and billable cost. Jobs carry ``workflow_name`` / ``head_branch`` /
-``created_at`` directly, so no join to the runs table is needed; the run-share
-denominator comes from a cheap runs count.
+runs"), and billable cost, all from one scan of the per-job cost source. The
+run-share denominator comes from a cheap runs count.
Unexpanded ``${{ matrix.* }}`` template names (skipped matrices) are collapsed for
grouping the same way the frontend does.
@@ -21,7 +20,6 @@ from products.engineering_analytics.backend.facade.contracts import WorkflowHeal
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_float
from products.engineering_analytics.backend.logic.queries._workflow_filters import (
DURATION_PERCENTILE_CONDITION,
- UNPAGED_SCAN_LIMIT,
branch_filter_clause,
cost_run_scope_filter_clause,
date_to_filter_clause,
@@ -51,62 +49,42 @@ def _job_name_expr(column: str) -> str:
return _JOB_NAME_TEMPLATE.replace("__NAME__", column)
+# One scan of the shared per-job cost source. It joins each job to its run, so the run-scope filters can
+# read the run's attributes, and the job stats and the billable cost read the same rows.
_AGGREGATE_SELECT = f"""
SELECT
- {_job_name_expr("name")} AS job_name,
+ {_job_name_expr("job_name")} AS job_group,
count() AS job_count,
- uniq(name) AS shard_count,
+ uniq(job_name) AS shard_count,
uniq(run_id) AS runs_in,
quantileIf(0.5)(queue_seconds, {_QUEUED_JOB_CONDITION}) AS queue_p50_seconds,
quantileIf(0.5)(duration_seconds, {DURATION_PERCENTILE_CONDITION}) AS p50_seconds,
quantileIf(0.95)(duration_seconds, {DURATION_PERCENTILE_CONDITION}) AS p95_seconds,
-- Jobs without a verdict (skipped, cancelled, neutral) stay in job_count but not in the rate.
{failure_rate_expr()} AS failure_rate,
- countIf(run_attempt > 1) AS retry_job_count
- FROM __JOBS_SOURCE__ AS j
+ countIf(run_attempt > 1) AS retry_job_count,
+ sum(ifNull(billable_seconds, 0)) AS billable_seconds,
+ sumIf(estimated_cost_usd, estimated_cost_usd IS NOT NULL) AS cost_sum,
+ countIf(estimated_cost_usd IS NOT NULL) AS costed_jobs
+ FROM __COST_SOURCE__ AS c
-- NOT is_rerun_copy: "Re-run failed jobs" re-lists every already-passed job under the new attempt
-- with the earlier attempt's timestamps. Counting those would double every duration sample and
- -- report retry pressure for jobs nobody retried.
+ -- report retry pressure for jobs nobody retried. A copy carries no cost, so the filter leaves the cost as is.
WHERE NOT is_rerun_copy
AND workflow_name = {{workflow_name}} AND created_at >= {{date_from}} __DATE_TO__ __BRANCH__
- __JOBS_RUN_SCOPE__
- GROUP BY job_name
+ __COST_RUN_SCOPE__
+ GROUP BY job_group
ORDER BY job_count DESC
LIMIT {_LIMIT}
"""
-# Billable cost per de-sharded job name, read straight off the shared per-job cost source (the same
-# rendered model as engineering_analytics_job_costs) so cost is computed once in SQL, not folded from
-# raw labels in Python. Cost columns are per-job on that source, so summing them per job name is exact.
-_COST_SELECT = f"""
- SELECT
- {_job_name_expr("job_name")} AS job_name,
- sum(ifNull(billable_seconds, 0)) AS billable_seconds,
- sumIf(estimated_cost_usd, estimated_cost_usd IS NOT NULL) AS cost_sum,
- countIf(estimated_cost_usd IS NOT NULL) AS costed_jobs
- FROM __COST_SOURCE__ AS c
- WHERE workflow_name = {{workflow_name}} AND created_at >= {{date_from}} __DATE_TO__ __BRANCH__
- __COST_RUN_SCOPE__
- GROUP BY job_name
- LIMIT {UNPAGED_SCAN_LIMIT}
-"""
-
-_RUNS_WINDOW = (
- "workflow_name = {workflow_name} AND run_started_at >= {date_from}"
- " __RUNS_DATE_TO__ __RUNS_BRANCH__ __RUNS_RUN_SCOPE__"
-)
-
-_RUN_COUNT_SELECT = f"""
+_RUN_COUNT_SELECT = """
SELECT count() AS total_runs
FROM __RUNS_SOURCE__ AS r
- WHERE {_RUNS_WINDOW}
+ WHERE workflow_name = {workflow_name} AND run_started_at >= {date_from}
+ __RUNS_DATE_TO__ __RUNS_BRANCH__ __RUNS_RUN_SCOPE__
"""
-# The jobs source carries no attribution or merge-queue column, so a job can only be scoped through
-# the run it belongs to. The subquery reuses the run-count window so both sides of the jobs table read
-# the same population.
-_RUNS_SCOPE_SUBQUERY = f"AND run_id IN (SELECT id FROM __RUNS_SOURCE__ AS r WHERE {_RUNS_WINDOW})"
-
def query_job_aggregates(
*,
@@ -117,13 +95,12 @@ def query_job_aggregates(
branch: str | None,
run_scope: WorkflowHealthRunScope = WorkflowHealthRunScope.ALL,
) -> list[WorkflowJobAggregate]:
- # Both templates window the job's OWN created_at, but this query EXCLUDES re-run copies, and a copy
- # is only recognisable while its original attempt is still in the scan: a re-run a day or more after
- # the original push would otherwise pull the copy inside the window, drop the original below a tight
+ # The query windows the job's OWN created_at, but it EXCLUDES re-run copies, and a copy is only
+ # recognisable while its original attempt is still in the scan: a re-run a day or more after the
+ # original push would otherwise pull the copy inside the window, drop the original below a tight
# floor, and count the copy as an execution. So take the wide floor, same as the cost surfaces.
- jobs_source = curated.jobs_source(created_floor=True)
cost_source = curated.job_cost_source(created_floor=True)
- if jobs_source is None or cost_source is None:
+ if cost_source is None:
return []
branch = branch.strip() if branch else None
@@ -132,29 +109,22 @@ def query_job_aggregates(
"date_from": ast.Constant(value=date_from),
"job_created_floor": run_windowed_job_created_floor_constant(date_from),
}
- # Shared filter clauses (each registers its own placeholder). The jobs/cost templates window and
- # branch-filter on the per-job created_at + head_branch; the run-count template reads the run
- # source's run_started_at (its head_branch is still the per-run branch).
+ # Each clause registers its own placeholder. The job template windows the job's created_at, and the
+ # run-count template the run's run_started_at.
date_to_clause = date_to_filter_clause(date_to, placeholders, column="created_at")
runs_date_to_clause = date_to_filter_clause(date_to, placeholders, column="run_started_at")
branch_clause = branch_filter_clause(branch, placeholders, column="head_branch")
- runs_branch_clause = branch_filter_clause(branch, placeholders, column="head_branch")
- runs_run_scope_clause = run_scope_filter_clause(run_scope)
- cost_run_scope_clause = cost_run_scope_filter_clause(run_scope)
- jobs_run_scope_clause = _RUNS_SCOPE_SUBQUERY if runs_run_scope_clause else ""
def fill(template: str) -> str:
return (
- template.replace("__JOBS_SOURCE__", jobs_source)
- .replace("__COST_SOURCE__", cost_source)
- .replace("__JOBS_RUN_SCOPE__", jobs_run_scope_clause)
- .replace("__COST_RUN_SCOPE__", cost_run_scope_clause)
- .replace("__RUNS_RUN_SCOPE__", runs_run_scope_clause)
+ template.replace("__COST_SOURCE__", cost_source)
+ .replace("__COST_RUN_SCOPE__", cost_run_scope_filter_clause(run_scope))
+ .replace("__RUNS_RUN_SCOPE__", run_scope_filter_clause(run_scope))
.replace("__RUNS_SOURCE__", curated.run_source())
.replace("__DATE_TO__", date_to_clause)
.replace("__RUNS_DATE_TO__", runs_date_to_clause)
.replace("__BRANCH__", branch_clause)
- .replace("__RUNS_BRANCH__", runs_branch_clause)
+ .replace("__RUNS_BRANCH__", branch_clause)
)
response = curated.run(
@@ -168,18 +138,6 @@ def query_job_aggregates(
)
total_runs = run_count_response.results[0][0] if run_count_response.results else 0
- # Billable cost per de-sharded job name, summed in SQL over the shared per-job cost source.
- cost_response = curated.run(
- fill(_COST_SELECT), query_type="engineering_analytics.job_aggregates_cost", placeholders=placeholders
- )
- billable_by_job: dict[str, tuple[float, float]] = {}
- for job_name, billable_seconds, cost_sum, costed_jobs in cost_response.results or []:
- # No costed job (every instance github-hosted, non-Linux, or still queued) → leave the cost
- # unknown rather than billing a not-yet-finished/non-billable job as $0.
- if not costed_jobs:
- continue
- billable_by_job[job_name] = (float(billable_seconds or 0.0), float(cost_sum or 0.0))
-
items: list[WorkflowJobAggregate] = []
for (
job_name,
@@ -191,8 +149,10 @@ def query_job_aggregates(
p95_seconds,
failure_rate,
retry_job_count,
+ billable_seconds,
+ cost_sum,
+ costed_jobs,
) in response.results:
- billable = billable_by_job.get(job_name)
items.append(
WorkflowJobAggregate(
job_name=job_name,
@@ -205,8 +165,10 @@ def query_job_aggregates(
p95_seconds=opt_float(p95_seconds),
failure_rate=opt_float(failure_rate),
retry_job_count=retry_job_count,
- billable_minutes=billable[0] / 60 if billable else None,
- estimated_cost_usd=billable[1] if billable else None,
+ # No costed job (every instance github-hosted, non-Linux, or still queued) leaves the cost
+ # unknown rather than billing a not-yet-finished or non-billable job as $0.
+ billable_minutes=float(billable_seconds or 0.0) / 60 if costed_jobs else None,
+ estimated_cost_usd=float(cost_sum or 0.0) if costed_jobs else None,
)
)
return items
diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.py
index b49738e01d88..dc197d328233 100644
--- a/products/engineering_analytics/backend/logic/sources.py
+++ b/products/engineering_analytics/backend/logic/sources.py
@@ -21,7 +21,7 @@ to read a specific source; otherwise the oldest source's repos are tried first,
import re
from collections.abc import Iterable, Iterator
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from typing import TYPE_CHECKING, NamedTuple
from uuid import UUID
@@ -205,10 +205,12 @@ def resolve_github_tables(
@dataclass(frozen=True)
class JobSourceTables:
- """One qualifying repo's job-level warehouse tables, for the exposed per-job views."""
+ """One qualifying repo's job-level warehouse tables, for the exposed per-job views. Read runs and
+ jobs through ``runs_source`` and ``jobs_source``, which add the repo's Depot CI; the ``github_``
+ tables hold GitHub Actions alone."""
- workflow_jobs: str
- workflow_runs: str
+ github_workflow_jobs: str
+ github_workflow_runs: str
# Optional: these views qualify on jobs + runs alone, so a repo can reach them with no PR
# snapshot. Consumers that enrich from it (default-branch PR attribution) degrade without it.
pull_requests: str | None = None
@@ -220,12 +222,12 @@ class JobSourceTables:
@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)
+ return depot_ci.with_depot_runs(self.github_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)
+ return depot_ci.with_depot_jobs(self.github_workflow_jobs, self.depot_job_attempts)
def resolve_job_source_tables(team: Team) -> list[JobSourceTables]:
@@ -239,29 +241,28 @@ def resolve_job_source_tables(team: Team) -> list[JobSourceTables]:
one source syncs several repos. Userless (the view sync runs in a system/Temporal context);
team scoping is the boundary.
"""
- resolved: list[JobSourceTables] = []
- depot_tables = resolve_depot_job_attempts_tables(team)
+ entries: list[tuple[str, JobSourceTables]] = []
for source in _github_sources(team):
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)
if runs and jobs:
- resolved.append(
- JobSourceTables(
- workflow_jobs=jobs,
- workflow_runs=runs,
- pull_requests=tables.get(PULL_REQUESTS_SCHEMA),
- 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),
- )
+ entry = JobSourceTables(
+ github_workflow_jobs=jobs,
+ github_workflow_runs=runs,
+ pull_requests=tables.get(PULL_REQUESTS_SCHEMA),
+ issue_events=tables.get(ISSUE_EVENTS_SCHEMA),
+ reviews=tables.get(REVIEWS_SCHEMA),
+ source_id=str(source.id),
)
- return resolved
+ entries.append((repository, entry))
+ # The views union every entry, so a repository that two GitHub sources sync takes its Depot table on
+ # one entry only, or every Depot job and its cost would count twice. Entries with the PR snapshot go
+ # first, because the friction view reads only those entries.
+ entries.sort(key=lambda repository_entry: repository_entry[1].pull_requests is None)
+ depot_tables = resolve_depot_job_attempts_tables(team)
+ return [replace(entry, depot_job_attempts=depot_tables.pop(repository, None)) for repository, entry in entries]
@dataclass(frozen=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 39fb4eae04c9..50ed7cc6f265 100644
--- a/products/engineering_analytics/backend/logic/views/ci_job_history.py
+++ b/products/engineering_analytics/backend/logic/views/ci_job_history.py
@@ -146,7 +146,7 @@ def build_query(
j.name AS job_name,
j.run_id AS run_id,
j.run_attempt AS run_attempt,
- j.head_branch AS head_branch,
+ {workflow_jobs.branch("j", "r")} AS head_branch,
r.head_sha AS head_sha,
j.status AS status,
j.conclusion AS conclusion,
@@ -186,7 +186,7 @@ def build_team_view(team: "Team") -> str | None:
jobs_table=source.jobs_source,
runs_table=source.runs_source,
pull_requests_table=source.pull_requests,
- head_commit_runs_table=source.workflow_runs,
+ head_commit_runs_table=source.github_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
index 8a674f095945..1a9e61af5a5b 100644
--- a/products/engineering_analytics/backend/logic/views/depot_ci.py
+++ b/products/engineering_analytics/backend/logic/views/depot_ci.py
@@ -122,6 +122,7 @@ def _attempts(depot: DepotJobAttempts, pull_requests_table: str | None) -> str:
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_id AS depot_job_id,
a.job_key AS job_key,
a.job_display_name AS job_display_name,
a.attempt AS attempt,
@@ -163,26 +164,40 @@ def _runs(attempts: str) -> str:
def _jobs(attempts: str) -> str:
+ # GitHub lists every job of a run under each run attempt. A job that a run attempt did not re-run keeps
+ # the timestamps of the attempt that ran, and the jobs builder flags that row as a copy. Depot numbers
+ # attempts per job, so each job's last attempt is listed again under every later attempt of its run.
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,
+ a.github_job_id AS id,
+ a.github_run_id AS run_id,
+ toInt(arrayJoin(range(a.attempt, if(a.attempt = last.job_attempt, last.run_attempt, a.attempt) + 1))) AS run_attempt,
+ if(ifNull(a.job_display_name, '') != '', a.job_display_name, a.job_key) AS name,
+ a.workflow_name AS workflow_name,
+ if(ifNull(a.attempt_finished_at, '') != '', 'completed', 'in_progress') AS status,
+ {_conclusion("a.attempt_status")} AS conclusion,
+ a.head_sha AS head_sha,
+ a.head_branch AS head_branch,
'{_DEFAULT_SANDBOX_LABELS}' AS labels,
- sandbox_id AS runner_name,
+ a.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,
+ a.attempt_started_at AS created_at,
+ a.attempt_started_at AS started_at,
+ a.attempt_finished_at AS completed_at,
NULL AS steps
- FROM {attempts}
+ FROM {attempts} AS a
+ INNER JOIN (
+ SELECT jobs.depot_job_id AS depot_job_id, jobs.job_attempt AS job_attempt, runs.run_attempt AS run_attempt
+ FROM (
+ SELECT github_run_id, depot_job_id, max(attempt) AS job_attempt
+ FROM {attempts}
+ GROUP BY github_run_id, depot_job_id
+ ) AS jobs
+ INNER JOIN (
+ SELECT github_run_id, max(attempt) AS run_attempt FROM {attempts} GROUP BY github_run_id
+ ) AS runs ON jobs.github_run_id = runs.github_run_id
+ ) AS last ON a.depot_job_id = last.depot_job_id
"""
@@ -192,7 +207,7 @@ def _union(github_table: str, columns: dict[str, dict[str, str]], depot_select:
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:
+def with_depot_runs(runs_table: str, depot: DepotJobAttempts | None, pull_requests_table: str | 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
@@ -202,9 +217,9 @@ def with_depot_runs(runs_table: str, depot: DepotJobAttempts | None, pull_reques
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.
+ Depot job rows carry no branch: the jobs builder scans its source twice, so a PR snapshot lookup here
+ would cost two PR scans per jobs read. A reader that joins a job to its run reads the branch through
+ ``workflow_jobs.branch``, which falls back to the run's.
"""
if depot is None:
return jobs_table
diff --git a/products/engineering_analytics/backend/logic/views/job_costs.py b/products/engineering_analytics/backend/logic/views/job_costs.py
index 273c11d18620..beb6f190d289 100644
--- a/products/engineering_analytics/backend/logic/views/job_costs.py
+++ b/products/engineering_analytics/backend/logic/views/job_costs.py
@@ -268,7 +268,7 @@ def build_query(
j.name AS job_name,
j.run_id AS run_id,
j.run_attempt AS run_attempt,
- j.head_branch AS head_branch,
+ {workflow_jobs.branch("j", "r")} AS head_branch,
j.status AS status,
j.conclusion AS conclusion,
j.runner_name AS runner_name,
diff --git a/products/engineering_analytics/backend/logic/views/pr_friction.py b/products/engineering_analytics/backend/logic/views/pr_friction.py
index 0037e105814c..e8a2672ed459 100644
--- a/products/engineering_analytics/backend/logic/views/pr_friction.py
+++ b/products/engineering_analytics/backend/logic/views/pr_friction.py
@@ -432,7 +432,7 @@ def build_team_view(team: "Team") -> str | None:
return None
# Each SELECT carries its own WITH, so each sits in its own subquery to keep the CTE names apart.
return "\nUNION ALL\n".join(
- f"SELECT * FROM ({build_query(source_id=source.source_id, pull_requests_table=source.pull_requests, workflow_runs_table=source.workflow_runs, workflow_jobs_table=source.workflow_jobs, issue_events_table=source.issue_events, reviews_table=source.reviews)})"
+ f"SELECT * FROM ({build_query(source_id=source.source_id, pull_requests_table=source.pull_requests, workflow_runs_table=source.runs_source, workflow_jobs_table=source.jobs_source, issue_events_table=source.issue_events, reviews_table=source.reviews)})"
for source in sources
if source.pull_requests
)
diff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.py
index 6f429b5cecfa..b15f5a00fce2 100644
--- a/products/engineering_analytics/backend/logic/views/source_schema.py
+++ b/products/engineering_analytics/backend/logic/views/source_schema.py
@@ -103,6 +103,7 @@ DEPOT_JOB_ATTEMPTS_COLUMNS: dict[str, dict[str, str]] = {
"workflow_created_at",
"workflow_started_at",
"workflow_finished_at",
+ "job_id",
"job_key",
"job_display_name",
"attempt_id",
diff --git a/products/engineering_analytics/backend/logic/views/workflow_jobs.py b/products/engineering_analytics/backend/logic/views/workflow_jobs.py
index 4cb5722cf861..5adee9ae8de2 100644
--- a/products/engineering_analytics/backend/logic/views/workflow_jobs.py
+++ b/products/engineering_analytics/backend/logic/views/workflow_jobs.py
@@ -64,6 +64,12 @@ _FIRST_STEP_STARTED_AT = (
)
+def branch(jobs_alias: str, runs_alias: str) -> str:
+ """A job's branch: its own, else its run's. A reader that joins a job to its run reads this, because
+ Depot CI job rows carry no branch."""
+ return f"coalesce(nullIf({jobs_alias}.head_branch, ''), {runs_alias}.head_branch)"
+
+
def build_query(table_name: str, *, created_floor: bool = False) -> str:
# The floor must live in its OWN innermost SELECT on the raw string column, like the runs
# builder's: the parsing SELECT below aliases parseDateTimeBestEffort(created_at) AS created_at,
diff --git a/products/engineering_analytics/backend/tests/_github_fixtures.py b/products/engineering_analytics/backend/tests/_github_fixtures.py
index 32ecdbe0839a..088180eb9e0d 100644
--- a/products/engineering_analytics/backend/tests/_github_fixtures.py
+++ b/products/engineering_analytics/backend/tests/_github_fixtures.py
@@ -23,7 +23,10 @@ from products.engineering_analytics.backend.logic.sources import (
WORKFLOW_RUNS_SCHEMA,
GitHubTables,
)
-from products.engineering_analytics.backend.logic.views.source_schema import WORKFLOW_JOBS_COLUMNS
+from products.engineering_analytics.backend.logic.views.source_schema import (
+ DEPOT_JOB_ATTEMPTS_COLUMNS,
+ WORKFLOW_JOBS_COLUMNS,
+)
from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource
from products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
@@ -76,6 +79,22 @@ def create_trunk_source(
)
+def _depot_attempt_row(**overrides: Any) -> dict[str, Any]:
+ return (
+ dict.fromkeys(DEPOT_JOB_ATTEMPTS_COLUMNS)
+ | {
+ "run_id": "427q556wmn",
+ "run_workflow_count": 1,
+ "repo": "PostHog/posthog",
+ "workflow_id": "6n4tghls33",
+ "job_id": "p4kd9tq2xs",
+ "attempt_id": "zf6sbbn2wh",
+ "attempt": 1,
+ }
+ | overrides
+ )
+
+
def create_depot_source(team: Team, *, prefix: str = "depot_", repository: str = "") -> ExternalDataSource:
return ExternalDataSource.objects.create(
team=team,
diff --git a/products/engineering_analytics/backend/tests/_logic_helpers.py b/products/engineering_analytics/backend/tests/_logic_helpers.py
index 0984d39b2225..4f31fd08d4c2 100644
--- a/products/engineering_analytics/backend/tests/_logic_helpers.py
+++ b/products/engineering_analytics/backend/tests/_logic_helpers.py
@@ -12,7 +12,9 @@ from django.utils import timezone
import pandas as pd
+from products.engineering_analytics.backend.logic.sources import DEPOT_JOB_ATTEMPTS_SCHEMA
from products.engineering_analytics.backend.logic.views.source_schema import (
+ DEPOT_JOB_ATTEMPTS_COLUMNS,
PULL_REQUESTS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
)
@@ -20,6 +22,7 @@ from products.engineering_analytics.backend.tests._github_fixtures import (
GITHUB_SOURCE_PREFIX,
_pr_row,
_run_row,
+ create_depot_source,
create_github_source,
link_schema,
seeding_object_storage,
@@ -209,6 +212,20 @@ class _WarehouseMixin(ClickhouseTestMixin, BaseTest):
# sources (Trunk) pass their endpoint's schema name explicitly.
link_schema(self.team, source, name=schema_name or base_name.removeprefix("github_"), table=table)
+ def _create_depot_table(self, rows: list[dict[str, Any]]) -> None:
+ # A Depot source joins the GitHub source that syncs the same repository.
+ if self._github_source is None:
+ self._github_source = create_github_source(self.team, repository="PostHog/posthog")
+ depot = create_depot_source(self.team, prefix="ci", repository="PostHog/posthog")
+ self._create_table(
+ "depot_job_attempts",
+ DEPOT_JOB_ATTEMPTS_COLUMNS,
+ rows,
+ source=depot,
+ prefix="ci",
+ schema_name=DEPOT_JOB_ATTEMPTS_SCHEMA,
+ )
+
class _EndpointsWarehouseMixin(_WarehouseMixin):
"""End-to-end aggregates over real warehouse tables. Seeds dates relative to
diff --git a/products/engineering_analytics/backend/tests/test_logic_sources.py b/products/engineering_analytics/backend/tests/test_logic_sources.py
index 1969a28d40f8..ce3cc1d47e97 100644
--- a/products/engineering_analytics/backend/tests/test_logic_sources.py
+++ b/products/engineering_analytics/backend/tests/test_logic_sources.py
@@ -490,7 +490,20 @@ class TestMultiRepoGitHubResolution(BaseTest):
"posthog/other": [(WORKFLOW_RUNS_SCHEMA, True)],
},
)
- # A Depot source joins only the repository it syncs, matched case-insensitively.
+ # A later source syncs PostHog/posthog again, with the PR snapshot.
+ with_prs = self._multi_repo_source(
+ prefix="prs",
+ legacy_repository="PostHog/posthog",
+ repos={
+ "PostHog/posthog": [
+ (WORKFLOW_RUNS_SCHEMA, True),
+ (WORKFLOW_JOBS_SCHEMA, True),
+ (PULL_REQUESTS_SCHEMA, True),
+ ]
+ },
+ )
+ # A Depot source joins only the repository it syncs, matched case-insensitively, and only one
+ # entry for it: the one with the PR snapshot, which the friction view reads.
depot = create_depot_source(self.team, prefix="ci", repository="posthog/PostHog")
link_schema(
self.team,
@@ -502,15 +515,21 @@ class TestMultiRepoGitHubResolution(BaseTest):
# with no PR snapshot and the run builder's PR attribution degrades to the message suffix.
assert set(resolve_job_source_tables(self.team)) == {
JobSourceTables(
- workflow_jobs="costgithub_posthog_posthog_workflow_jobs",
- workflow_runs="costgithub_posthog_posthog_workflow_runs",
+ github_workflow_jobs="costgithub_posthog_posthog_workflow_jobs",
+ github_workflow_runs="costgithub_posthog_posthog_workflow_runs",
pull_requests=None,
source_id=str(source.id),
+ ),
+ JobSourceTables(
+ github_workflow_jobs="prsgithub_posthog_posthog_workflow_jobs",
+ github_workflow_runs="prsgithub_posthog_posthog_workflow_runs",
+ pull_requests="prsgithub_posthog_posthog_pull_requests",
+ source_id=str(with_prs.id),
depot_job_attempts=DepotJobAttempts(table="cidepot_job_attempts", repository="posthog/posthog"),
),
JobSourceTables(
- workflow_jobs="costgithub_posthog_posthog_com_workflow_jobs",
- workflow_runs="costgithub_posthog_posthog_com_workflow_runs",
+ github_workflow_jobs="costgithub_posthog_posthog_com_workflow_jobs",
+ github_workflow_runs="costgithub_posthog_posthog_com_workflow_runs",
pull_requests=None,
source_id=str(source.id),
),
diff --git a/products/engineering_analytics/backend/tests/test_logic_workflows.py b/products/engineering_analytics/backend/tests/test_logic_workflows.py
index 8f5795ac1014..acf45efc0782 100644
--- a/products/engineering_analytics/backend/tests/test_logic_workflows.py
+++ b/products/engineering_analytics/backend/tests/test_logic_workflows.py
@@ -24,6 +24,7 @@ from products.engineering_analytics.backend.logic.views.source_schema import (
WORKFLOW_RUNS_COLUMNS,
)
from products.engineering_analytics.backend.tests._github_fixtures import (
+ _depot_attempt_row,
_issue_event_row,
_pr_row,
_run_row,
@@ -1176,6 +1177,41 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):
e2e = next(j for j in jobs if j.name == "e2e")
assert e2e.runner_provider == "github_hosted" and e2e.estimated_cost_usd is None
+ def test_job_aggregates_branch_filter_matches_depot_jobs_through_their_run(self) -> None:
+ started, completed = _ago_with_duration(1, 120)
+ self._create_depot_table(
+ [
+ _depot_attempt_row(
+ ref="refs/pull/65/merge",
+ head_sha="sha65",
+ workflow_name="CI",
+ workflow_status="finished",
+ workflow_created_at=started,
+ workflow_started_at=started,
+ workflow_finished_at=completed,
+ job_key="ci.yml:lint",
+ attempt_status="finished",
+ attempt_started_at=started,
+ attempt_finished_at=completed,
+ )
+ ]
+ )
+ self._create_table(
+ "github_pull_requests",
+ PULL_REQUESTS_COLUMNS,
+ [_pr_row(65, "alice", "open", 0, _ago(1), head_sha="sha65", head_ref="feature/depot")],
+ )
+ self._create_table(
+ "github_workflow_runs",
+ WORKFLOW_RUNS_COLUMNS,
+ [_run_row(9800, "CI", "sha-main", "completed", "success", _ago(1), _ago(1), head_branch="main")],
+ )
+ self._create_table("github_workflow_jobs", WORKFLOW_JOBS_COLUMNS, [_job_row(98000, 9800, "build", "success")])
+
+ aggregates = api.list_job_aggregates(team=self.team, workflow_name="CI", branch="feature/depot")
+
+ assert [aggregate.job_name for aggregate in aggregates] == ["ci.yml:lint"]
+
def test_job_aggregates_rate_and_queue_time_use_verdicts(self) -> None:
self._create_table(
"github_pull_requests",
diff --git a/products/engineering_analytics/backend/tests/test_pr_friction.py b/products/engineering_analytics/backend/tests/test_pr_friction.py
index 23dc4ac3288d..f81ead42194a 100644
--- a/products/engineering_analytics/backend/tests/test_pr_friction.py
+++ b/products/engineering_analytics/backend/tests/test_pr_friction.py
@@ -2,6 +2,8 @@ from collections import Counter, defaultdict
from datetime import UTC, datetime, timedelta
from typing import Any
+from parameterized import parameterized
+
from posthog.hogql.query import execute_hogql_query
from products.engineering_analytics.backend.facade.contracts import (
@@ -19,7 +21,12 @@ from products.engineering_analytics.backend.logic.views.source_schema import (
WORKFLOW_JOBS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
)
-from products.engineering_analytics.backend.tests._github_fixtures import _issue_event_row, _pr_row, _run_row
+from products.engineering_analytics.backend.tests._github_fixtures import (
+ _depot_attempt_row,
+ _issue_event_row,
+ _pr_row,
+ _run_row,
+)
from products.engineering_analytics.backend.tests._logic_helpers import (
_ago,
_ago_offset_with_duration,
@@ -212,7 +219,30 @@ class TestPRFrictionView(_WarehouseMixin):
assert response.columns == list(pr_friction.FIELDS)
return {row[2]: dict(zip(response.columns, row)) for row in response.results}
- def test_view_matches_the_timeline_replay(self) -> None:
+ def _seed_depot_ci(self) -> None:
+ start, end = _span(0, 15)
+ self._create_depot_table(
+ [
+ _depot_attempt_row(
+ ref="refs/pull/36/merge",
+ head_sha="sha36",
+ workflow_name="Backend CI on Depot",
+ workflow_status="failed",
+ workflow_created_at=start,
+ workflow_started_at=start,
+ workflow_finished_at=end,
+ job_key="ci-backend.yml:lint",
+ attempt_status="failed",
+ attempt_started_at=start,
+ attempt_finished_at=end,
+ )
+ ]
+ )
+
+ @parameterized.expand([("github_ci", False), ("depot_ci", True)])
+ def test_view_matches_the_timeline_replay(self, _name: str, with_depot_ci: bool) -> None:
+ if with_depot_ci:
+ self._seed_depot_ci()
self._seed()
rows = self._view_rows()
timelines = query_pull_request_timelines(
@@ -251,6 +281,8 @@ class TestPRFrictionView(_WarehouseMixin):
assert set(timeline_figures) == {31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44}
assert view_figures == timeline_figures
+ if with_depot_ci:
+ assert view_figures[36]["ci_running"] > 0
def test_view_counts_what_the_author_went_through(self) -> None:
self._seed()
diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.py
index 0ee6dfa687bc..0d53bfd65c4f 100644
--- a/products/engineering_analytics/backend/tests/test_views.py
+++ b/products/engineering_analytics/backend/tests/test_views.py
@@ -15,6 +15,7 @@ from products.engineering_analytics.backend.logic.sources import (
resolve_trunk_merge_queue_table,
)
from products.engineering_analytics.backend.logic.views import (
+ ci_job_history,
depot_ci,
job_costs,
pull_requests,
@@ -255,6 +256,7 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
started: str,
finished: str,
*,
+ job_id: str = "p4kd9tq2xs",
run_id: str = "427q556wmn",
run_workflow_count: int = 1,
workflow_id: str = "6n4tghls33",
@@ -276,6 +278,7 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
"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_id": job_id,
"job_key": "ci-backend.yml:turbo-tests:matrix-38",
"job_display_name": display_name,
"attempt_id": attempt_id,
@@ -295,7 +298,13 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
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=""
+ "b82nsv77wl",
+ 1,
+ "finished",
+ "2026-09-24T14:52:00.000Z",
+ "2026-09-24T14:52:30.000Z",
+ job_id="t7m3xc4pzb",
+ display_name="",
),
# A run with two workflows keys each one by its own id, so no join on the id fans out.
attempt(
@@ -304,6 +313,7 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
"finished",
"2026-09-24T14:52:00.000Z",
"2026-09-24T14:53:00.000Z",
+ job_id="w2hq8vn5cd",
workflow_id="cccccccccc",
workflow_name="Monitor",
workflow_status="finished",
@@ -315,6 +325,7 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
"failed",
"2026-09-24T14:52:00.000Z",
"2026-09-24T14:53:00.000Z",
+ job_id="x9fz3kr7bm",
workflow_id="dddddddddd",
workflow_name="Timing",
workflow_status="failed",
@@ -327,6 +338,7 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
"finished",
"2026-09-24T14:52:00.000Z",
"2026-09-24T14:53:00.000Z",
+ job_id="y6tc2pw4hn",
run_id="zzzzzzzzzz",
repo="PostHog/other",
),
@@ -347,16 +359,23 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
]
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"
+ f"FROM ({workflow_jobs.build_query(jobs)}) AS j WHERE run_id = 80213453736890 ORDER BY started_at, run_attempt"
) == [
(80213453736890, 1, "ci-backend.yml:turbo-tests:matrix-38", "success", 30, 0),
+ # Listed again under the run's second attempt, like a job GitHub did not re-run.
+ (80213453736890, 2, "ci-backend.yml:turbo-tests:matrix-38", "success", 30, 1),
(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)]
+ "SELECT DISTINCT provider, vcpu, estimated_cost_usd > 0, head_branch, is_rerun_copy "
+ f"FROM ({job_costs.build_query(jobs_table=jobs, runs_table=runs)}) AS c WHERE run_id = 80213453736890 "
+ "ORDER BY is_rerun_copy"
+ ) == [("depot", 2, 1, "feature/depot", 0), ("depot", 2, 0, "feature/depot", 1)]
+ assert self._select(
+ "SELECT DISTINCT head_branch "
+ f"FROM ({ci_job_history.build_query(jobs_table=jobs, runs_table=runs)}) AS h WHERE run_id = 80213453736890"
+ ) == [("feature/depot",)]
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.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/depot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/depot.py
index 96ad1d8c2774..8f3d310da29f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/depot.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/depot.py
@@ -21,12 +21,15 @@ JSONObject = dict[str, Any]
DEPOT_CI_SERVICE_URL = "https://api.depot.dev/depot.ci.v1.CIService"
REQUEST_TIMEOUT_SECONDS = 60
-LIST_RUNS_PAGE_SIZE = 200
-IN_FLIGHT_STATUSES = ["queued", "running"]
+# When a ListRuns page ends inside a second, the next page skips that second's other runs. A walk with
+# another page size ends its pages elsewhere and returns most of them; a run both walks skip is lost
+# until Depot fixes its cursor. Depot caps pages at 100.
+LIST_RUNS_PAGE_SIZES = (100, 57)
TERMINAL_STATUSES = ["finished", "failed", "cancelled"]
-# Depot can leave a run in `queued` and never start it. A queued run older than this counts as stuck,
-# so it does not hold the sync horizon back. A running run always holds it, because its jobs time out.
-QUEUED_MAX_AGE = dt.timedelta(hours=6)
+# Depot can leave a run queued or running forever. A real run can take hours, but a real queued run
+# starts in minutes, so past these ages an in-flight run counts as stuck.
+IN_FLIGHT_MAX_AGE = {"queued": dt.timedelta(hours=6), "running": dt.timedelta(hours=24)}
+IN_FLIGHT_STATUSES = list(IN_FLIGHT_MAX_AGE)
# Connect sends every RPC as a POST. Every RPC this source calls is a read, so a retry is as safe as
# a retried GET.
@@ -58,8 +61,8 @@ def _parse_timestamp(value: dt.datetime | str) -> dt.datetime:
return parsed
-def _list_runs(session: Session, repository: str, statuses: list[str]) -> Iterator[JSONObject]:
- body: JSONObject = {"repo": repository, "status": statuses, "pageSize": LIST_RUNS_PAGE_SIZE}
+def _walk_runs(session: Session, repository: str, statuses: list[str], page_size: int) -> Iterator[JSONObject]:
+ body: JSONObject = {"repo": repository, "status": statuses, "pageSize": page_size}
while True:
page = _call(session, "ListRuns", body)
yield from page.get("runs", [])
@@ -69,31 +72,49 @@ def _list_runs(session: Session, repository: str, statuses: list[str]) -> Iterat
body = {**body, "pageToken": next_page_token}
-# The sync only takes runs created before every recent in-flight run, so the watermark never passes
-# a run that has not finished and each run is fetched once, after it is terminal. A job that is
-# retried after its run was synced is therefore never picked up.
-def _in_flight_horizon(session: Session, repository: str, now: dt.datetime) -> dt.datetime:
+def _list_runs(
+ session: Session, repository: str, statuses: list[str], created_after: dt.datetime | None = None
+) -> list[tuple[dt.datetime, JSONObject]]:
+ """Oldest first. ListRuns has no time filter, but it lists newest first, so each walk stops at the
+ first run older than ``created_after``. The second walk's copy of a run wins, as the fresher status."""
+ runs: dict[str, tuple[dt.datetime, JSONObject]] = {}
+ for page_size in LIST_RUNS_PAGE_SIZES:
+ listed = 0
+ for run in _walk_runs(session, repository, statuses, page_size):
+ created_at = _parse_timestamp(run["createdAt"])
+ if created_after is not None and created_at < created_after:
+ break
+ runs[run["runId"]] = (created_at, run)
+ listed += 1
+ if listed < page_size:
+ # No page end inside the listing, so nothing was skipped.
+ break
+ return sorted(runs.values(), key=lambda entry: (entry[0], entry[1]["runId"]))
+
+
+# The watermark stays behind every run still going, because a run it passed is never read. A stuck run
+# with no workflows is the exception: it can never produce rows, and holding for it would stop every
+# sync. A job retried after its run synced is not read again.
+def _in_flight_horizon(
+ session: Session, repository: str, now: dt.datetime, logger: FilteringBoundLogger
+) -> dt.datetime:
horizon = now
- for run in _list_runs(session, repository, IN_FLIGHT_STATUSES):
- created_at = _parse_timestamp(run["createdAt"])
- if run["status"] == "running" or created_at > now - QUEUED_MAX_AGE:
- horizon = min(horizon, created_at)
+ for created_at, run in _list_runs(session, repository, IN_FLIGHT_STATUSES):
+ if created_at < now - IN_FLIGHT_MAX_AGE.get(run["status"], IN_FLIGHT_MAX_AGE["queued"]):
+ if not _call(session, "GetRunStatus", {"runId": run["runId"]}).get("workflows"):
+ continue
+ logger.warning("depot_ci.stuck_run_holds_horizon", run_id=run["runId"], created_at=created_at.isoformat())
+ horizon = min(horizon, created_at)
return horizon
def _runs_to_sync(
session: Session, repository: str, created_after: dt.datetime | None, created_before: dt.datetime
) -> list[JSONObject]:
- runs: list[JSONObject] = []
- # ListRuns has no time filter but returns terminal runs newest first, so the walk stops at the
- # first run at or before the lower bound, and reversing the walk yields the runs oldest first.
- for run in _list_runs(session, repository, TERMINAL_STATUSES):
- created_at = _parse_timestamp(run["createdAt"])
- if created_after is not None and created_at <= created_after:
- break
- if created_at < created_before:
- runs.append(run)
- return runs[::-1]
+ # Depot stamps runs in whole seconds, and a sync that stopped partway through a second saved it as
+ # the watermark, so that second is read again. The merge on attempt_id drops the repeats.
+ runs = _list_runs(session, repository, TERMINAL_STATUSES, created_after)
+ return [run for created_at, run in runs if created_at < created_before]
def _attempt_rows(run: JSONObject, workflow: JSONObject, run_workflow_count: int) -> list[JSONObject]:
@@ -167,7 +188,7 @@ def depot_source(
def items() -> Iterator[list[JSONObject]]:
session = _make_session(api_token)
- horizon = _in_flight_horizon(session, repository, dt.datetime.now(dt.UTC))
+ horizon = _in_flight_horizon(session, repository, dt.datetime.now(dt.UTC), logger)
runs = _runs_to_sync(session, repository, lower_bound, horizon)
logger.info(
"depot_ci.runs_to_sync",
@@ -188,6 +209,8 @@ def depot_source(
partition_format="week",
partition_keys=[RUN_CREATED_AT],
sort_mode="asc",
+ # The watermark saves per chunk, and the default chunk holds a whole first sync of a busy repository.
+ chunk_size=5_000,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/tests/test_depot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/tests/test_depot.py
index ba811d802492..98828cc801bd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/tests/test_depot.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/tests/test_depot.py
@@ -51,13 +51,11 @@ def _single_attempt_workflow(run: dict[str, Any]) -> dict[str, Any]:
def _fake_session(
- terminal_pages: list[list[dict[str, Any]]],
+ terminal_runs: list[dict[str, Any]],
in_flight_runs: list[dict[str, Any]] | None = None,
workflows_by_run: dict[str, list[dict[str, Any]]] | None = None,
) -> mock.MagicMock:
- workflows = workflows_by_run or {
- run["runId"]: [_single_attempt_workflow(run)] for page in terminal_pages for run in page
- }
+ workflows = workflows_by_run or {run["runId"]: [_single_attempt_workflow(run)] for run in terminal_runs}
workflows_by_id = {workflow["workflowId"]: workflow for runs in workflows.values() for workflow in runs}
def post(url: str, json: dict[str, Any], timeout: float) -> Response:
@@ -65,9 +63,14 @@ def _fake_session(
if method == "ListRuns" and json["status"] == IN_FLIGHT:
return _response(200, {"runs": in_flight_runs or []}, method)
if method == "ListRuns":
- page_index = int(json.get("pageToken", "0"))
- next_page_token = str(page_index + 1) if page_index + 1 < len(terminal_pages) else ""
- return _response(200, {"runs": terminal_pages[page_index], "nextPageToken": next_page_token}, method)
+ # Depot's cursor: a page that ends inside a second makes the next page skip the rest of it.
+ start = int(json.get("pageToken", "0"))
+ page = terminal_runs[start : start + json["pageSize"]]
+ end = start + len(page)
+ while page and end < len(terminal_runs) and terminal_runs[end]["createdAt"] == page[-1]["createdAt"]:
+ end += 1
+ next_page_token = str(end) if end < len(terminal_runs) else ""
+ return _response(200, {"runs": page, "nextPageToken": next_page_token}, method)
if method == "GetRunStatus":
run_workflows = workflows.get(json["runId"], [])
return _response(200, {"workflows": [{"workflowId": w["workflowId"]} for w in run_workflows]}, method)
@@ -96,18 +99,22 @@ def _synced_rows(session: mock.MagicMock, created_after: dt.datetime | str | Non
# Newest first, the order ListRuns returns terminal runs in.
-TERMINAL_PAGES = [
- [_run("r6", dt.timedelta(minutes=10)), _run("r5", dt.timedelta(hours=1))],
- [_run("r4", dt.timedelta(hours=2)), _run("r3", dt.timedelta(hours=3))],
- [_run("r2", dt.timedelta(hours=4)), _run("r1", dt.timedelta(hours=5))],
- [_run("r0", dt.timedelta(days=6))],
+TERMINAL_RUNS = [
+ _run("r6", dt.timedelta(minutes=10)),
+ _run("r5", dt.timedelta(hours=1)),
+ _run("r4", dt.timedelta(hours=2)),
+ _run("r3", dt.timedelta(hours=3)),
+ _run("r2", dt.timedelta(hours=4)),
+ _run("r1", dt.timedelta(hours=5)),
+ _run("r0", dt.timedelta(days=6)),
]
-WATERMARK = NOW - dt.timedelta(hours=4)
+# Between r3 and r2, so no run can tie it.
+WATERMARK = NOW - dt.timedelta(hours=3, minutes=30)
RECENT_IN_FLIGHT = {**_run("in-flight", dt.timedelta(minutes=90)), "status": "queued"}
-STALE_QUEUED = {**_run("stale", dt.timedelta(days=30)), "status": "queued"}
+QUEUED_PAST_CUTOFF = {**_run("queued-7h", dt.timedelta(hours=7)), "status": "queued"}
LONG_RUNNING = {**_run("long", dt.timedelta(minutes=150)), "status": "running"}
-# Older than the queued cutoff, and still running, so it holds the horizon.
-VERY_LONG_RUNNING = {**_run("very-long", dt.timedelta(hours=7)), "status": "running"}
+RUNNING_INSIDE_CUTOFF = {**_run("running-23h", dt.timedelta(hours=23)), "status": "running"}
+RUNNING_PAST_CUTOFF = {**_run("running-25h", dt.timedelta(hours=25)), "status": "running"}
class TestDepotSource:
@@ -116,37 +123,46 @@ class TestDepotSource:
[
([], ["r3", "r4", "r5", "r6"]),
([RECENT_IN_FLIGHT], ["r3", "r4"]),
- ([STALE_QUEUED], ["r3", "r4", "r5", "r6"]),
- ([STALE_QUEUED, RECENT_IN_FLIGHT], ["r3", "r4"]),
+ ([QUEUED_PAST_CUTOFF], ["r3", "r4", "r5", "r6"]),
+ ([RECENT_IN_FLIGHT, QUEUED_PAST_CUTOFF], ["r3", "r4"]),
([LONG_RUNNING], ["r3"]),
- ([VERY_LONG_RUNNING], []),
+ ([RUNNING_INSIDE_CUTOFF], []),
+ ([RUNNING_PAST_CUTOFF], ["r3", "r4", "r5", "r6"]),
],
)
def test_syncs_only_runs_created_before_the_oldest_recent_in_flight_run(
self, in_flight_runs: list[dict[str, Any]], expected_run_ids: list[str]
) -> None:
- session = _fake_session(TERMINAL_PAGES, in_flight_runs)
+ session = _fake_session(TERMINAL_RUNS, in_flight_runs)
rows = _synced_rows(session, WATERMARK)
assert [row["run_id"] for row in rows] == expected_run_ids
+ def test_a_stuck_run_with_workflows_still_holds_the_horizon(self) -> None:
+ stuck = {**_run("stuck", dt.timedelta(days=30)), "status": "running"}
+ workflows = {run["runId"]: [_single_attempt_workflow(run)] for run in [*TERMINAL_RUNS, stuck]}
+ session = _fake_session(TERMINAL_RUNS, [stuck], workflows_by_run=workflows)
+
+ assert _synced_rows(session, WATERMARK) == []
+
@pytest.mark.parametrize(
"created_after, expected_run_ids, expected_terminal_pages",
[
- (WATERMARK, ["r3", "r4", "r5", "r6"], 3),
- (_iso(WATERMARK), ["r3", "r4", "r5", "r6"], 3),
- (None, ["r0", "r1", "r2", "r3", "r4", "r5", "r6"], 4),
+ (WATERMARK, ["r3", "r4", "r5", "r6"], 5),
+ (TERMINAL_RUNS[4]["createdAt"], ["r2", "r3", "r4", "r5", "r6"], 5),
+ (None, ["r0", "r1", "r2", "r3", "r4", "r5", "r6"], 7),
],
# The bounds derive from the wall clock, so fixed ids keep every xdist worker collecting the same tests.
- ids=["datetime_watermark", "string_watermark", "no_watermark"],
+ ids=["datetime_watermark", "watermark_in_a_runs_second", "no_watermark"],
)
def test_walks_terminal_runs_down_to_the_lower_bound_and_yields_them_oldest_first(
self, created_after: dt.datetime | str | None, expected_run_ids: list[str], expected_terminal_pages: int
) -> None:
- session = _fake_session(TERMINAL_PAGES)
+ session = _fake_session(TERMINAL_RUNS)
- rows = _synced_rows(session, created_after)
+ with mock.patch(f"{MODULE}.LIST_RUNS_PAGE_SIZES", (2, 3)):
+ rows = _synced_rows(session, created_after)
assert [row["run_id"] for row in rows] == expected_run_ids
terminal_list_calls = [
@@ -154,22 +170,50 @@ class TestDepotSource:
]
assert len(terminal_list_calls) == expected_terminal_pages
+ @pytest.mark.parametrize(
+ "page_sizes, expected_run_ids",
+ [
+ ((3,), ["oldest", "tied-0", "tied-1", "newest"]),
+ ((3, 4), ["oldest", "tied-0", "tied-1", "tied-2", "newest"]),
+ ],
+ ids=["one_walk_skips_the_rest_of_the_second", "a_second_walk_returns_it"],
+ )
+ def test_a_second_walk_returns_runs_a_page_end_skips(
+ self, page_sizes: tuple[int, ...], expected_run_ids: list[str]
+ ) -> None:
+ runs = [
+ _run("newest", dt.timedelta(minutes=10)),
+ *[_run(f"tied-{index}", dt.timedelta(hours=1)) for index in range(3)],
+ _run("oldest", dt.timedelta(hours=2)),
+ ]
+ session = _fake_session(runs)
+
+ with mock.patch(f"{MODULE}.LIST_RUNS_PAGE_SIZES", page_sizes):
+ rows = _synced_rows(session, None)
+
+ assert [row["run_id"] for row in rows] == expected_run_ids
+
def test_request_shapes(self) -> None:
- session = _fake_session(TERMINAL_PAGES[:2])
+ session = _fake_session(TERMINAL_RUNS[:4])
- with mock.patch(f"{MODULE}.make_tracked_session", return_value=session) as make_session:
+ with (
+ mock.patch(f"{MODULE}.make_tracked_session", return_value=session) as make_session,
+ mock.patch(f"{MODULE}.LIST_RUNS_PAGE_SIZES", (2, 3)),
+ ):
_batches(depot_source(API_TOKEN, REPOSITORY, None, mock.MagicMock()))
assert make_session.call_args.kwargs["headers"] == {"Authorization": f"Bearer {API_TOKEN}"}
assert API_TOKEN in make_session.call_args.kwargs["redact_values"]
# Every Depot RPC is a POST, which the shared retry leaves out, so a 429 must still retry.
assert make_session.call_args.kwargs["retry"].is_retry("POST", 429)
- assert _requests(session)[:3] == [
- ("ListRuns", {"repo": REPOSITORY, "status": IN_FLIGHT, "pageSize": 200}),
- ("ListRuns", {"repo": REPOSITORY, "status": TERMINAL, "pageSize": 200}),
- ("ListRuns", {"repo": REPOSITORY, "status": TERMINAL, "pageSize": 200, "pageToken": "1"}),
+ assert _requests(session)[:5] == [
+ ("ListRuns", {"repo": REPOSITORY, "status": IN_FLIGHT, "pageSize": 2}),
+ ("ListRuns", {"repo": REPOSITORY, "status": TERMINAL, "pageSize": 2}),
+ ("ListRuns", {"repo": REPOSITORY, "status": TERMINAL, "pageSize": 2, "pageToken": "2"}),
+ ("ListRuns", {"repo": REPOSITORY, "status": TERMINAL, "pageSize": 3}),
+ ("ListRuns", {"repo": REPOSITORY, "status": TERMINAL, "pageSize": 3, "pageToken": "3"}),
]
- assert _requests(session)[3:5] == [("GetRunStatus", {"runId": "r3"}), ("GetWorkflow", {"workflowId": "r3-wf"})]
+ assert _requests(session)[5:7] == [("GetRunStatus", {"runId": "r3"}), ("GetWorkflow", {"workflowId": "r3-wf"})]
def test_flattens_one_row_per_attempt_of_every_workflow_in_the_run(self) -> None:
run = _run("run-1", dt.timedelta(hours=1))
@@ -221,7 +265,7 @@ class TestDepotSource:
"workflowId": "wf-2",
"jobs": [{"jobId": "job-report", "attempts": [{"attemptId": "attempt-3"}]}],
}
- session = _fake_session([[run]], workflows_by_run={"run-1": [backend, report]})
+ session = _fake_session([run], workflows_by_run={"run-1": [backend, report]})
rows = _synced_rows(session, None)