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.

perf(engineering-analytics): bound the hand-off shell filter (#110283)

Raúl Negrón-Otero31324972b179
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index 84ab5f4bf2a9..3e86e6fe54ce 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -280,7 +280,7 @@ class CuratedGitHubSource:
self._tables.workflow_jobs,
)
- def _jobs_table(self, workflow_jobs_table: str) -> str:
+ def _jobs_table(self, workflow_jobs_table: str) -> workflow_jobs.JobsTable:
return depot_ci.with_depot_jobs(workflow_jobs_table, self._depot_job_attempts(), self._tables.workflow_runs)
def trunk_merge_queue_source(self) -> str | None:
diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.py
index 5b38438daee0..c4b12c67df00 100644
--- a/products/engineering_analytics/backend/logic/sources.py
+++ b/products/engineering_analytics/backend/logic/sources.py
@@ -31,7 +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.engineering_analytics.backend.logic.views import depot_ci, workflow_jobs
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
@@ -227,7 +227,7 @@ class JobSourceTables:
)
@property
- def jobs_source(self) -> str:
+ def jobs_source(self) -> workflow_jobs.JobsTable:
"""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.github_workflow_jobs, self.depot_job_attempts, self.github_workflow_runs)
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 f5feafa1dbec..a40a46b61486 100644
--- a/products/engineering_analytics/backend/logic/views/ci_job_history.py
+++ b/products/engineering_analytics/backend/logic/views/ci_job_history.py
@@ -123,7 +123,7 @@ def _head_commit_query(runs_table: str) -> str:
def build_query(
*,
- jobs_table: str,
+ jobs_table: workflow_jobs.JobsTable,
runs_table: str,
pull_requests_table: str | None = None,
head_commit_runs_table: str | None = None,
diff --git a/products/engineering_analytics/backend/logic/views/depot_ci.py b/products/engineering_analytics/backend/logic/views/depot_ci.py
index c1569e9d73c1..6f02ccc3e65d 100644
--- a/products/engineering_analytics/backend/logic/views/depot_ci.py
+++ b/products/engineering_analytics/backend/logic/views/depot_ci.py
@@ -25,8 +25,11 @@ import re
from posthog.dataclasses import frozen
-from products.engineering_analytics.backend.logic.queries._workflow_filters import DECISIVE_FAILURE_CONCLUSIONS_SQL
-from products.engineering_analytics.backend.logic.views import workflow_runs
+from products.engineering_analytics.backend.logic.queries._workflow_filters import (
+ DECISIVE_FAILURE_CONCLUSIONS_SQL,
+ SUCCESSFUL_RUN_CONDITION,
+)
+from products.engineering_analytics.backend.logic.views import workflow_jobs, workflow_runs
from products.engineering_analytics.backend.logic.views.source_schema import (
WORKFLOW_JOBS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
@@ -256,26 +259,33 @@ def _executed_attempts(depot: DepotJobAttempts, handoffs: str, pull_requests_tab
def _github_shells(jobs_table: str, runs_table: str, handoffs: str) -> str:
- # No hand-off job predates Depot's first hand-off, so the day before it floors the scan of the jobs table.
+ # No hand-off job predates Depot's first hand-off, so the day before it floors the hand-off and relay jobs.
+ floor = f"(SELECT toString(subtractDays(toDate(min(created_at)), 1)) FROM {handoffs})"
+ handed_off = f"name = '{_GITHUB_HANDOFF_JOB}' AND conclusion = 'success' AND created_at >= {floor}"
+ # A run can recover weeks after its failed attempt, so the failure check has no date floor. Every attempt
+ # keeps the id of its run, so an id bound cannot cut an attempt. Run ids grow with time, so the first run
+ # that handed off is a bound a scan can skip files on.
+ first_run = f"(SELECT min(run_id) FROM {jobs_table} WHERE {handed_off})"
+ relays = f"""
+ SELECT run_id
+ FROM {jobs_table}
+ WHERE run_id >= {first_run}
+ GROUP BY run_id
+ HAVING countIf({handed_off}) > 0
+ AND argMaxIf(
+ ifNull(conclusion, ''), tuple(run_attempt, id), name = '{_GITHUB_RELAY_JOB}' AND created_at >= {floor}
+ ) = 'success'
+ AND countIf(conclusion IN ({DECISIVE_FAILURE_CONCLUSIONS_SQL})) = 0
+ """
+ # The runs builder parses JSON columns on every row, so the raw columns narrow its input first.
+ successful_relays = f"id >= {first_run} AND {SUCCESSFUL_RUN_CONDITION} AND id IN ({relays})"
return f"""
- SELECT j.run_id FROM (
- SELECT run_id
- FROM {jobs_table}
- WHERE created_at >= (SELECT toString(subtractDays(toDate(min(created_at)), 1)) FROM {handoffs})
- GROUP BY run_id
- HAVING countIf(name = '{_GITHUB_HANDOFF_JOB}' AND conclusion = 'success') > 0
- AND argMaxIf(ifNull(conclusion, ''), tuple(run_attempt, id), name = '{_GITHUB_RELAY_JOB}') = 'success'
- ) AS j
- INNER JOIN ({workflow_runs.build_query(f"({_github_runs(runs_table)})")}) AS r ON j.run_id = r.id
- WHERE r.status = 'completed' AND r.conclusion = 'success'
- -- A run can recover weeks after its failed attempt, so the failure check has no date floor.
- AND j.run_id NOT IN (
- SELECT run_id FROM {jobs_table} WHERE conclusion IN ({DECISIVE_FAILURE_CONCLUSIONS_SQL})
- )
- AND (r.head_sha, r.pr_number) IN (
- SELECT head_sha, pr_number FROM {handoffs}
- WHERE took_handoff AND pr_number > 0 AND workflow_status = 'finished'
- )
+ SELECT r.id
+ FROM ({workflow_runs.build_query(f"({_github_runs(runs_table, successful_relays)})")}) AS r
+ WHERE (r.head_sha, r.pr_number) IN (
+ SELECT head_sha, pr_number FROM {handoffs}
+ WHERE took_handoff AND pr_number > 0 AND workflow_status = 'finished'
+ )
"""
@@ -309,16 +319,22 @@ def with_depot_runs(
return f"({_github_runs(runs_table, where)} UNION ALL {depot_runs})"
-def with_depot_jobs(jobs_table: str, depot: DepotJobAttempts | None, runs_table: str) -> str:
+def with_depot_jobs(jobs_table: str, depot: DepotJobAttempts | None, runs_table: str) -> workflow_jobs.JobsTable:
"""The GitHub jobs table, or a subquery that also holds the Depot CI job attempts when they are synced.
- Hand-off shells are left out, as in ``with_depot_runs``. 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.
+ Hand-off shells are left out of the rows, as in ``with_depot_runs``. They stay in the source of the
+ duplicate scan, so a jobs read builds the shell filter once. 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 f"({_github_jobs(jobs_table)})"
+ return workflow_jobs.JobsTable.of(f"({_github_jobs(jobs_table)})")
handoffs = _handoff_workflows(depot)
where = f"run_id NOT IN ({_github_shells(jobs_table, runs_table, handoffs)})"
depot_jobs = _jobs(_executed_attempts(depot, handoffs, pull_requests_table=None))
- return f"({_github_jobs(jobs_table, where)} UNION ALL {depot_jobs})"
+ every_depot_job = _jobs(_attempts(depot, pull_requests_table=None))
+ return workflow_jobs.JobsTable(
+ rows=f"({_github_jobs(jobs_table, where)} UNION ALL {depot_jobs})",
+ duplicates=f"({_github_jobs(jobs_table)} UNION ALL {every_depot_job})",
+ )
diff --git a/products/engineering_analytics/backend/logic/views/job_costs.py b/products/engineering_analytics/backend/logic/views/job_costs.py
index 635d735a670e..ad7d77caf216 100644
--- a/products/engineering_analytics/backend/logic/views/job_costs.py
+++ b/products/engineering_analytics/backend/logic/views/job_costs.py
@@ -148,7 +148,7 @@ def _run_passthrough_aliases() -> str:
def build_query(
*,
- jobs_table: str,
+ jobs_table: workflow_jobs.JobsTable,
runs_table: str,
include_run_columns: bool = False,
created_floor: bool = False,
diff --git a/products/engineering_analytics/backend/logic/views/pr_friction.py b/products/engineering_analytics/backend/logic/views/pr_friction.py
index 2c9ad8ef7b54..c546e7ff8201 100644
--- a/products/engineering_analytics/backend/logic/views/pr_friction.py
+++ b/products/engineering_analytics/backend/logic/views/pr_friction.py
@@ -109,7 +109,7 @@ def build_query(
source_id: str,
pull_requests_table: str,
workflow_runs_table: str,
- workflow_jobs_table: str,
+ workflow_jobs_table: workflow_jobs.JobsTable,
issue_events_table: str | None,
reviews_table: str | None,
) -> str:
@@ -210,7 +210,7 @@ master AS (
SELECT ifNull(j.workflow_name, '') AS workflow_name,
{_strip_shard("j.name")} AS job,
parseDateTimeBestEffort(j.completed_at) AS completed_at
- FROM {workflow_jobs_table} AS j
+ FROM {workflow_jobs_table.rows} AS j
INNER JOIN ({runs}) AS mr ON j.run_id = mr.id AND j.ci_engine = mr.ci_engine
WHERE j.created_at >= {_raw_floor(run_days)}
AND {workflow_jobs.branch("j", "mr")} IN (SELECT default_branch FROM pr WHERE default_branch != '')
diff --git a/products/engineering_analytics/backend/logic/views/workflow_jobs.py b/products/engineering_analytics/backend/logic/views/workflow_jobs.py
index 9ac8bf53325b..3668c65c9a43 100644
--- a/products/engineering_analytics/backend/logic/views/workflow_jobs.py
+++ b/products/engineering_analytics/backend/logic/views/workflow_jobs.py
@@ -43,7 +43,7 @@ can prune on — the parsed ``created_at`` stays the precise filter, the raw twi
A caller's own outer ``created_at_raw`` predicate can prune the jobs scan, but never the duplicate
scan, which reads no ``created_at_raw``. Windowed callers therefore pass ``created_floor=True`` and
register the ``{job_created_floor}`` placeholder (see ``run_started_floor_constant``, shared with
-the runs builder). The floor is a prefilter on the RAW column inside the shared table source, so it
+the runs builder). The floor is a prefilter on the RAW column inside the source of each scan, so it
bounds both scans. The trade is exact: a run whose
earlier attempt falls below the floor loses the evidence that its later attempt is a copy, so a
boundary re-run reads as billable — the same coarseness the floor already has, and why the floor sits
@@ -52,6 +52,8 @@ a day below the window.
Embedded as a subquery by the jobs query module (see ``_curated``); nothing registers a global view.
"""
+from posthog.dataclasses import frozen
+
# The moment the job actually began running: the first entry of the ``steps`` JSON array. ``steps`` is
# a Nullable JSON string, and ClickHouse rejects an Array nested inside a Nullable, so it is
# ``ifNull``-unwrapped before ``JSONExtractArrayRaw`` (``toString`` keeps this correct if the pipeline
@@ -70,14 +72,34 @@ def branch(jobs_alias: str, runs_alias: str) -> str:
return f"coalesce(nullIf({jobs_alias}.head_branch, ''), {runs_alias}.head_branch)"
-def build_query(table_name: str, *, created_floor: bool = False) -> str:
+@frozen
+class JobsTable:
+ """The jobs a read returns, and the source of the builder's duplicate scan.
+
+ ``duplicates`` may hold runs that ``rows`` leaves out, because the join only gives a job row the first
+ attempt of its own run. A source that pays to leave runs out, like the hand-off shell filter, then pays
+ once per jobs read.
+ """
+
+ rows: str
+ duplicates: str
+
+ @classmethod
+ def of(cls, table: str) -> "JobsTable":
+ """One table for both scans."""
+ return cls(rows=table, duplicates=table)
+
+
+def build_query(table: JobsTable, *, 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,
- # so a WHERE there would compare the parsed DateTime against the floor string. Both the jobs scan
- # and the duplicate scan read this source, so the one floor bounds both.
- table_source = (
- f"(SELECT * FROM {table_name} WHERE created_at >= {{job_created_floor}})" if created_floor else table_name
- )
+ # so a WHERE there would compare the parsed DateTime against the floor string. The jobs scan and
+ # the duplicate scan each read a floored source, so the one floor bounds both.
+ def floored(source: str) -> str:
+ return f"(SELECT * FROM {source} WHERE created_at >= {{job_created_floor}})" if created_floor else source
+
+ rows_source = floored(table.rows)
+ duplicates_source = floored(table.duplicates)
return f"""
SELECT
job.id AS id,
@@ -137,7 +159,7 @@ def build_query(table_name: str, *, created_floor: bool = False) -> str:
parseDateTimeBestEffort(started_at) AS started_at,
parseDateTimeBestEffort(completed_at) AS completed_at,
{_FIRST_STEP_STARTED_AT} AS first_step_started_at
- FROM (SELECT *, created_at AS created_at_raw FROM {table_source})
+ FROM (SELECT *, created_at AS created_at_raw FROM {rows_source})
) AS job
-- The duplicated (run_id, name, started_at, completed_at) groups: the re-run copies plus
-- their originals, from a scan that reads only these five columns. The HAVING drops the
@@ -152,7 +174,7 @@ def build_query(table_name: str, *, created_floor: bool = False) -> str:
parseDateTimeBestEffort(started_at) AS started_key,
parseDateTimeBestEffort(completed_at) AS completed_key,
min(run_attempt) AS first_attempt
- FROM {table_source}
+ FROM {duplicates_source}
GROUP BY ci_engine, run_id, name, started_key, completed_key
HAVING count() > 1 AND started_key IS NOT NULL AND completed_key IS NOT NULL
) AS dupes
diff --git a/products/engineering_analytics/backend/tests/test_source_scan_budget.py b/products/engineering_analytics/backend/tests/test_source_scan_budget.py
new file mode 100644
index 000000000000..f4b47c1f00f8
--- /dev/null
+++ b/products/engineering_analytics/backend/tests/test_source_scan_budget.py
@@ -0,0 +1,47 @@
+from collections.abc import Callable
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.engineering_analytics.backend.logic.sources import JobSourceTables
+from products.engineering_analytics.backend.logic.views import depot_ci, workflow_jobs, workflow_runs
+
+_RUNS = "raw_workflow_runs"
+_JOBS = "raw_workflow_jobs"
+_PULL_REQUESTS = "raw_pull_requests"
+_DEPOT = "raw_depot_job_attempts"
+
+_SOURCE = JobSourceTables(
+ github_workflow_jobs=_JOBS,
+ github_workflow_runs=_RUNS,
+ pull_requests=_PULL_REQUESTS,
+ depot_job_attempts=depot_ci.DepotJobAttempts(table=_DEPOT, repository="PostHog/posthog"),
+)
+
+
+def _runs_source() -> str:
+ return workflow_runs.build_query(_SOURCE.runs_source, pull_requests_table=_PULL_REQUESTS, started_floor=True)
+
+
+def _jobs_source() -> str:
+ return workflow_jobs.build_query(_SOURCE.jobs_source, created_floor=True)
+
+
+class TestSourceScanBudget(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("runs_source", _runs_source, {_RUNS: 2, _JOBS: 3, _PULL_REQUESTS: 2, _DEPOT: 7}),
+ ("jobs_source", _jobs_source, {_RUNS: 1, _JOBS: 5, _PULL_REQUESTS: 0, _DEPOT: 14}),
+ ]
+ )
+ def test_source_names_each_warehouse_table_within_its_budget(
+ self, _name: str, render: Callable[[], str], budget: dict[str, int]
+ ) -> None:
+ sql = render()
+ over_budget = {table: sql.count(table) for table, limit in budget.items() if sql.count(table) > limit}
+ assert not over_budget, (
+ "Every read embeds these sources, and a page load runs about twenty reads, so one more "
+ "table read here multiplies across all of them. Measure read_rows for the new SQL in "
+ "production before you raise a budget."
+ )
diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.py
index af922989d28f..baa33cfe9fc5 100644
--- a/products/engineering_analytics/backend/tests/test_views.py
+++ b/products/engineering_analytics/backend/tests/test_views.py
@@ -490,6 +490,10 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
(223978965517241,),
(244340689655172,),
]
+ job_rows = "SELECT ci_engine, id, run_id, run_attempt, is_rerun_copy FROM ({}) AS j ORDER BY ci_engine, id, run_attempt"
+ assert self._select(job_rows.format(workflow_jobs.build_query(jobs))) == self._select(
+ job_rows.format(workflow_jobs.build_query(workflow_jobs.JobsTable.of(jobs.rows)))
+ )
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, run_attempt"