:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(engineering-analytics): expose per-job CI cost as a warehouse view (#70431)
Julian Bezfd58dfbb604d
diff --git a/products/data_modeling/backend/migrations/0028_alter_datawarehousemanagedviewset_kind.py b/products/data_modeling/backend/migrations/0028_alter_datawarehousemanagedviewset_kind.pynew file mode 100644index 000000000000..6a100b256ff1--- /dev/null+++ b/products/data_modeling/backend/migrations/0028_alter_datawarehousemanagedviewset_kind.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.14 on 2026-07-13 10:57++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("data_modeling", "0027_datawarehousesavedquery_column_order")]++ operations = [+ migrations.AlterField(+ model_name="datawarehousemanagedviewset",+ name="kind",+ field=models.CharField(+ choices=[+ ("revenue_analytics", "Revenue Analytics"),+ ("engineering_analytics", "Engineering Analytics"),+ ],+ max_length=64,+ ),+ ),+ ]diff --git a/products/data_modeling/backend/migrations/max_migration.txt b/products/data_modeling/backend/migrations/max_migration.txtindex 30fe609a99db..62c0d908a679 100644--- a/products/data_modeling/backend/migrations/max_migration.txt+++ b/products/data_modeling/backend/migrations/max_migration.txt@@ -1 +1 @@-0027_datawarehousesavedquery_column_order+0028_alter_datawarehousemanagedviewset_kinddiff --git a/products/data_modeling/backend/models/datawarehouse_managed_viewset.py b/products/data_modeling/backend/models/datawarehouse_managed_viewset.pyindex ff06e3fed133..ceaa5ede5204 100644--- a/products/data_modeling/backend/models/datawarehouse_managed_viewset.py+++ b/products/data_modeling/backend/models/datawarehouse_managed_viewset.py@@ -35,6 +35,9 @@ class ExpectedView:name: strquery: dict[str, Any]columns: dict[str, dict[str, Any]]+ # Materialized views get a 12h sync schedule and a managed DAG node. A non-materialized view+ # (e.g. engineering analytics) is computed at query time — no schedule, no DAG, no S3 table.+ materialized: bool = Trueclass DataWarehouseManagedViewSet(CreatedMetaFields, UpdatedMetaFields, UUIDTModel):@@ -74,6 +77,8 @@ class DataWarehouseManagedViewSet(CreatedMetaFields, UpdatedMetaFields, UUIDTModexpected_views: list[ExpectedView] = []if self.kind == DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS:expected_views = self._get_expected_views_for_revenue_analytics()+ elif self.kind == DataWarehouseManagedViewSetKind.ENGINEERING_ANALYTICS:+ expected_views = self._get_expected_views_for_engineering_analytics()else:raise DataWarehouseManagedViewSet.UnsupportedViewsetKind(cast(DataWarehouseManagedViewSetKind, self.kind))@@ -149,11 +154,14 @@ class DataWarehouseManagedViewSet(CreatedMetaFields, UpdatedMetaFields, UUIDTModsaved_query.query = view.querysaved_query.set_columns(view.columns)saved_query.external_tables = external_tables_by_view[view.name]- saved_query.is_materialized = True- saved_query.sync_frequency_interval = timedelta(hours=12)+ saved_query.is_materialized = view.materialized+ # A non-materialized view is computed at query time — no sync schedule, and it never+ # enters the schedule/DAG lists below.+ saved_query.sync_frequency_interval = timedelta(hours=12) if view.materialized else Nonesaved_query.save()- saved_queries_to_schedule.append(saved_query)+ if view.materialized:+ saved_queries_to_schedule.append(saved_query)if created:views_created += 1@@ -175,23 +183,27 @@ class DataWarehouseManagedViewSet(CreatedMetaFields, UpdatedMetaFields, UUIDTMod# and eventually exhausting the connection pool. Concurrent sync_views for the same team+kind# can therefore race on node/edge placement; that is tolerated for now, pending a pooling-safe# guard. The transaction-scoped lock above still serializes the saved-query writes.- managed_dag = DAG.get_or_create_revenue_analytics(self.team)- for saved_query in saved_queries_to_schedule:- try:- sync_saved_query_to_dag(saved_query, dag=managed_dag, allow_managed=True)- # Drop any stale node left in another DAG (e.g. a legacy Default-DAG placement),- # unless something there still depends on it (don't orphan a dependent).- for stale in Node.objects.filter(team=self.team, saved_query=saved_query).exclude(dag=managed_dag):- if not stale.outgoing_edges.exists():- stale.delete()- except Exception as e:- capture_exception(e, {"managed_viewset_id": self.id, "view_name": saved_query.name})- logger.warning(- "failed_to_sync_managed_view_to_dag",- team_id=self.team_id,- view_name=saved_query.name,- error=str(e),- )+ # Only materialized views get a managed DAG (the revenue-analytics 12h schedule). When+ # nothing is scheduled (e.g. the non-materialized engineering-analytics view), skip DAG+ # creation entirely — no managed DAG is created for that kind.+ if saved_queries_to_schedule:+ managed_dag = DAG.get_or_create_revenue_analytics(self.team)+ for saved_query in saved_queries_to_schedule:+ try:+ sync_saved_query_to_dag(saved_query, dag=managed_dag, allow_managed=True)+ # Drop any stale node left in another DAG (e.g. a legacy Default-DAG placement),+ # unless something there still depends on it (don't orphan a dependent).+ for stale in Node.objects.filter(team=self.team, saved_query=saved_query).exclude(dag=managed_dag):+ if not stale.outgoing_edges.exists():+ stale.delete()+ except Exception as e:+ capture_exception(e, {"managed_viewset_id": self.id, "view_name": saved_query.name})+ logger.warning(+ "failed_to_sync_managed_view_to_dag",+ team_id=self.team_id,+ view_name=saved_query.name,+ error=str(e),+ )for saved_query in saved_queries_to_schedule:try:@@ -208,6 +220,10 @@ class DataWarehouseManagedViewSet(CreatedMetaFields, UpdatedMetaFields, UUIDTModviews_deleted = 0for orphaned_view in orphaned_views_to_revert:try:+ # Unconditional on purpose: revert_materialization is idempotent for a+ # never-materialized view (no table to drop; schedule deletion swallows NOT_FOUND),+ # and skipping it on a heuristic can strand the Temporal schedule of a view whose+ # materialization failed midway (is_materialized already reset to False).orphaned_view.revert_materialization()orphaned_view.soft_delete()views_deleted += 1@@ -264,9 +280,12 @@ class DataWarehouseManagedViewSet(CreatedMetaFields, UpdatedMetaFields, UUIDTModself.delete()return views_deleted- def to_saved_query_metadata(self, name: str):+ def to_saved_query_metadata(self, name: str) -> dict[str, Any]:+ # Called from DataWarehouseSavedQuery.hogql_definition for every managed view, so it must+ # degrade gracefully for any kind rather than raise — an unhandled kind here would break+ # resolving the saved query. Only revenue analytics carries the extra per-schema kind.if self.kind != DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS:- raise DataWarehouseManagedViewSet.UnsupportedViewsetKind(cast(DataWarehouseManagedViewSetKind, self.kind))+ return {"managed_viewset_kind": self.kind}return {"managed_viewset_kind": self.kind,@@ -299,6 +318,27 @@ class DataWarehouseManagedViewSet(CreatedMetaFields, UpdatedMetaFields, UUIDTModfor view in expected_views]+ def _get_expected_views_for_engineering_analytics(self) -> list[ExpectedView]:+ """The engineering-analytics per-job CI cost view, adapted from its facade contract.++ Non-materialized: the view is computed at query time so a Depot rate change propagates+ immediately and it never joins the materialization schedule / managed DAG. Imported lazily+ (like revenue above) to keep the product's read layer off the django.setup() path.+ """+ from products.engineering_analytics.backend.facade.warehouse_views import ( # noqa: PLC0415 — keeps the product read layer off the startup path+ get_expected_warehouse_views,+ )++ return [+ ExpectedView(+ name=view.name,+ query={"kind": "HogQLQuery", "query": view.query},+ columns=self._get_columns_from_fields(view.fields),+ materialized=False,+ )+ for view in get_expected_warehouse_views(self.team)+ ]+@staticmethoddef _get_columns_from_fields(fields: dict[str, FieldOrTable]) -> dict[str, dict[str, Any]]:return {diff --git a/products/data_warehouse/backend/models/test/test_managed_viewset.py b/products/data_warehouse/backend/models/test/test_managed_viewset.pyindex 04472f571029..1ff0eecda788 100644--- a/products/data_warehouse/backend/models/test/test_managed_viewset.py+++ b/products/data_warehouse/backend/models/test/test_managed_viewset.py@@ -285,6 +285,95 @@ class TestDataWarehouseManagedViewSetModel(BaseTest):)+class TestEngineeringAnalyticsManagedViewSet(BaseTest):+ """sync_views for the non-materialized engineering-analytics kind: it must create a+ query-time saved query (no materialization schedule, no managed DAG), stay idempotent, and+ create nothing for a team without a qualifying GitHub source.+ """++ PREFIX = "myprefix"+ VIEW_NAME = "engineering_analytics_job_costs"++ def _github_source(self) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=self.team,+ source_id="gh",+ connection_id="gh",+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.GITHUB,+ prefix=self.PREFIX,+ )++ def _link(self, source: ExternalDataSource, schema_name: str, table_suffix: str) -> None:+ table = DataWarehouseTable.objects.create(+ team=self.team,+ name=f"{self.PREFIX}github_{table_suffix}",+ format=DataWarehouseTable.TableFormat.CSVWithNames,+ url_pattern="",+ external_data_source=source,+ columns=DUMMY_COLUMNS,+ )+ ExternalDataSchema.objects.create(+ team=self.team, source=source, name=schema_name, table=table, should_sync=True+ )++ def _viewset(self) -> DataWarehouseManagedViewSet:+ return DataWarehouseManagedViewSet.objects.create(+ team=self.team, kind=DataWarehouseManagedViewSetKind.ENGINEERING_ANALYTICS+ )++ def _views(self, viewset: DataWarehouseManagedViewSet) -> list[DataWarehouseSavedQuery]:+ return list(+ DataWarehouseSavedQuery.objects.filter(team=self.team, managed_viewset=viewset).exclude(deleted=True)+ )++ @patch(SCHEDULE_MATERIALIZATION)+ def test_sync_views_creates_non_materialized_view(self, mock_schedule):+ source = self._github_source()+ self._link(source, "workflow_runs", "workflow_runs")+ self._link(source, "workflow_jobs", "workflow_jobs")++ viewset = self._viewset()+ viewset.sync_views()++ views = self._views(viewset)+ self.assertEqual(len(views), 1)+ view = views[0]+ self.assertEqual(view.name, self.VIEW_NAME)+ self.assertFalse(view.is_materialized)+ self.assertIsNone(view.sync_frequency_interval)+ # A non-materialized view is computed at query time — it must never be scheduled for+ # materialization, nor get a managed (revenue-analytics) DAG.+ mock_schedule.assert_not_called()+ self.assertFalse(DAG.objects.filter(team=self.team, name=REVENUE_ANALYTICS_DAG_NAME).exists())++ @patch(SCHEDULE_MATERIALIZATION)+ def test_sync_views_is_idempotent(self, _):+ source = self._github_source()+ self._link(source, "workflow_runs", "workflow_runs")+ self._link(source, "workflow_jobs", "workflow_jobs")++ viewset = self._viewset()+ viewset.sync_views()+ first = self._views(viewset)+ viewset.sync_views()+ second = self._views(viewset)++ self.assertEqual(len(first), 1)+ self.assertEqual([v.id for v in first], [v.id for v in second])++ @patch(SCHEDULE_MATERIALIZATION)+ def test_sync_views_creates_nothing_without_qualifying_source(self, _):+ # Only workflow_runs synced (no jobs) — no view to expose, so sync creates nothing.+ source = self._github_source()+ self._link(source, "workflow_runs", "workflow_runs")++ viewset = self._viewset()+ viewset.sync_views()++ self.assertEqual(len(self._views(viewset)), 0)++class TestManagedViewSetSyncWithStripeSource(BaseTest):"""Tests for sync_views behavior with a Stripe external data source.diff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.tsindex 56c7b5343717..ae08dbd3fd5e 100644--- a/products/data_warehouse/frontend/generated/api.ts+++ b/products/data_warehouse/frontend/generated/api.ts@@ -614,7 +614,10 @@ export const insightVariablesDestroy = async (projectId: string, id: string, opt})}-export const getManagedViewsetsRetrieveUrl = (projectId: string, kind: 'revenue_analytics') => {+export const getManagedViewsetsRetrieveUrl = (+ projectId: string,+ kind: 'revenue_analytics' | 'engineering_analytics'+) => {return `/api/projects/${projectId}/managed_viewsets/${kind}/`}@@ -624,7 +627,7 @@ export const getManagedViewsetsRetrieveUrl = (projectId: string, kind: 'revenue_*/export const managedViewsetsRetrieve = async (projectId: string,- kind: 'revenue_analytics',+ kind: 'revenue_analytics' | 'engineering_analytics',options?: RequestInit): Promise<void> => {return apiMutator<void>(getManagedViewsetsRetrieveUrl(projectId, kind), {@@ -633,7 +636,7 @@ export const managedViewsetsRetrieve = async (})}-export const getManagedViewsetsUpdateUrl = (projectId: string, kind: 'revenue_analytics') => {+export const getManagedViewsetsUpdateUrl = (projectId: string, kind: 'revenue_analytics' | 'engineering_analytics') => {return `/api/projects/${projectId}/managed_viewsets/${kind}/`}@@ -643,7 +646,7 @@ export const getManagedViewsetsUpdateUrl = (projectId: string, kind: 'revenue_an*/export const managedViewsetsUpdate = async (projectId: string,- kind: 'revenue_analytics',+ kind: 'revenue_analytics' | 'engineering_analytics',options?: RequestInit): Promise<void> => {return apiMutator<void>(getManagedViewsetsUpdateUrl(projectId, kind), {diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex c0effacbfc9c..5571ad3f71c2 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -150,6 +150,39 @@ A PR's current CI status is the head-SHA join between the two (the `ci_rollup` CAll time-windowed access uses `date_from` / `date_to` per PostHog convention (relative `-30d` or ISO8601).+### Exposed warehouse view++One warehouse view is exposed so insights, subscriptions, other products, and agents (via+`execute-sql`) can query per-job CI cost directly — the only surface where the curated read layer+is reachable as data rather than through the named endpoints.++- **Name:** `engineering_analytics_job_costs`, provisioned per-team as a `DataWarehouseSavedQuery`+ (the revenue-analytics managed-viewset mechanism, kind `engineering_analytics`).+- **Grain:** one row per job attempt (a retry appears once per attempt — correct for cost). Every+ job is kept, including non-billable ones: `provider` / `os` / `vcpu` / `multiplier` describe any+ classifiable runner (github-hosted included) and are NULL only when the labels name no recognized+ runner; `billable_seconds` / `estimated_cost_usd` are NULL when the job isn't billable+ (github-hosted, non-Linux, or unclassifiable) or unsettled (no elapsed yet). NULL cost is+ disambiguated by `provider` (non-billable) vs `completed_at` (unsettled) — a queued job is never+ shown as `$0.00`.+ Jobs whose run row is missing (the LEFT JOIN to `workflow_runs`) keep NULL attribution+ (`repo_owner` / `repo_name` / `pr_number`) rather than being dropped.+- **Non-materialized:** results are computed at query time — there is no stored table to rebuild.+ The rendered SQL itself is persisted per team, so a cost-model change in `cost.py` reaches a+ team's view on its next re-render (the post-load hook re-syncs on every GitHub runs/jobs load,+ bounding staleness to one sync cycle for active teams); a fleet-wide resync is a one-line loop+ over the `engineering_analytics` viewsets.+- **Single source of truth:** the cost columns are generated from `logic/cost.py`'s constants (the+ same rate ladder + label→tier parser the Python model uses), rendered as HogQL. A ClickHouse-backed+ parity test asserts the view's output equals the Python model's across the classification matrix,+ so the SQL can only drift from the model if that test fails.+- **One cost path for the view and the endpoints.** The product's endpoint cost queries (`pr_cost`,+ the workflow/author/runner-tier cost splits, the cost-per-merge series) read this same rendered+ per-job cost SELECT — via `_curated.job_cost_source()`, which adds only endpoint-private run+ pass-through columns for windowing/branch filters — and aggregate `billable_seconds` /+ `estimated_cost_usd` in ClickHouse. Cost is therefore computed exactly once, in one place; there is+ no separate Python cost rollup for the endpoints to drift from the view.+## 6. Delivery shapeVertical slices, each independently mergeable. The near-term path:@@ -172,6 +205,7 @@ Engineering-specific decisions. Product-level decisions live in README → Locke- **Signals emission for PostHog Code is the goal; the substrate is shaped for it.** Valuable CI conditions are surfaced as Signals via the Signals product's `emit_signal()` for PostHog Code to act on. Detection of what counts as a valuable Signal is defined once in `logic/` over the read layer, so the emitter and the MCP/SQL surface share one definition — never re-derived in the UI. The emission contract (source taxonomy, thresholds, autonomy priority) is owned by the Signals product; nothing in the read substrate or surfaces may foreclose it.- **Curated read layer, run privately; MCP is the official surface via named typed endpoints.** _(Changed — reason:)_ registering the curated views in the global HogQL catalog (`Database.create_for`, the `revenue_analytics` precedent) inverts the dependency — core imports the product — and runs on the per-query hot path for **every** team. Running the curated `build_query()` as subqueries from the product's own DRF endpoints keeps domain rules defined once while leaving the product isolated and off the hot path: core imports only the viewset, exactly like `visual_review`. The endpoints back both the MCP tools and the UI, so there is no parallel read path. (This restructure is the written reason for changing the prior "registered substrate + generic SQL surface" decision.)- **`metric_quality` is a typed field on `pr_lifecycle`; aggregate endpoints carry caveats in field names + docs.** _(Changed — reason:)_ the aggregate endpoints return typed lists, so the coarse/staleness caveats ride in honest field names (`open_to_merge_seconds`) and serializer/tool descriptions — structurally hard to misread. `pr_lifecycle` keeps the typed `metric_quality` field (`partial`) where the assembly's incompleteness is load-bearing.+- **The `engineering_analytics_job_costs` warehouse view does not reopen "no global HogQL view registration".** The locked-out thing is `Database.create_for` _code_ registration that inverts the dependency (core imports the product) and runs on every team's per-query hot path. This view is the opposite: team-scoped managed _data_ (a `DataWarehouseSavedQuery` synced only for teams with a GitHub source), created by the same managed-viewset mechanism revenue analytics uses. Core never imports the product to serve it, and teams without a synced GitHub source have no view at all. The cost model stays defined once in `logic/cost.py` (rendered to HogQL, guarded by a parity test); the view exists so cost is queryable by insights / subscriptions / other products / `execute-sql`, which the named endpoints alone don't cover. See §5 → Exposed warehouse view.- **No new ingestion to support v1 UI.** Repo identity, labels, and `is_bot` are mapped from the warehouse JSON already landed; the PR↔CI status is a head-SHA join. All in the read layer.- **HogQL only for analytics data.** No raw ClickHouse.- **No product Postgres DB.** Tool calls are stateless; saved/stateful state is a later, separate decision. No `db_routing.yaml` entry — analytics data lives in the warehouse / ClickHouse. If a product-config model is ever needed, it goes on the **main** DB as a team-scoped model (`TeamScopedRootMixin`), not a separate DB.diff --git a/products/engineering_analytics/backend/apps.py b/products/engineering_analytics/backend/apps.pyindex e44233f3df2a..43408f8e847d 100644--- a/products/engineering_analytics/backend/apps.py+++ b/products/engineering_analytics/backend/apps.py@@ -2,7 +2,23 @@from django.apps import AppConfig+# Light re-export module (no heavy deps) — safe to import on the startup path.+from products.warehouse_sources.backend.facade.hooks import register_engineering_analytics_view_sync+class EngineeringAnalyticsConfig(AppConfig):name = "products.engineering_analytics.backend"label = "engineering_analytics"++ def ready(self) -> None:+ # Register the warehouse view-sync so the data-import pipeline can trigger it without+ # importing this product (it depends on warehouse_sources). The impl is imported lazily to+ # keep the read layer / data_modeling off the django.setup() path.+ def _sync_engineering_analytics_views(schema: object, source: object) -> None:+ from products.engineering_analytics.backend.warehouse_view_sync import ( # noqa: PLC0415 — keeps data_modeling + read layer off the startup path+ sync_engineering_analytics_views,+ )++ sync_engineering_analytics_views(schema, source) # type: ignore[arg-type]++ register_engineering_analytics_view_sync(_sync_engineering_analytics_views)diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex 3ba39600ca2f..5e202b5fcc47 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -27,6 +27,8 @@ from enum import StrEnumfrom pydantic.dataclasses import dataclass+from posthog.hogql.database.models import FieldOrTable+class GitHubSourceNotConnectedError(Exception):"""Raised when a team has no GitHub warehouse source — the curated queries@@ -149,6 +151,22 @@ class GitHubSource:prefix: str+@dataclass(frozen=True)+class ExpectedWarehouseView:+ """A code-generated warehouse view this product exposes as a team-scoped DataWarehouse saved+ query. data_modeling adapts it into its own ``ExpectedView`` without importing this product's+ internals (avoids a dependency cycle). ``query`` is the HogQL SELECT body; ``fields`` maps column+ name -> a ``FieldOrTable`` instance, from which data_modeling derives the stored+ ``{"hogql": <field class>, "clickhouse": <type>, "valid": True}`` metadata via its shared+ ``_get_columns_from_fields`` path (the same one revenue analytics uses) — so the type strings are+ never hand-written here and can't drift from the real field classes.+ """++ name: str+ query: str+ fields: dict[str, FieldOrTable]++@dataclass(frozen=True)class RepoRef:provider: strdiff --git a/products/engineering_analytics/backend/facade/warehouse_views.py b/products/engineering_analytics/backend/facade/warehouse_views.pynew file mode 100644index 000000000000..4f484c735323--- /dev/null+++ b/products/engineering_analytics/backend/facade/warehouse_views.py@@ -0,0 +1,21 @@+"""The warehouse views this product exposes, for data_modeling's managed-viewset sync.++data_modeling calls ``get_expected_warehouse_views(team)`` and adapts the returned frozen+contracts into its own ``ExpectedView`` rows (as non-materialized saved queries). Kept behind the+facade so data_modeling never imports this product's read layer directly — it depends only on the+provider-neutral ``ExpectedWarehouseView`` contract.+"""++from posthog.models.team import Team++from products.engineering_analytics.backend.facade.contracts import ExpectedWarehouseView+from products.engineering_analytics.backend.logic.views import job_costs+++def get_expected_warehouse_views(team: Team) -> list[ExpectedWarehouseView]:+ """The team's exposed warehouse views. Empty when the team has no GitHub source with both the+ workflow_runs and workflow_jobs endpoints synced (so no view is created for such teams)."""+ query = job_costs.build_team_view(team)+ if query is None:+ return []+ return [ExpectedWarehouseView(name=job_costs.VIEW_NAME, query=query, fields=job_costs.FIELDS)]diff --git a/products/engineering_analytics/backend/logic/cost.py b/products/engineering_analytics/backend/logic/cost.pyindex a08ca52f7b49..9ec118ace022 100644--- a/products/engineering_analytics/backend/logic/cost.py+++ b/products/engineering_analytics/backend/logic/cost.py@@ -17,7 +17,6 @@ source-agnostic so they are unit-tested today and wired to the ``github_workflowwarehouse source once it lands (see SPEC section 6/9)."""-from collections.abc import Iterablefrom dataclasses import dataclassfrom enum import StrEnum@@ -135,6 +134,24 @@ def runner_descriptor(labels: list[str]) -> tuple[str, str]:return "self_hosted", tier.os.value+def runner_tier_descriptor(provider: str | None, os: str | None, vcpu: int | None) -> tuple[str, str]:+ """Provider badge + human tier label from an already-classified ``(provider, os, vcpu)`` tuple — the+ display form of ``runner_descriptor`` for callers that group by the rendered tier columns (the job+ cost source's ``provider`` / ``os`` / ``vcpu``) rather than raw labels. Same mapping as+ ``runner_descriptor``, minus the raw-label fallback: grouped by tier there is no single ``runs-on``+ to echo, so a github-hosted or unclassified tier reads as its OS (or ``''``) instead of the label.+ ``provider`` is the ``render_provider`` output — ``'depot'`` / ``'github_hosted'`` / ``None``.+ """+ if provider is None:+ return "unknown", ""+ if provider == RunnerProvider.GITHUB_HOSTED.value:+ return "github_hosted", (os or "")+ # Depot is the only billed provider — it maps to the 'self_hosted' badge; Linux reads as '<vcpu>-core'.+ if os == RunnerOS.LINUX.value:+ return "self_hosted", f"{vcpu}-core"+ return "self_hosted", (os or "")++def estimate_job_cost_usd(labels: list[str], elapsed_seconds: float | None) -> float | None:"""Estimated Depot dollar cost for one job, or ``None`` when no honest figure exists.@@ -175,32 +192,134 @@ class PRCostAggregate:excluded_jobs: int-def aggregate_pr_cost(jobs: Iterable[tuple[list[str], float | None]]) -> PRCostAggregate:- """Sum per-job cost over a PR's jobs, partitioning each job by why it does (or doesn't) count.+# --- HogQL renderer -------------------------------------------------------------------+# The same cost model, rendered as HogQL expression strings so a warehouse view can compute+# provider / os / vcpu / multiplier / billable_seconds / estimated_cost_usd in ClickHouse+# without leaving Python as the single source of truth. Every expression is generated from the+# constants above (never a literal duplicate of a rate, prefix, OS token, or multiplier), so the+# view SQL can only ever drift from the Python model if these constants change — which the+# ClickHouse-backed parity test guards against. Each renderer takes SQL expression strings for+# its inputs and returns a HogQL expression; the caller (logic.views.job_costs) threads them+# through nested subqueries so the two label picks (``render_depot_label`` / ``render_hosted_label``)+# and then provider/os/vcpu are each computed once per row and reused. Parity-critical notes mirror+# classify_runner / _depot_vcpu / billing_multiplier / estimate_job_cost_usd exactly.+++def _has_os_token_sql(label_sql: str) -> str:+ """True when the label names a recognized OS — the substring test of ``_os_from_label``."""+ checks = " OR ".join(f"position(lowerUTF8({label_sql}), '{token}') > 0" for token in _OS_BY_TOKEN)+ return f"({checks})"+++def _os_of_label_sql(label_sql: str) -> str:+ """The OS a label names, in ``_OS_BY_TOKEN`` priority order (ubuntu > macos > windows) — the+ ``multiIf`` form of ``_os_from_label``'s first-match-wins over the dict."""+ branches: list[str] = []+ for token, os_ in _OS_BY_TOKEN.items():+ branches.append(f"position(lowerUTF8({label_sql}), '{token}') > 0")+ branches.append(f"'{os_.value}'")+ return "multiIf(" + ", ".join(branches) + ", NULL)"+- Each input is one job's ``(labels, elapsed_seconds)``. A job counts toward cost only when its- runner classifies as a billable self-hosted Linux tier AND it has elapsed time; everything else- lands in ``unsettled_jobs`` (self-hosted Linux, no elapsed) or ``excluded_jobs`` (provider-hosted /- non-Linux). The billable classification is currently Depot-shaped (the only modeled provider).+def _depot_vcpu_sql(label_sql: str) -> str:+ """vCPU from a Depot label's trailing size segment — the SQL form of ``_depot_vcpu``.++ Split on '-'; only the 4th-or-later segment can be a size, so a bare-integer OS version+ (``depot-macos-14``) in the version slot is never read as vcpu. ``match(..., '^[0-9]+$')`` is+ the parity of Python ``str.isdecimal`` (plain ASCII digits — ``isdecimal`` rejects the unicode+ digits ``int()`` would too, so an ASCII-only regex matches its accept set here)."""- billable_seconds = 0.0- total_cost = 0.0- costed = unsettled = excluded = 0- for labels, elapsed_seconds in jobs:- tier = classify_runner(labels)- if tier is None or tier.provider is not RunnerProvider.DEPOT or tier.os is not RunnerOS.LINUX:- excluded += 1- continue- if elapsed_seconds is None:- unsettled += 1- continue- billable_seconds += max(0.0, elapsed_seconds)- total_cost += estimate_job_cost_usd(labels, elapsed_seconds) or 0.0- costed += 1- return PRCostAggregate(- billable_seconds=billable_seconds,- estimated_cost_usd=total_cost if costed else None,- costed_jobs=costed,- unsettled_jobs=unsettled,- excluded_jobs=excluded,+ segments = f"splitByChar('-', {label_sql})"+ last = f"arrayElement({segments}, length({segments}))"+ return f"if(length({segments}) >= 4 AND match({last}, '^[0-9]+$'), toInt({last}), {_DEFAULT_DEPOT_VCPU})"+++def render_depot_label(labels_array_sql: str) -> str:+ """First label (array order) that is a real Depot runner: ``depot-`` prefixed AND names an OS.+ Empty string when none — Depot wins over hosted because provider/os/vcpu test this first.++ This is the expensive ``arrayFilter`` label scan, so the caller computes it once as its own+ column and feeds that column (not the array) into ``render_provider`` / ``render_os`` / ``render_vcpu``.+ """+ is_depot = f"(startsWith(lowerUTF8(_label), '{_DEPOT_PREFIX}') AND {_has_os_token_sql('_label')})"+ return f"arrayElement(arrayFilter(_label -> {is_depot}, {labels_array_sql}), 1)"+++def render_hosted_label(labels_array_sql: str) -> str:+ """First label (array order) that names an OS but is NOT ``depot-`` prefixed — the+ github-hosted fallback (``hosted_os`` in ``classify_runner``). Empty string when none.++ Like ``render_depot_label``, the expensive ``arrayFilter`` scan — computed once as its own+ column and reused across the provider/os/vcpu renderers.+ """+ is_hosted = f"(NOT startsWith(lowerUTF8(_label), '{_DEPOT_PREFIX}') AND {_has_os_token_sql('_label')})"+ return f"arrayElement(arrayFilter(_label -> {is_hosted}, {labels_array_sql}), 1)"+++def render_provider(depot_label_sql: str, hosted_label_sql: str) -> str:+ """RunnerProvider value ('depot' / 'github_hosted') or NULL — the SQL form of+ ``classify_runner(...).provider`` over the two precomputed label picks (``render_depot_label`` /+ ``render_hosted_label``). Depot before hosted (Depot is the only billed provider)."""+ return (+ f"multiIf({depot_label_sql} != '', '{RunnerProvider.DEPOT.value}', "+ f"{hosted_label_sql} != '', '{RunnerProvider.GITHUB_HOSTED.value}', NULL)"+ )+++def render_os(depot_label_sql: str, hosted_label_sql: str) -> str:+ """RunnerOS value ('linux' / 'macos' / 'windows') or NULL — the OS of the winning label (the+ precomputed Depot label if any, else the hosted one), matching ``classify_runner(...).os``. Both+ inputs are the label-pick columns from ``render_depot_label`` / ``render_hosted_label``, so this is+ a cheap ``multiIf`` over string columns, not a re-scan of the labels array."""+ return (+ f"multiIf({depot_label_sql} != '', {_os_of_label_sql(depot_label_sql)}, "+ f"{hosted_label_sql} != '', {_os_of_label_sql(hosted_label_sql)}, NULL)")+++def render_vcpu(depot_label_sql: str, hosted_label_sql: str) -> str:+ """vCPU of the winning runner or NULL — Depot reads its size segment, github-hosted is the+ 2-vCPU default (``_DEFAULT_DEPOT_VCPU``), matching ``classify_runner(...).vcpu``. Both inputs are+ the precomputed label-pick columns (``render_depot_label`` / ``render_hosted_label``)."""+ return (+ f"multiIf({depot_label_sql} != '', {_depot_vcpu_sql(depot_label_sql)}, "+ f"{hosted_label_sql} != '', {_DEFAULT_DEPOT_VCPU}, NULL)"+ )+++def render_multiplier(vcpu_sql: str) -> str:+ """Depot billing multiplier for a vCPU count, or NULL when vcpu is NULL — the SQL form of+ ``billing_multiplier``: the ``_MULTIPLIER_BY_VCPU`` ladder, else ``max(1, vcpu // 2)``."""+ branches: list[str] = []+ for vcpu, multiplier in _MULTIPLIER_BY_VCPU.items():+ branches.append(f"{vcpu_sql} = {vcpu}")+ branches.append(f"{multiplier}")+ ladder = "multiIf(" + ", ".join(branches) + f", greatest(1, intDiv({vcpu_sql}, 2)))"+ return f"if({vcpu_sql} IS NULL, NULL, {ladder})"+++def render_is_billable_tier(provider_sql: str, os_sql: str) -> str:+ """SQL predicate: True when a job's classified tier is billable — self-hosted Linux (Depot Linux,+ the only modeled billed tier). Generated from the enums so ``'depot'`` / ``'linux'`` never appear+ as string literals in the query layer. NULL-safe: an unclassified tier (``provider`` NULL) reads as+ not billable. This is the one place the billable-partition rule is spelled out; the endpoint cost+ aggregates and the two renderers below all read it, so the three-bucket split can't drift."""+ return f"ifNull({provider_sql} = '{RunnerProvider.DEPOT.value}' AND {os_sql} = '{RunnerOS.LINUX.value}', 0)"+++def render_billable_seconds(provider_sql: str, os_sql: str, elapsed_sql: str) -> str:+ """Raw billable wall-clock seconds (NOT multiplier-weighted): ``greatest(elapsed, 0)`` only for+ a billable self-hosted Linux job with a known elapsed, else NULL — mirrors the ``max(0, elapsed)``+ a costed job contributes to a PR's ``billable_seconds``."""+ billable = render_is_billable_tier(provider_sql, os_sql)+ return f"if({billable} AND {elapsed_sql} IS NOT NULL, greatest({elapsed_sql}, 0), NULL)"+++def render_estimated_cost_usd(provider_sql: str, os_sql: str, vcpu_sql: str, elapsed_sql: str) -> str:+ """Estimated Depot dollar cost for one job — the SQL form of ``estimate_job_cost_usd``:+ NULL when not billable (non-Depot / non-Linux / unclassified) and NULL for an unsettled job+ (elapsed unknown, never $0.00), a real 0.0 for non-positive elapsed, else+ ``(elapsed / 60) * REFERENCE_RATE_USD_PER_MIN * multiplier``."""+ is_depot_linux = render_is_billable_tier(provider_sql, os_sql)+ cost = f"({elapsed_sql} / 60) * {REFERENCE_RATE_USD_PER_MIN} * {render_multiplier(vcpu_sql)}"+ return f"multiIf(NOT {is_depot_linux}, NULL, {elapsed_sql} IS NULL, NULL, {elapsed_sql} <= 0, 0.0, {cost})"diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.pyindex 0b98b5a0bff6..621c0625bd38 100644--- a/products/engineering_analytics/backend/logic/queries/_curated.py+++ b/products/engineering_analytics/backend/logic/queries/_curated.py@@ -27,7 +27,7 @@ from posthog.clickhouse.workload import Workloadfrom posthog.models.team import Teamfrom products.engineering_analytics.backend.logic.sources import GitHubTables, resolve_github_tables-from products.engineering_analytics.backend.logic.views import pull_requests, workflow_jobs, workflow_runs+from products.engineering_analytics.backend.logic.views import job_costs, pull_requests, workflow_jobs, workflow_runsif TYPE_CHECKING:from posthog.rbac.user_access_control import UserAccessControl@@ -78,6 +78,25 @@ class CuratedGitHubSource:return Nonereturn f"({workflow_jobs.build_query(self._tables.workflow_jobs)})"+ def job_cost_source(self) -> str | None:+ """Per-job cost ``SELECT`` subquery — the same view body ``engineering_analytics_job_costs``+ exposes, but with the endpoint-only run pass-through columns (``run_started_at`` /+ ``run_head_branch``). None when the jobs table isn't synced, exactly like ``jobs_source``.++ This is the single cost-computation path: ``provider`` / ``os`` / ``vcpu`` / ``billable_seconds``+ / ``estimated_cost_usd`` are rendered from ``logic.cost`` in ClickHouse, so every endpoint cost+ query aggregates the same per-job figures the exposed view (and the parity test) do — there is+ no separate Python cost rollup to drift.+ """+ 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,+ include_run_columns=True,+ )+ return f"({query})"+def runs_cte(self) -> str:"""CTE materializing the curated workflow-runs source once.diff --git a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py b/products/engineering_analytics/backend/logic/queries/_workflow_filters.pyindex 6db01fa878d0..70b98293b2d6 100644--- a/products/engineering_analytics/backend/logic/queries/_workflow_filters.py+++ b/products/engineering_analytics/backend/logic/queries/_workflow_filters.py@@ -16,32 +16,46 @@ from products.engineering_analytics.backend.facade.contracts import WorkflowHealDURATION_PERCENTILE_CONDITION = "status = 'completed' AND conclusion = 'success'"-def branch_filter_clause(branch: str | None, placeholders: dict[str, ast.Expr]) -> str:- """Exact ``head_branch`` filter; registers its ``{branch}`` placeholder.-- An empty/whitespace branch is "no filter", not a literal match on ''.+def branch_filter_clause(+ branch: str | None, placeholders: dict[str, ast.Expr], *, column: str = "r.head_branch"+) -> str:+ """Exact head-branch filter; registers its ``{branch}`` placeholder.++ An empty/whitespace branch is "no filter", not a literal match on ''. ``column`` lets the cost+ queries point the same filter at the job cost source's ``c.run_head_branch`` (the run's branch,+ kept distinct from the per-job ``head_branch``) instead of the run source's ``r.head_branch``."""value = branch.strip() if branch else ""if not value:return ""placeholders["branch"] = ast.Constant(value=value)- return "AND r.head_branch = {branch}"+ return f"AND {column} = {{branch}}"-def date_to_filter_clause(date_to: datetime | None, placeholders: dict[str, ast.Expr]) -> str:- """Optional window end; registers its ``{date_to}`` placeholder."""+def date_to_filter_clause(+ date_to: datetime | None, placeholders: dict[str, ast.Expr], *, column: str = "r.run_started_at"+) -> str:+ """Optional window end; registers its ``{date_to}`` placeholder. ``column`` retargets it at the+ cost source's ``c.run_started_at`` for the cost queries."""if date_to is None:return ""placeholders["date_to"] = ast.Constant(value=date_to)- return "AND r.run_started_at <= {date_to}"+ return f"AND {column} <= {{date_to}}"-def run_scope_filter_clause(run_scope: WorkflowHealthRunScope) -> str:+def run_scope_filter_clause(+ run_scope: WorkflowHealthRunScope,+ *,+ branch_column: str = "r.head_branch",+ attributed_predicate: str = "r.pr_number > 0",+) -> str:if run_scope == WorkflowHealthRunScope.PULL_REQUEST:# A default-branch run can still carry a PR association (its SHA matches an open PR),- # so attribution (pr_number > 0 — see the workflow_runs builder docstring) alone doesn't+ # so attribution alone (pr_number > 0 — see the workflow_runs builder docstring) doesn't# keep trunk runs out. The source doesn't record which branch is the repo's default, so# exclude the common default-branch names — the same approximation repo_overview's# query_default_branch resolves per-repo, not reused here because it costs an extra query.- return "AND r.head_branch NOT IN ('master', 'main') AND r.pr_number > 0"+ # The cost queries pass the cost source's columns; there pr_number is 0→NULL normalized, so+ # "attributed" becomes ``c.pr_number IS NOT NULL`` rather than ``> 0``.+ return f"AND {branch_column} NOT IN ('master', 'main') AND {attributed_predicate}"return ""diff --git a/products/engineering_analytics/backend/logic/queries/job_aggregates.py b/products/engineering_analytics/backend/logic/queries/job_aggregates.pyindex f03e02aea903..50120b0df88b 100644--- a/products/engineering_analytics/backend/logic/queries/job_aggregates.py+++ b/products/engineering_analytics/backend/logic/queries/job_aggregates.py@@ -18,24 +18,33 @@ from datetime import datetimefrom posthog.hogql import astfrom products.engineering_analytics.backend.facade.contracts import WorkflowJobAggregate-from products.engineering_analytics.backend.logic.cost import estimate_job_cost_usdfrom products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource, opt_float-from products.engineering_analytics.backend.logic.queries._workflow_filters import DURATION_PERCENTILE_CONDITION-from products.engineering_analytics.backend.logic.queries.pr_cost import _parse_labels+from products.engineering_analytics.backend.logic.queries._workflow_filters import (+ DURATION_PERCENTILE_CONDITION,+ branch_filter_clause,+ date_to_filter_clause,+)_LIMIT = 200# De-shard + de-template in SQL so grouping happens server-side over millions of job rows.# Mirrors jobGroups.stripShardSuffix / collapseTemplates on the frontend and# master_failures.strip_shard_suffix in Python — keep the three in sync.-_JOB_NAME = (- "replaceRegexpOne(replaceRegexpAll(name, '\\\\$\\\\{\\\\{[^}]*\\\\}\\\\}', '…'),"+_JOB_NAME_TEMPLATE = (+ "replaceRegexpOne(replaceRegexpAll(__NAME__, '\\\\$\\\\{\\\\{[^}]*\\\\}\\\\}', '…'),"" '\\\\s*\\\\((\\\\d+)/(\\\\d+)\\\\)(\\\\))?$', '\\\\3')")++def _job_name_expr(column: str) -> str:+ """The de-shard/de-template expression over ``column`` — the raw ``name`` in the jobs source, or+ the cost source's ``job_name`` (which is that same ``name``, renamed by the cost builder)."""+ return _JOB_NAME_TEMPLATE.replace("__NAME__", column)++_AGGREGATE_SELECT = f"""SELECT- {_JOB_NAME} AS job_name,+ {_job_name_expr("name")} AS job_name,count() AS job_count,uniq(name) AS shard_count,uniq(run_id) AS runs_in,@@ -51,15 +60,18 @@ _AGGREGATE_SELECT = f"""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} AS job_name,- labels,- sumIf(greatest(duration_seconds, 0), duration_seconds IS NOT NULL) AS elapsed_seconds,- countIf(duration_seconds IS NOT NULL) AS settled_jobs- FROM __JOBS_SOURCE__ AS j+ {_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 cWHERE workflow_name = {{workflow_name}} AND created_at >= {{date_from}} __DATE_TO__ __BRANCH__- GROUP BY job_name, labels+ GROUP BY job_name"""_RUN_COUNT_SELECT = """@@ -78,7 +90,8 @@ def query_job_aggregates(branch: str | None,) -> list[WorkflowJobAggregate]:jobs_source = curated.jobs_source()- if jobs_source is None:+ cost_source = curated.job_cost_source()+ if jobs_source is None or cost_source is None:return []branch = branch.strip() if branch else None@@ -86,19 +99,23 @@ def query_job_aggregates("workflow_name": ast.Constant(value=workflow_name),"date_from": ast.Constant(value=date_from),}- if date_to is not None:- placeholders["date_to"] = ast.Constant(value=date_to)- if branch:- placeholders["branch"] = ast.Constant(value=branch)+ # 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).+ 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")def fill(template: str) -> str:return (template.replace("__JOBS_SOURCE__", jobs_source)+ .replace("__COST_SOURCE__", cost_source).replace("__RUNS_SOURCE__", curated.run_source())- .replace("__DATE_TO__", "AND created_at <= {date_to}" if date_to is not None else "")- .replace("__RUNS_DATE_TO__", "AND run_started_at <= {date_to}" if date_to is not None else "")- .replace("__BRANCH__", "AND head_branch = {branch}" if branch else "")- .replace("__RUNS_BRANCH__", "AND head_branch = {branch}" if branch else "")+ .replace("__DATE_TO__", date_to_clause)+ .replace("__RUNS_DATE_TO__", runs_date_to_clause)+ .replace("__BRANCH__", branch_clause)+ .replace("__RUNS_BRANCH__", runs_branch_clause))response = curated.run(@@ -112,20 +129,17 @@ def query_job_aggregates()total_runs = run_count_response.results[0][0] if run_count_response.results else 0- # Billable cost per job name, folded over its (labels) groups via the shared cost model.+ # 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, labels_raw, elapsed_seconds, settled_jobs in cost_response.results or []:- # An all-unsettled group (every instance still queued/running) sums to 0 elapsed — pass None- # so its cost stays unknown instead of billing a not-yet-finished job as $0.- elapsed = float(elapsed_seconds or 0.0) if settled_jobs else None- cost = estimate_job_cost_usd(_parse_labels(labels_raw), elapsed)- if cost is None:+ 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- seconds, usd = billable_by_job.get(job_name, (0.0, 0.0))- billable_by_job[job_name] = (seconds + (elapsed or 0.0), usd + cost)+ billable_by_job[job_name] = (float(billable_seconds or 0.0), float(cost_sum or 0.0))items: list[WorkflowJobAggregate] = []for (diff --git a/products/engineering_analytics/backend/logic/queries/pr_cost.py b/products/engineering_analytics/backend/logic/queries/pr_cost.pyindex b3747a02a9a6..c1dffe70fbc1 100644--- a/products/engineering_analytics/backend/logic/queries/pr_cost.py+++ b/products/engineering_analytics/backend/logic/queries/pr_cost.py@@ -1,17 +1,25 @@"""HogQL assembly of a PR's estimated CI cost, summed over the jobs of all its runs.Cost is job-level: a run fans into parallel jobs on different runner tiers, so per-PR cost is a sum-over jobs (see ``logic.cost``). This joins the optional jobs source (``_curated.jobs_source``) to the-runs source to bring each job's ``workflow_name`` alongside its ``labels`` / elapsed, then aggregates-in Python twice: once over all jobs (the whole-PR rollup) and once per workflow (the per-workflow cost-column). When the jobs source isn't synced, ``jobs_source()`` is None and this returns an empty summary-(``jobs_available=False``) so the UI hides the cost cards instead of erroring.+over jobs (see ``logic.cost``). Every query here reads the shared per-job cost source+(``_curated.job_cost_source`` — the same rendered model the exposed ``engineering_analytics_job_costs``+view computes) and aggregates the per-job ``billable_seconds`` / ``estimated_cost_usd`` in SQL, so+cost is computed exactly once, in ClickHouse, from the ``logic.cost`` constants. When the jobs source+isn't synced, ``job_cost_source()`` is None and these return empty results (``jobs_available=False``)+so the UI hides the cost cards instead of erroring.++The three-bucket partition (costed / unsettled / excluded) is the SQL twin of the old Python rollup:+a job is costed when its rendered ``estimated_cost_usd`` is non-NULL (billable self-hosted Linux with+a known elapsed — including a real 0.0 for a non-positive elapsed), unsettled when it is a billable+tier with no elapsed yet, and excluded otherwise. ``estimated_cost_usd`` is reconstructed as None when+nothing was costable (a SQL sum over an empty set is 0, which must read as "nothing to cost", never a+real $0.00). Grouped results are small, but each query keeps an explicit ``LIMIT`` so a wide scope+(the PR list scans up to a thousand PRs) can't hit HogQL's default 100-row cap."""-import jsonfrom collections import defaultdict+from collections.abc import Iterablefrom datetime import datetime-from typing import Anyfrom posthog.hogql import ast@@ -23,7 +31,11 @@ from products.engineering_analytics.backend.facade.contracts import (WorkflowHealthRunScope,WorkflowRunnerCost,)-from products.engineering_analytics.backend.logic.cost import PRCostAggregate, aggregate_pr_cost, runner_descriptor+from products.engineering_analytics.backend.logic.cost import (+ PRCostAggregate,+ render_is_billable_tier,+ runner_tier_descriptor,+)from products.engineering_analytics.backend.logic.queries._buckets import (Granularity,bucket_expr,@@ -38,22 +50,64 @@ from products.engineering_analytics.backend.logic.queries._workflow_filters imporun_scope_filter_clause,)-# Pre-aggregated per (workflow, run, attempt, runner-label) — a raw per-job SELECT has no LIMIT, so HogQL-# caps it at DEFAULT_RETURNED_ROWS (100) and silently drops the rest, undercounting any PR with >100 jobs.-# Each group carries finished/elapsed/unfinished, expanded back into per-job tuples (cost is linear in-# elapsed) so the run- and workflow-level rollups stay exact. Same shape as the PR-list cost query.-_SELECT = """- SELECT- r.workflow_name, r.id AS run_id, r.run_attempt, j.labels,- countIf(j.duration_seconds IS NOT NULL) AS finished,- sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL) AS elapsed,- countIf(j.duration_seconds IS NULL) AS unfinished- FROM __JOBS_SOURCE__ AS j- INNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt- WHERE r.pr_number = {pr_number} AND r.repo_owner = {repo_owner} AND r.repo_name = {repo_name}- GROUP BY r.workflow_name, r.id, r.run_attempt, j.labels- LIMIT 1000000-"""+# The billable-tier predicate over the cost source's classified columns — defined once in logic.cost+# so 'depot'/'linux' never appear as literals here.+_BILLABLE_TIER = render_is_billable_tier("c.provider", "c.os")+++def _cost_aggregates(when: str = "1", suffix: str = "") -> str:+ """The five per-scope cost aggregates over the cost source, optionally gated by ``when`` (a SQL+ predicate, e.g. a window) and suffixed so a single scan can carry two windows side by side.++ ``billable_seconds`` sums ``greatest(elapsed, 0)`` over costed rows; ``cost_sum`` sums the rendered+ per-job dollar cost; ``costed_jobs`` counts rows with a non-NULL cost; ``unsettled_jobs`` and+ ``excluded_jobs`` complete the three-bucket partition. ``costed_jobs`` is what tells "$0.00" apart+ from "nothing to cost" downstream — a SQL sum can't.+ """+ return (+ f"sumIf(ifNull(c.billable_seconds, 0), {when}) AS billable_seconds{suffix}, "+ f"sumIf(c.estimated_cost_usd, c.estimated_cost_usd IS NOT NULL AND ({when})) AS cost_sum{suffix}, "+ f"countIf(c.estimated_cost_usd IS NOT NULL AND ({when})) AS costed_jobs{suffix}, "+ f"countIf({_BILLABLE_TIER} AND c.duration_seconds IS NULL AND ({when})) AS unsettled_jobs{suffix}, "+ f"countIf(NOT {_BILLABLE_TIER} AND ({when})) AS excluded_jobs{suffix}"+ )+++def _aggregate(+ billable_seconds: float | None,+ cost_sum: float | None,+ costed: int | None,+ unsettled: int | None,+ excluded: int | None,+) -> PRCostAggregate:+ """Build a ``PRCostAggregate`` from one grouped SQL row's five cost columns."""+ costed_jobs = int(costed or 0)+ return PRCostAggregate(+ billable_seconds=float(billable_seconds or 0.0),+ # None (not 0.0) when nothing was costable, so an all-unsettled/excluded scope reads honestly.+ estimated_cost_usd=float(cost_sum or 0.0) if costed_jobs else None,+ costed_jobs=costed_jobs,+ unsettled_jobs=int(unsettled or 0),+ excluded_jobs=int(excluded or 0),+ )+++def _sum_aggregates(rows: Iterable[tuple]) -> PRCostAggregate:+ """Fold several grouped cost rows (five columns each) into one aggregate — cost is linear, so+ summing finer-grained groups is exact. Used to roll the per-(workflow, run) rows of a PR up to+ per-workflow and whole-PR totals from a single query."""+ billable_seconds = cost_sum = 0.0+ costed = unsettled = excluded = 0+ for row_billable, row_cost, row_costed, row_unsettled, row_excluded in rows:+ billable_seconds += float(row_billable or 0.0)+ cost_sum += float(row_cost or 0.0)+ costed += int(row_costed or 0)+ unsettled += int(row_unsettled or 0)+ excluded += int(row_excluded or 0)+ # Delegate the PRCostAggregate construction (incl. the None-vs-$0.00 rule) to _aggregate, so that+ # rule lives in exactly one place — the folded columns are just its five inputs.+ return _aggregate(billable_seconds, cost_sum, costed, unsettled, excluded)+_EMPTY = PRCostSummary(jobs_available=False,@@ -66,6 +120,22 @@ _EMPTY = PRCostSummary(by_run=[],)+# One grouped scan of the PR's jobs at the finest grain (workflow × run attempt); the whole-PR,+# per-workflow, and per-run rollups all fold from these rows in Python (cost is linear). Filtering on+# the cost source's run-attribution columns (pr_number is 0→NULL normalized) drops jobs whose run row+# is missing, matching the legacy INNER JOIN population.+_PR_COST_SELECT = """+ SELECT+ c.workflow_name AS workflow_name,+ c.run_id AS run_id,+ c.run_attempt AS run_attempt,+ __COST_AGGREGATES__+ FROM __COST_SOURCE__ AS c+ WHERE c.pr_number = {pr_number} AND c.repo_owner = {repo_owner} AND c.repo_name = {repo_name}+ GROUP BY c.workflow_name, c.run_id, c.run_attempt+ LIMIT 1000000+"""+def query_pr_cost(*,@@ -74,11 +144,11 @@ def query_pr_cost(repo_owner: str,repo_name: str,) -> PRCostSummary:- jobs_source = curated.jobs_source()- if jobs_source is None:+ cost_source = curated.job_cost_source()+ if cost_source is None:# The optional job-level source isn't synced for this team yet — no honest cost to report.return _EMPTY- sql = _SELECT.replace("__JOBS_SOURCE__", jobs_source).replace("__RUNS_SOURCE__", curated.run_source())+ sql = _PR_COST_SELECT.replace("__COST_SOURCE__", cost_source).replace("__COST_AGGREGATES__", _cost_aggregates())response = curated.run(sql,query_type="engineering_analytics.pr_cost",@@ -89,21 +159,19 @@ def query_pr_cost(},)rows = response.results or []- all_jobs: list[tuple[list[str], float | None]] = []- by_workflow_jobs: dict[str, list[tuple[list[str], float | None]]] = defaultdict(list)- by_run_jobs: dict[tuple[int, int], list[tuple[list[str], float | None]]] = defaultdict(list)- for workflow, run_id, run_attempt, labels, finished, elapsed, unfinished in rows:- jobs = _expand_jobs(_parse_labels(labels), int(finished or 0), float(elapsed or 0.0), int(unfinished or 0))- all_jobs.extend(jobs)- by_workflow_jobs[workflow or ""].extend(jobs)- by_run_jobs[(int(run_id), int(run_attempt))].extend(jobs)- overall = aggregate_pr_cost(all_jobs)+ overall = _sum_aggregates(row[3:] for row in rows)+ by_workflow_rows: dict[str, list[tuple]] = defaultdict(list)+ by_run_rows: dict[tuple[int, int], list[tuple]] = defaultdict(list)+ for workflow, run_id, run_attempt, *agg in rows:+ by_workflow_rows[workflow or ""].append(tuple(agg))+ by_run_rows[(int(run_id), int(run_attempt))].append(tuple(agg))by_workflow = [- _to_workflow_cost(workflow, aggregate_pr_cost(jobs)) for workflow, jobs in sorted(by_workflow_jobs.items())+ _to_workflow_cost(workflow, _sum_aggregates(agg_rows))+ for workflow, agg_rows in sorted(by_workflow_rows.items())]by_run = [- _to_run_cost(run_id, run_attempt, aggregate_pr_cost(jobs))- for (run_id, run_attempt), jobs in sorted(by_run_jobs.items())+ _to_run_cost(run_id, run_attempt, _sum_aggregates(agg_rows))+ for (run_id, run_attempt), agg_rows in sorted(by_run_rows.items())]return PRCostSummary(@@ -118,21 +186,17 @@ def query_pr_cost()-# Pre-aggregated in SQL (per PR × runner-label combo) so the row count stays small — a raw per-job-# SELECT over every PR's jobs blows past HogQL's default row cap and silently truncates. Each group-# carries finished/elapsed/unfinished, which is expanded back into per-job tuples (cost is linear in-# elapsed) so the pure aggregate_pr_cost still produces the exact rollup. Scoped to the PR numbers the-# list is actually showing so a team with deep CI history doesn't pay an all-time jobs×runs join per page.-_LIST_SELECT = """+# Per-PR billable cost across the given PR numbers, aggregated in SQL and scoped to the visible PR+# numbers so a team with deep CI history doesn't pay an all-time scan per page.+_LIST_COST_SELECT = """SELECT- r.repo_owner, r.repo_name, r.pr_number, j.labels,- countIf(j.duration_seconds IS NOT NULL) AS finished,- sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL) AS elapsed,- countIf(j.duration_seconds IS NULL) AS unfinished- FROM __JOBS_SOURCE__ AS j- INNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt- WHERE r.pr_number IN {pr_numbers}- GROUP BY r.repo_owner, r.repo_name, r.pr_number, j.labels+ c.repo_owner AS repo_owner,+ c.repo_name AS repo_name,+ c.pr_number AS pr_number,+ __COST_AGGREGATES__+ FROM __COST_SOURCE__ AS c+ WHERE c.pr_number IN {pr_numbers}+ GROUP BY c.repo_owner, c.repo_name, c.pr_numberLIMIT 1000000"""@@ -142,39 +206,33 @@ def query_pr_list_costs() -> dict[tuple[str, str, int], PRCostAggregate]:"""Per-PR billable cost across the given PR numbers' runs, keyed by (repo_owner, repo_name, pr_number).- Empty when the jobs source isn't synced or no PR numbers are given. One grouped pass over jobs ⋈ runs- so the PR list can show a cost/minutes column per row without a query per PR; scoped to the visible PR- numbers so the scan tracks the page, not the team's whole CI history.+ Empty when the jobs source isn't synced or no PR numbers are given. One grouped pass over the cost+ source so the PR list can show a cost/minutes column per row without a query per PR; scoped to the+ visible PR numbers so the scan tracks the page, not the team's whole CI history."""- jobs_source = curated.jobs_source()- if jobs_source is None or not pr_numbers:+ cost_source = curated.job_cost_source()+ if cost_source is None or not pr_numbers:return {}- sql = _LIST_SELECT.replace("__JOBS_SOURCE__", jobs_source).replace("__RUNS_SOURCE__", curated.run_source())+ sql = _LIST_COST_SELECT.replace("__COST_SOURCE__", cost_source).replace("__COST_AGGREGATES__", _cost_aggregates())response = curated.run(sql,query_type="engineering_analytics.pr_list_costs",placeholders={"pr_numbers": ast.Constant(value=pr_numbers)},)- by_pr: dict[tuple[str, str, int], list[tuple[list[str], float | None]]] = defaultdict(list)- for repo_owner, repo_name, pr_number, labels, finished, elapsed, unfinished in response.results or []:- by_pr[(repo_owner, repo_name, int(pr_number))].extend(- _expand_jobs(_parse_labels(labels), int(finished or 0), float(elapsed or 0.0), int(unfinished or 0))- )- return {key: aggregate_pr_cost(jobs) for key, jobs in by_pr.items()}+ return {+ (repo_owner, repo_name, int(pr_number)): _aggregate(*agg)+ for repo_owner, repo_name, pr_number, *agg in response.results or []+ }-# Per-workflow billable cost over a window (Workflows tab). Same grouped+expand shape as the PR list,-# but keyed by workflow_name and filtered by the run window + optional branch.+# Per-workflow billable cost over a window (Workflows tab), grouped and costed in SQL and keyed by+# workflow_name. Windowed and optionally branch/run-scope filtered on the run's attributes (the cost+# source carries run_started_at and run_head_branch alongside the per-job cost columns)._WINDOW_COST_SELECT = """- SELECT- r.workflow_name, j.labels,- countIf(j.duration_seconds IS NOT NULL) AS finished,- sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL) AS elapsed,- countIf(j.duration_seconds IS NULL) AS unfinished- FROM __JOBS_SOURCE__ AS j- INNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt- WHERE r.run_started_at >= {date_from} __DATE_TO__ __BRANCH__ __RUN_SCOPE__- GROUP BY r.workflow_name, j.labels+ SELECT c.workflow_name AS workflow_name, __COST_AGGREGATES__+ FROM __COST_SOURCE__ AS c+ WHERE c.run_started_at >= {date_from} __DATE_TO__ __BRANCH__ __RUN_SCOPE__+ GROUP BY c.workflow_nameLIMIT 1000000"""@@ -189,30 +247,29 @@ def query_workflow_window_costs() -> dict[str, PRCostAggregate]:"""Per-workflow billable cost over [date_from, date_to] (optional branch/run_scope), keyed by workflow_name.- Empty when the jobs source isn't synced. Mirrors the PR-list cost: grouped per workflow×label in SQL,- expanded back through aggregate_pr_cost.+ Empty when the jobs source isn't synced. Grouped per workflow in SQL over the shared cost source;+ the window/branch/run_scope predicates read the run's attributes, so the population matches the+ run-level ``query_workflow_health`` (a job whose run is missing has a NULL run_started_at and is+ excluded by the window filter, matching the legacy INNER JOIN)."""- jobs_source = curated.jobs_source()- if jobs_source is None:+ cost_source = curated.job_cost_source()+ if cost_source is None:return {}placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}- date_to_clause = date_to_filter_clause(date_to, placeholders)- branch_clause = branch_filter_clause(branch, placeholders)- run_scope_clause = run_scope_filter_clause(run_scope)+ date_to_clause = date_to_filter_clause(date_to, placeholders, column="c.run_started_at")+ branch_clause = branch_filter_clause(branch, placeholders, column="c.run_head_branch")+ run_scope_clause = run_scope_filter_clause(+ run_scope, branch_column="c.run_head_branch", attributed_predicate="c.pr_number IS NOT NULL"+ )sql = (- _WINDOW_COST_SELECT.replace("__JOBS_SOURCE__", jobs_source)- .replace("__RUNS_SOURCE__", curated.run_source())+ _WINDOW_COST_SELECT.replace("__COST_SOURCE__", cost_source)+ .replace("__COST_AGGREGATES__", _cost_aggregates()).replace("__DATE_TO__", date_to_clause).replace("__BRANCH__", branch_clause).replace("__RUN_SCOPE__", run_scope_clause))response = curated.run(sql, query_type="engineering_analytics.workflow_window_costs", placeholders=placeholders)- by_workflow: dict[str, list[tuple[list[str], float | None]]] = defaultdict(list)- for workflow_name, labels, finished, elapsed, unfinished in response.results or []:- by_workflow[workflow_name or ""].extend(- _expand_jobs(_parse_labels(labels), int(finished or 0), float(elapsed or 0.0), int(unfinished or 0))- )- return {workflow: aggregate_pr_cost(jobs) for workflow, jobs in by_workflow.items()}+ return {(workflow or ""): _aggregate(*agg) for workflow, *agg in response.results or []}# One author's CI spend split by workflow (the author page's "where their CI minutes go"). Runs are@@ -220,18 +277,13 @@ def query_workflow_window_costs(# pr_number alone, since PR numbers restart per repo (SPEC §7). Windowed on the run start so the figure# answers "spend over [window]", never an unbounded all-time._AUTHOR_WORKFLOW_SELECT = """- SELECT- r.workflow_name, j.labels,- countIf(j.duration_seconds IS NOT NULL) AS finished,- sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL) AS elapsed,- countIf(j.duration_seconds IS NULL) AS unfinished- FROM __JOBS_SOURCE__ AS j- INNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt+ SELECT c.workflow_name AS workflow_name, __COST_AGGREGATES__+ FROM __COST_SOURCE__ AS cINNER JOIN (SELECT DISTINCT repo_owner, repo_name, number FROM __PR_SOURCE__ WHERE author_handle = {author}- ) AS ap ON r.repo_owner = ap.repo_owner AND r.repo_name = ap.repo_name AND r.pr_number = ap.number- WHERE r.run_started_at >= {date_from} __DATE_TO__- GROUP BY r.workflow_name, j.labels+ ) AS ap ON c.repo_owner = ap.repo_owner AND c.repo_name = ap.repo_name AND c.pr_number = ap.number+ WHERE c.run_started_at >= {date_from} __DATE_TO__+ GROUP BY c.workflow_nameLIMIT 1000000"""@@ -245,11 +297,12 @@ def query_author_workflow_costs() -> list[WorkflowCost]:"""One author's billable CI cost split by workflow over [date_from, date_to], highest spend first.- Empty when the jobs source isn't synced. Same grouped+expand shape as the other cost queries;- the author→runs link goes through their PR numbers (the one attribution rule, SPEC §7).+ Empty when the jobs source isn't synced. Grouped and costed in SQL over the shared cost source; the+ author→runs link goes through their PR numbers (the one attribution rule, SPEC §7) — the cost+ source's normalized pr_number never matches on an unattributed (NULL) run."""- jobs_source = curated.jobs_source()- if jobs_source is None:+ cost_source = curated.job_cost_source()+ if cost_source is None:return []placeholders: dict[str, ast.Expr] = {"author": ast.Constant(value=author),@@ -257,40 +310,27 @@ def query_author_workflow_costs(}date_to_clause = ""if date_to is not None:- date_to_clause = "AND r.run_started_at <= {date_to}"+ date_to_clause = "AND c.run_started_at <= {date_to}"placeholders["date_to"] = ast.Constant(value=date_to)sql = (- _AUTHOR_WORKFLOW_SELECT.replace("__JOBS_SOURCE__", jobs_source)- .replace("__RUNS_SOURCE__", curated.run_source())+ _AUTHOR_WORKFLOW_SELECT.replace("__COST_SOURCE__", cost_source)+ .replace("__COST_AGGREGATES__", _cost_aggregates()).replace("__PR_SOURCE__", curated.pr_source()).replace("__DATE_TO__", date_to_clause))response = curated.run(sql, query_type="engineering_analytics.author_workflow_costs", placeholders=placeholders)- by_workflow: dict[str, list[tuple[list[str], float | None]]] = defaultdict(list)- for workflow_name, labels, finished, elapsed, unfinished in response.results or []:- by_workflow[workflow_name or ""].extend(- _expand_jobs(_parse_labels(labels), int(finished or 0), float(elapsed or 0.0), int(unfinished or 0))- )- costs = [_to_workflow_cost(workflow, aggregate_pr_cost(jobs)) for workflow, jobs in by_workflow.items()]+ costs = [_to_workflow_cost(workflow or "", _aggregate(*agg)) for workflow, *agg in response.results or []]return sorted(costs, key=lambda cost: (cost.estimated_cost_usd or 0.0, cost.billable_minutes), reverse=True)# The window-cost shape twice over — the current window and the equal-length one before it — as-# per-window conditional aggregates on one jobs⋈runs scan, so the repo hub's delta doesn't pay the-# (largest-table) join twice. Window predicates mirror the two separate calls exactly.+# per-window conditional aggregates on one cost-source scan, so the repo hub's delta doesn't pay the+# scan twice. Window predicates mirror the two separate calls exactly._WINDOW_COST_WITH_PREV_SELECT = """- SELECT- r.workflow_name, j.labels,- countIf(j.duration_seconds IS NOT NULL AND __CUR__) AS finished,- sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL AND __CUR__) AS elapsed,- countIf(j.duration_seconds IS NULL AND __CUR__) AS unfinished,- countIf(j.duration_seconds IS NOT NULL AND __PREV__) AS finished_prev,- sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL AND __PREV__) AS elapsed_prev,- countIf(j.duration_seconds IS NULL AND __PREV__) AS unfinished_prev- FROM __JOBS_SOURCE__ AS j- INNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt- WHERE r.run_started_at >= {prev_from} __DATE_TO__- GROUP BY r.workflow_name, j.labels+ SELECT c.workflow_name AS workflow_name, __CUR_AGG__, __PREV_AGG__+ FROM __COST_SOURCE__ AS c+ WHERE c.run_started_at >= {prev_from} __DATE_TO__+ GROUP BY c.workflow_nameLIMIT 1000000"""@@ -305,63 +345,54 @@ def query_workflow_window_costs_with_prev("""``query_workflow_window_costs`` for [date_from, date_to] and [prev_from, date_from] in one scan.Returns ``(current, previous)``, both keyed by workflow_name; empty when the jobs source isn't synced.+ A workflow lands in a window's dict only when it had at least one job in that window (same as the+ prior implementation), so a workflow present only in the other window doesn't create a phantom+ zero-cost entry."""- jobs_source = curated.jobs_source()- if jobs_source is None:+ cost_source = curated.job_cost_source()+ if cost_source is None:return {}, {}placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from),"prev_from": ast.Constant(value=prev_from),}- cur = "(r.run_started_at >= {date_from}" + (" AND r.run_started_at <= {date_to})" if date_to else ")")- prev = "(r.run_started_at >= {prev_from} AND r.run_started_at <= {date_from})"+ cur = "(c.run_started_at >= {date_from}" + (" AND c.run_started_at <= {date_to})" if date_to else ")")+ prev = "(c.run_started_at >= {prev_from} AND c.run_started_at <= {date_from})"date_to_clause = ""if date_to is not None:- date_to_clause = "AND r.run_started_at <= {date_to}"+ date_to_clause = "AND c.run_started_at <= {date_to}"placeholders["date_to"] = ast.Constant(value=date_to)sql = (- _WINDOW_COST_WITH_PREV_SELECT.replace("__JOBS_SOURCE__", jobs_source)- .replace("__RUNS_SOURCE__", curated.run_source())- .replace("__CUR__", cur)- .replace("__PREV__", prev)+ _WINDOW_COST_WITH_PREV_SELECT.replace("__COST_SOURCE__", cost_source)+ .replace("__CUR_AGG__", _cost_aggregates(when=cur))+ .replace("__PREV_AGG__", _cost_aggregates(when=prev, suffix="_prev")).replace("__DATE_TO__", date_to_clause))response = curated.run(sql, query_type="engineering_analytics.workflow_window_costs_with_prev", placeholders=placeholders)- by_workflow_cur: dict[str, list[tuple[list[str], float | None]]] = defaultdict(list)- by_workflow_prev: dict[str, list[tuple[list[str], float | None]]] = defaultdict(list)- for workflow_name, labels, finished, elapsed, unfinished, finished_prev, elapsed_prev, unfinished_prev in (- response.results or []- ):- parsed = _parse_labels(labels)- by_workflow_cur[workflow_name or ""].extend(- _expand_jobs(parsed, int(finished or 0), float(elapsed or 0.0), int(unfinished or 0))- )- by_workflow_prev[workflow_name or ""].extend(- _expand_jobs(parsed, int(finished_prev or 0), float(elapsed_prev or 0.0), int(unfinished_prev or 0))- )- return (- {workflow: aggregate_pr_cost(jobs) for workflow, jobs in by_workflow_cur.items() if jobs},- {workflow: aggregate_pr_cost(jobs) for workflow, jobs in by_workflow_prev.items() if jobs},- )+ by_workflow_cur: dict[str, PRCostAggregate] = {}+ by_workflow_prev: dict[str, PRCostAggregate] = {}+ for workflow_name, *columns in response.results or []:+ workflow = workflow_name or ""+ cur_agg = _aggregate(*columns[0:5])+ prev_agg = _aggregate(*columns[5:10])+ if _has_jobs(cur_agg):+ by_workflow_cur[workflow] = cur_agg+ if _has_jobs(prev_agg):+ by_workflow_prev[workflow] = prev_agg+ return by_workflow_cur, by_workflow_prev# CI cost per merged PR over time (repo hub's Cost section trend). Two bucketed scans — cost by run-# start, merges by merge time — folded together per bucket. Cost stays a Python rollup (aggregate_pr_cost)-# so the runner-tier multiplier never leaves the backend; only the finished/elapsed/unfinished group-# columns cross from HogQL, same as every other cost query here.+# start, merges by merge time — folded together per bucket. Cost is aggregated in SQL over the shared+# cost source (same rendered model as every other cost surface); only the per-bucket dollar figure+# crosses back to Python._COST_SERIES_SELECT = """- SELECT- __BUCKET_FN__ AS bucket_start,- j.labels,- countIf(j.duration_seconds IS NOT NULL) AS finished,- sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL) AS elapsed,- countIf(j.duration_seconds IS NULL) AS unfinished- FROM __JOBS_SOURCE__ AS j- INNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt- WHERE r.run_started_at >= {date_from} __DATE_TO__- GROUP BY bucket_start, j.labels+ SELECT __BUCKET_FN__ AS bucket_start, __COST_AGGREGATES__+ FROM __COST_SOURCE__ AS c+ WHERE c.run_started_at >= {date_from} __DATE_TO__+ GROUP BY bucket_startLIMIT 1000000"""@@ -399,34 +430,30 @@ def query_cost_per_merge_series(returned so the caller can label an empty chart consistently."""granularity = pick_granularity(date_from, date_to)- jobs_source = curated.jobs_source()- if jobs_source is None:+ cost_source = curated.job_cost_source()+ if cost_source is None:return granularity, []placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}date_to_runs = ""date_to_merged = ""if date_to is not None:- date_to_runs = "AND r.run_started_at <= {date_to}"+ date_to_runs = "AND c.run_started_at <= {date_to}"date_to_merged = "AND merged_at <= {date_to}"placeholders["date_to"] = ast.Constant(value=date_to)cost_sql = (- _COST_SERIES_SELECT.replace("__JOBS_SOURCE__", jobs_source)- .replace("__RUNS_SOURCE__", curated.run_source())- .replace("__BUCKET_FN__", bucket_expr(granularity, "r.run_started_at"))+ _COST_SERIES_SELECT.replace("__COST_SOURCE__", cost_source)+ .replace("__COST_AGGREGATES__", _cost_aggregates())+ .replace("__BUCKET_FN__", bucket_expr(granularity, "c.run_started_at")).replace("__DATE_TO__", date_to_runs))cost_response = curated.run(cost_sql, query_type="engineering_analytics.cost_per_merge_cost", placeholders=placeholders)- jobs_by_bucket: dict[datetime, list[tuple[list[str], float | None]]] = defaultdict(list)- for bucket_start, labels, finished, elapsed, unfinished in cost_response.results or []:- key = normalize_bucket(bucket_start, granularity)- jobs_by_bucket[key].extend(- _expand_jobs(_parse_labels(labels), int(finished or 0), float(elapsed or 0.0), int(unfinished or 0))- )- cost_by_bucket = {bucket: aggregate_pr_cost(jobs).estimated_cost_usd for bucket, jobs in jobs_by_bucket.items()}+ cost_by_bucket: dict[datetime, float | None] = {}+ for bucket_start, *agg in cost_response.results or []:+ cost_by_bucket[normalize_bucket(bucket_start, granularity)] = _aggregate(*agg).estimated_cost_usdmerges_sql = (_MERGES_SERIES_SELECT.replace("__PR_SOURCE__", curated.pr_source())@@ -464,18 +491,19 @@ def query_cost_per_merge_series(# Per-runner-tier cost for one workflow (single-workflow page "where the spend goes" breakdown), scoped# to the page's run window (and optional branch) so the figure always answers "spend over [window]",-# never an unbounded all-time.+# never an unbounded all-time. Grouped by the rendered (provider, os, vcpu) tier in SQL — the cost+# source already classifies each job — and mapped to a display badge/label in Python._RUNNER_COST_SELECT = """SELECT- j.labels,- countIf(j.duration_seconds IS NOT NULL) AS finished,- sumIf(greatest(j.duration_seconds, 0), j.duration_seconds IS NOT NULL) AS elapsed,- countIf(j.duration_seconds IS NULL) AS unfinished- FROM __JOBS_SOURCE__ AS j- INNER JOIN __RUNS_SOURCE__ AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt- WHERE r.repo_owner = {repo_owner} AND r.repo_name = {repo_name} AND r.workflow_name = {workflow_name}- AND r.run_started_at >= {date_from} __DATE_TO__ __BRANCH__- GROUP BY j.labels+ c.provider AS provider,+ c.os AS os,+ c.vcpu AS vcpu,+ count() AS job_count,+ __COST_AGGREGATES__+ FROM __COST_SOURCE__ AS c+ WHERE c.repo_owner = {repo_owner} AND c.repo_name = {repo_name} AND c.workflow_name = {workflow_name}+ AND c.run_started_at >= {date_from} __DATE_TO__ __BRANCH__+ GROUP BY c.provider, c.os, c.vcpuLIMIT 1000000"""@@ -491,10 +519,10 @@ def query_workflow_runner_costs(branch: str | None = None,) -> list[WorkflowRunnerCost]:"""A workflow's CI cost broken down by runner tier over [date_from, date_to] (optional branch),- highest spend first. Empty when the jobs source isn't synced. Raw runner-label combos are folded- into their display tier (via runner_descriptor)."""- jobs_source = curated.jobs_source()- if jobs_source is None:+ highest spend first. Empty when the jobs source isn't synced. Grouped by the rendered+ (provider, os, vcpu) tier and mapped to its display badge/label via ``runner_tier_descriptor``."""+ cost_source = curated.job_cost_source()+ if cost_source is None:return []placeholders: dict[str, ast.Expr] = {"repo_owner": ast.Constant(value=repo_owner),@@ -502,11 +530,11 @@ def query_workflow_runner_costs("workflow_name": ast.Constant(value=workflow_name),"date_from": ast.Constant(value=date_from),}- date_to_clause = date_to_filter_clause(date_to, placeholders)- branch_clause = branch_filter_clause(branch, placeholders)+ date_to_clause = date_to_filter_clause(date_to, placeholders, column="c.run_started_at")+ branch_clause = branch_filter_clause(branch, placeholders, column="c.run_head_branch")sql = (- _RUNNER_COST_SELECT.replace("__JOBS_SOURCE__", jobs_source)- .replace("__RUNS_SOURCE__", curated.run_source())+ _RUNNER_COST_SELECT.replace("__COST_SOURCE__", cost_source)+ .replace("__COST_AGGREGATES__", _cost_aggregates()).replace("__DATE_TO__", date_to_clause).replace("__BRANCH__", branch_clause))@@ -515,20 +543,15 @@ def query_workflow_runner_costs(query_type="engineering_analytics.workflow_runner_costs",placeholders=placeholders,)- by_tier: dict[tuple[str, str], list[tuple[list[str], float | None]]] = defaultdict(list)- for labels_raw, finished, elapsed, unfinished in response.results or []:- labels = _parse_labels(labels_raw)- by_tier[runner_descriptor(labels)].extend(- _expand_jobs(labels, int(finished or 0), float(elapsed or 0.0), int(unfinished or 0))- )- costs = []- for (provider, label), jobs in by_tier.items():- aggregate = aggregate_pr_cost(jobs)+ costs: list[WorkflowRunnerCost] = []+ for provider, os_, vcpu, job_count, *agg in response.results or []:+ aggregate = _aggregate(*agg)+ badge, label = runner_tier_descriptor(provider, os_, int(vcpu) if vcpu is not None else None)costs.append(WorkflowRunnerCost(- provider=provider,+ provider=badge,runner_label=label,- job_count=len(jobs),+ job_count=int(job_count),billable_minutes=aggregate.billable_seconds / 60,estimated_cost_usd=aggregate.estimated_cost_usd,)@@ -536,16 +559,9 @@ def query_workflow_runner_costs(return sorted(costs, key=lambda cost: (cost.estimated_cost_usd or 0.0, cost.billable_minutes), reverse=True)-def _expand_jobs(- labels: list[str], finished: int, elapsed_total: float, unfinished: int-) -> list[tuple[list[str], float | None]]:- """Re-expand a (labels, finished, elapsed_total, unfinished) group into per-job (labels, elapsed)- tuples for aggregate_pr_cost. Elapsed is split evenly across finished jobs — cost is linear in- elapsed, so the summed cost/minutes/counts are identical to costing each real job. The SQL sums- ``greatest(duration_seconds, 0)`` so a single clock-skewed negative duration can't cancel its- group-mates' elapsed before the split — matching aggregate_pr_cost's per-job ``max(0, elapsed)``."""- per = (elapsed_total / finished) if finished else 0.0- return [(labels, per)] * finished + [(labels, None)] * unfinished+def _has_jobs(aggregate: PRCostAggregate) -> bool:+ """True when the aggregate covers at least one job (any bucket) — the "this window had runs" test."""+ return bool(aggregate.costed_jobs + aggregate.unsettled_jobs + aggregate.excluded_jobs)def _to_run_cost(run_id: int, run_attempt: int, aggregate: PRCostAggregate) -> RunCost:@@ -566,13 +582,3 @@ def _to_workflow_cost(workflow_name: str, aggregate: PRCostAggregate) -> Workflounsettled_jobs=aggregate.unsettled_jobs,excluded_jobs=aggregate.excluded_jobs,)---def _parse_labels(raw: Any) -> list[str]:- if not raw:- return []- try:- parsed = json.loads(raw)- except (TypeError, ValueError):- return []- return [str(item) for item in parsed] if isinstance(parsed, list) else []diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.pyindex f24157417c97..fb5a5fe3c2b7 100644--- a/products/engineering_analytics/backend/logic/sources.py+++ b/products/engineering_analytics/backend/logic/sources.py@@ -100,6 +100,25 @@ def resolve_github_tables(raise GitHubSourceNotConnectedError()+def resolve_job_cost_source_pairs(team: Team) -> list[tuple[str, str]]:+ """``(jobs_table, runs_table)`` for every GitHub source with BOTH the jobs and runs endpoints synced.++ Used to build the exposed per-job cost view, which unions across all of a team's qualifying+ sources. Unlike ``resolve_github_tables`` (which needs pull_requests + workflow_runs and returns+ one source), this needs workflow_jobs + workflow_runs and returns all of them — the cost view has+ no PR dependency and shouldn't collapse a team's repos to one. Userless (the view sync runs in a+ system/Temporal context); team scoping is the boundary.+ """+ pairs: list[tuple[str, str]] = []+ for source in _github_sources(team):+ tables = _synced_table_names(team=team, source=source)+ runs = tables.get(WORKFLOW_RUNS_SCHEMA)+ jobs = tables.get(WORKFLOW_JOBS_SCHEMA)+ if runs and jobs:+ pairs.append((jobs, runs))+ return pairs++def list_github_sources(*, team: Team, user_access_control: "UserAccessControl | None" = None) -> list[GitHubSource]:"""The team's connected GitHub sources the caller may access, as selectable refs, oldest first.diff --git a/products/engineering_analytics/backend/logic/views/job_costs.py b/products/engineering_analytics/backend/logic/views/job_costs.pynew file mode 100644index 000000000000..47cb361b5c3c--- /dev/null+++ b/products/engineering_analytics/backend/logic/views/job_costs.py@@ -0,0 +1,231 @@+"""Curated per-job CI cost view — the one warehouse view this product exposes.++Composes the curated ``workflow_jobs`` and ``workflow_runs`` builders (one row per job attempt)+and renders the Depot cost model from ``logic.cost`` as ClickHouse expressions, so+``provider`` / ``os`` / ``vcpu`` / ``multiplier`` / ``billable_seconds`` / ``estimated_cost_usd``+are computed at query time from the same constants the Python model uses. The cost model stays+defined once in ``logic.cost``; this module only wires its rendered expressions over the join.++``build_query`` produces the SELECT for one GitHub source; ``build_team_view`` unions every+qualifying source into the single view body. The join is a LEFT JOIN (all jobs are kept — a job+whose run row is missing keeps NULL attribution) rather than the INNER join the per-PR cost+queries use, because the view is the full per-job substrate, not a PR-scoped rollup.++Nothing here is registered as a global HogQL view; the view is provisioned per-team as a+non-materialized ``DataWarehouseSavedQuery`` by data_modeling's managed-viewset sync.+"""++from typing import TYPE_CHECKING++from posthog.hogql.database.models import (+ DateTimeDatabaseField,+ FieldOrTable,+ FloatDatabaseField,+ IntegerDatabaseField,+ StringDatabaseField,+)++from products.engineering_analytics.backend.logic.cost import (+ render_billable_seconds,+ render_depot_label,+ render_estimated_cost_usd,+ render_hosted_label,+ render_multiplier,+ render_os,+ render_provider,+ render_vcpu,+)+from products.engineering_analytics.backend.logic.sources import resolve_job_cost_source_pairs+from products.engineering_analytics.backend.logic.views import workflow_jobs, workflow_runs++if TYPE_CHECKING:+ from posthog.models.team import Team++# Public view name — stable contract for insights, subscriptions, other products, and execute-sql.+VIEW_NAME = "engineering_analytics_job_costs"++# Public column contract (order matters — it fixes the UNION ALL column order across sources and+# the saved-query schema). Real ``FieldOrTable`` instances so data_modeling derives the stored+# ``{"hogql": <field class>, "clickhouse": <type>, "valid": True}`` metadata via the same+# ``_get_columns_from_fields`` path revenue analytics uses (no hand-written type-string literals to+# drift). ``nullable=True`` where the LEFT JOIN or the cost model can produce NULL (unjoined run →+# NULL attribution; unclassified/non-billable job → NULL cost).+FIELDS: dict[str, FieldOrTable] = {+ "repo_owner": StringDatabaseField(name="repo_owner", nullable=True),+ "repo_name": StringDatabaseField(name="repo_name", nullable=True),+ "pr_number": IntegerDatabaseField(name="pr_number", nullable=True),+ "workflow_name": StringDatabaseField(name="workflow_name"),+ "job_name": StringDatabaseField(name="job_name"),+ "run_id": IntegerDatabaseField(name="run_id"),+ "run_attempt": IntegerDatabaseField(name="run_attempt"),+ "head_branch": StringDatabaseField(name="head_branch"),+ "status": StringDatabaseField(name="status"),+ "conclusion": StringDatabaseField(name="conclusion", nullable=True),+ "runner_name": StringDatabaseField(name="runner_name"),+ "created_at": DateTimeDatabaseField(name="created_at", nullable=True),+ "started_at": DateTimeDatabaseField(name="started_at", nullable=True),+ "completed_at": DateTimeDatabaseField(name="completed_at", nullable=True),+ "queue_seconds": IntegerDatabaseField(name="queue_seconds", nullable=True),+ "duration_seconds": IntegerDatabaseField(name="duration_seconds", nullable=True),+ "provider": StringDatabaseField(name="provider", nullable=True),+ "os": StringDatabaseField(name="os", nullable=True),+ "vcpu": IntegerDatabaseField(name="vcpu", nullable=True),+ "multiplier": IntegerDatabaseField(name="multiplier", nullable=True),+ "billable_seconds": IntegerDatabaseField(name="billable_seconds", nullable=True),+ "estimated_cost_usd": FloatDatabaseField(name="estimated_cost_usd", nullable=True),+}+++# The two endpoint-only run pass-through columns — the run's start time and the *run's* head branch+# (distinct from the job's ``head_branch``), used only by the product's endpoint cost queries to+# window and branch-filter on run attributes. One source of truth: the innermost join layer renders+# "<expr> AS <alias>" and every outer layer re-projects the bare aliases, so a new pass-through is+# added in exactly one place. Deliberately kept out of the public view (``build_team_view`` uses the+# default): ``run_head_branch`` would duplicate ``head_branch`` for the exposed grain, and the view+# already carries ``created_at`` for time filtering.+_RUN_PASSTHROUGH: tuple[tuple[str, str], ...] = (+ ("run_started_at", "r.run_started_at"),+ ("run_head_branch", "r.head_branch"),+)+++def _run_passthrough_defs() -> str:+ """ "<expr> AS <alias>" for each run pass-through — the innermost join layer that first reads them."""+ return "".join(f",\n {expr} AS {alias}" for alias, expr in _RUN_PASSTHROUGH)+++def _run_passthrough_aliases() -> str:+ """Bare aliases for each run pass-through — re-projected by every layer above the join."""+ return "".join(f",\n {alias}" for alias, _ in _RUN_PASSTHROUGH)+++def build_query(*, jobs_table: str, runs_table: str, include_run_columns: bool = False) -> str:+ """The per-job cost SELECT for one GitHub source: curated jobs LEFT JOIN curated runs.++ Grain is one row per job attempt (a retry appears once per attempt — correct for cost). The+ cost columns are derived only from the job's ``labels`` + elapsed, so an unjoined run (no ``r``+ row) leaves only the attribution columns (``repo_owner`` / ``repo_name`` / ``pr_number``) NULL.++ Layered so each per-row classification step is computed once: the join layer parses ``labels_arr``;+ the label layer picks ``depot_label`` / ``hosted_label`` from it (one ``arrayFilter`` scan each);+ the tier layer derives ``provider`` / ``os`` / ``vcpu`` from those two cheap columns; the final+ layer derives ``multiplier`` / ``billable_seconds`` / ``estimated_cost_usd``.++ ``include_run_columns`` threads the ``_RUN_PASSTHROUGH`` run columns through every layer — used+ only by the endpoint cost queries; the public view omits them.+ """+ jobs = workflow_jobs.build_query(jobs_table)+ runs = workflow_runs.build_query(runs_table)++ # labels is already ifNull'd to '[]' by the jobs builder; JSONExtract to Array(String) yields+ # [] for any non-array/invalid JSON, matching cost._parse_labels' empty-on-bad-input behavior.+ labels_array = "JSONExtract(labels, 'Array(String)')"++ inner_run_columns = _run_passthrough_defs() if include_run_columns else ""+ run_columns = _run_passthrough_aliases() if include_run_columns else ""++ return f"""+ SELECT+ repo_owner,+ repo_name,+ pr_number,+ workflow_name,+ job_name,+ run_id,+ run_attempt,+ head_branch,+ status,+ conclusion,+ runner_name,+ created_at,+ started_at,+ completed_at,+ queue_seconds,+ duration_seconds,+ provider,+ os,+ vcpu,+ {render_multiplier("vcpu")} AS multiplier,+ {render_billable_seconds("provider", "os", "duration_seconds")} AS billable_seconds,+ {render_estimated_cost_usd("provider", "os", "vcpu", "duration_seconds")} AS estimated_cost_usd{run_columns}+ FROM (+ SELECT+ repo_owner,+ repo_name,+ pr_number,+ workflow_name,+ job_name,+ run_id,+ run_attempt,+ head_branch,+ status,+ conclusion,+ runner_name,+ created_at,+ started_at,+ completed_at,+ queue_seconds,+ duration_seconds,+ {render_provider("depot_label", "hosted_label")} AS provider,+ {render_os("depot_label", "hosted_label")} AS os,+ {render_vcpu("depot_label", "hosted_label")} AS vcpu{run_columns}+ FROM (+ SELECT+ repo_owner,+ repo_name,+ pr_number,+ workflow_name,+ job_name,+ run_id,+ run_attempt,+ head_branch,+ status,+ conclusion,+ runner_name,+ created_at,+ started_at,+ completed_at,+ queue_seconds,+ duration_seconds,+ {render_depot_label("labels_arr")} AS depot_label,+ {render_hosted_label("labels_arr")} AS hosted_label{run_columns}+ FROM (+ SELECT+ r.repo_owner AS repo_owner,+ r.repo_name AS repo_name,+ -- An unattributed run surfaces pr_number 0 in the runs builder; normalize both+ -- that and the LEFT-JOIN NULL to NULL so a missing PR is never read as PR #0.+ nullIf(r.pr_number, 0) AS pr_number,+ j.workflow_name AS workflow_name,+ j.name AS job_name,+ j.run_id AS run_id,+ j.run_attempt AS run_attempt,+ j.head_branch AS head_branch,+ j.status AS status,+ j.conclusion AS conclusion,+ j.runner_name AS runner_name,+ j.created_at AS created_at,+ j.started_at AS started_at,+ j.completed_at AS completed_at,+ j.queue_seconds AS queue_seconds,+ j.duration_seconds AS duration_seconds,+ {labels_array} AS labels_arr{inner_run_columns}+ FROM ({jobs}) AS j+ LEFT JOIN ({runs}) AS r ON j.run_id = r.id AND j.run_attempt = r.run_attempt+ )+ )+ )+ """+++def build_team_view(team: "Team") -> str | None:+ """The full view body for a team: every GitHub source with both runs and jobs synced, unioned.++ None when the team has no qualifying source (no view is created). One view over all sources so+ the exposed name stays stable regardless of how many GitHub sources a team connects.+ """+ pairs = resolve_job_cost_source_pairs(team)+ if not pairs:+ return None+ selects = [build_query(jobs_table=jobs_table, runs_table=runs_table) for jobs_table, runs_table in pairs]+ return "\nUNION ALL\n".join(selects)diff --git a/products/engineering_analytics/backend/tests/test_cost.py b/products/engineering_analytics/backend/tests/test_cost.pyindex 725a610e98a3..139a556a084d 100644--- a/products/engineering_analytics/backend/tests/test_cost.py+++ b/products/engineering_analytics/backend/tests/test_cost.py@@ -7,7 +7,6 @@ from products.engineering_analytics.backend.logic.cost import (RunnerOS,RunnerProvider,RunnerTier,- aggregate_pr_cost,billing_multiplier,classify_runner,estimate_job_cost_usd,@@ -106,34 +105,3 @@ class TestCostModel:# A Depot job that ran for no measurable time (started == completed, or clock skew) is a# real, measured 0.0 — distinct from the unknown-elapsed case above.assert estimate_job_cost_usd(["depot-ubuntu-latest"], elapsed) == 0.0---class TestAggregatePRCost:- def test_partitions_jobs_by_billability(self):- # One Depot Linux job (costed), one github-hosted (excluded), one non-Linux Depot (excluded),- # one Depot Linux still running (unsettled). Only the first contributes minutes and cost.- result = aggregate_pr_cost(- [- (["depot-ubuntu-22.04-4"], 120.0), # costed: 2 min on a 4-core (2x) tier- (["ubuntu-latest"], 300.0), # github-hosted → excluded- (["depot-macos-14"], 600.0), # non-Linux Depot → excluded- (["depot-ubuntu-22.04-4"], None), # no elapsed → unsettled- ]- )- assert result.costed_jobs == 1- assert result.excluded_jobs == 2- assert result.unsettled_jobs == 1- assert result.billable_seconds == 120.0- assert result.estimated_cost_usd == pytest.approx(2 * REFERENCE_RATE_USD_PER_MIN * 2)-- def test_cost_is_none_when_nothing_costable(self):- # Only excluded / unsettled jobs → "no figure yet", never a misleading $0.00.- result = aggregate_pr_cost([(["ubuntu-latest"], 300.0), (["depot-ubuntu-latest"], None)])- assert result.estimated_cost_usd is None- assert result.costed_jobs == 0-- def test_empty_input(self):- result = aggregate_pr_cost([])- assert result == result.__class__(- billable_seconds=0.0, estimated_cost_usd=None, costed_jobs=0, unsettled_jobs=0, excluded_jobs=0- )diff --git a/products/engineering_analytics/backend/tests/test_job_costs.py b/products/engineering_analytics/backend/tests/test_job_costs.pynew file mode 100644index 000000000000..b262e6cc65c2--- /dev/null+++ b/products/engineering_analytics/backend/tests/test_job_costs.py@@ -0,0 +1,161 @@+import json+import tempfile+from pathlib import Path+from typing import Any++import pytest+from posthog.test.base import BaseTest, ClickhouseTestMixin++import pandas as pd++from posthog.hogql.query import execute_hogql_query++from products.engineering_analytics.backend.logic.cost import (+ RunnerOS,+ RunnerProvider,+ billing_multiplier,+ classify_runner,+ estimate_job_cost_usd,+)+from products.engineering_analytics.backend.logic.views import job_costs+from products.engineering_analytics.backend.logic.views.source_schema import (+ WORKFLOW_JOBS_COLUMNS,+ WORKFLOW_RUNS_COLUMNS,+)+from products.warehouse_sources.backend.test.utils import create_data_warehouse_table_from_csv++TEST_BUCKET = "test_storage_bucket-posthog.products.engineering_analytics.job_costs"+GITHUB_SOURCE_PREFIX = "myprefix"++# The classification matrix: (scenario, labels, started_at, completed_at, status). The view derives+# cost from labels + elapsed only, so every row exercises a distinct classify_runner / cost branch.+# Expected values are computed from the Python model in the test, so a row fails only on Python↔SQL+# drift — exactly the regression this guards.+_BASE = "2026-01-01 10:00:00"+++def _plus(seconds: int) -> str:+ minute, second = divmod(10 * 3600 + seconds, 60)+ hour, minute = divmod(minute, 60)+ return f"2026-01-01 {hour:02d}:{minute:02d}:{second:02d}"+++_MATRIX: list[tuple[str, list[str], str, str | None, str]] = [+ ("depot_linux_sized", ["depot-ubuntu-22.04-16"], _BASE, _plus(600), "completed"),+ ("depot_linux_default", ["depot-ubuntu-latest"], _BASE, _plus(300), "completed"),+ ("depot_macos_versioned", ["depot-macos-14"], _BASE, _plus(600), "completed"),+ ("depot_windows", ["depot-windows-2022"], _BASE, _plus(600), "completed"),+ ("github_hosted", ["ubuntu-latest"], _BASE, _plus(300), "completed"),+ ("unknown_labels", ["self-hosted-custom"], _BASE, _plus(300), "completed"),+ ("decoy_depot_cache", ["depot-docker-cache", "ubuntu-latest"], _BASE, _plus(300), "completed"),+ ("depot_unknown_size", ["depot-ubuntu-22.04-6"], _BASE, _plus(600), "completed"),+ ("unsettled_no_completion", ["depot-ubuntu-latest"], _BASE, None, "in_progress"),+ ("zero_elapsed", ["depot-ubuntu-latest"], _BASE, _BASE, "completed"),+ ("negative_elapsed", ["depot-ubuntu-latest"], _plus(30), _BASE, "completed"),+ ("empty_labels", [], _BASE, _plus(300), "completed"),+]+++def _elapsed_seconds(started: str, completed: str | None, status: str) -> int | None:+ # Mirror the jobs builder: duration is only computed for completed jobs, as completed - started.+ if status != "completed" or completed is None:+ return None+ return int((pd.Timestamp(completed) - pd.Timestamp(started)).total_seconds())+++def _expected_billable(labels: list[str], elapsed: int | None) -> int | None:+ tier = classify_runner(labels)+ if tier is None or tier.provider is not RunnerProvider.DEPOT or tier.os is not RunnerOS.LINUX or elapsed is None:+ return None+ return max(elapsed, 0)+++def _job_row(job_id: int, labels: list[str], started: str, completed: str | None, status: str) -> dict[str, Any]:+ return {+ "id": job_id,+ "run_id": 9000 + job_id,+ "run_attempt": 1,+ "name": f"job-{job_id}",+ "workflow_name": "CI",+ "status": status,+ "conclusion": "success" if status == "completed" else None,+ "head_sha": f"sha{job_id}",+ "head_branch": "main",+ "labels": json.dumps(labels),+ "runner_name": "runner-x",+ "runner_group_name": "",+ "created_at": started,+ "started_at": started,+ "completed_at": completed,+ "steps": "[]",+ }+++class TestJobCostsViewParity(ClickhouseTestMixin, BaseTest):+ """The generated view SQL must produce exactly what the Python cost model produces.++ This is the drift guard for the single-source-of-truth contract: the view is rendered from the+ same constants as logic.cost, so any change to one side that isn't matched on the other shows up+ here. Skips when object storage is unreachable so the suite still runs without the dev stack.+ """++ def _create_table(self, base_name: str, columns: dict, rows: list[dict[str, Any]]) -> str:+ df = pd.DataFrame(rows, columns=list(columns.keys()))+ tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False)+ df.to_csv(tmp.name, index=False)+ tmp.close()+ self.addCleanup(Path(tmp.name).unlink, missing_ok=True)+ try:+ table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(+ csv_path=Path(tmp.name),+ table_name=base_name,+ table_columns=columns,+ test_bucket=TEST_BUCKET,+ team=self.team,+ source_prefix=GITHUB_SOURCE_PREFIX,+ )+ except PermissionError as err:+ self.skipTest(f"object storage unavailable: {err}")+ self.addCleanup(cleanup)+ return table.name++ def test_view_matches_python_cost_model(self) -> None:+ jobs_table = self._create_table(+ "github_workflow_jobs",+ WORKFLOW_JOBS_COLUMNS,+ [+ _job_row(i, labels, started, completed, status)+ for i, (_, labels, started, completed, status) in enumerate(_MATRIX)+ ],+ )+ # A runs table with no matching rows: the cost columns don't depend on the join, so the LEFT+ # JOIN just leaves attribution NULL — exactly the "job without a run row" path.+ runs_table = self._create_table(+ "github_workflow_runs",+ WORKFLOW_RUNS_COLUMNS,+ [dict.fromkeys(WORKFLOW_RUNS_COLUMNS)],+ )++ sql = (+ "SELECT job_name, provider, os, vcpu, multiplier, billable_seconds, estimated_cost_usd "+ f"FROM ({job_costs.build_query(jobs_table=jobs_table, runs_table=runs_table)}) ORDER BY job_name"+ )+ rows = execute_hogql_query(query=sql, team=self.team, query_type="engineering_analytics.test").results+ by_job = {row[0]: row for row in rows}++ for index, (scenario, labels, started, completed, status) in enumerate(_MATRIX):+ elapsed = _elapsed_seconds(started, completed, status)+ tier = classify_runner(labels)+ _job_name, provider, os_, vcpu, multiplier, billable, cost = by_job[f"job-{index}"]++ assert provider == (tier.provider.value if tier else None), scenario+ assert os_ == (tier.os.value if tier else None), scenario+ assert vcpu == (tier.vcpu if tier else None), scenario+ assert multiplier == (billing_multiplier(tier) if tier else None), scenario+ assert billable == _expected_billable(labels, elapsed), scenario++ expected_cost = estimate_job_cost_usd(labels, elapsed)+ if expected_cost is None:+ assert cost is None, scenario+ else:+ assert cost == pytest.approx(expected_cost), scenariodiff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.pyindex c346ba1de649..935ee99335b4 100644--- a/products/engineering_analytics/backend/tests/test_logic.py+++ b/products/engineering_analytics/backend/tests/test_logic.py@@ -400,14 +400,14 @@ class TestEndpointMapping(BaseTest):class TestCostPerMergeSeries(BaseTest):"""The cost-per-merged-PR trend on the repo hub: bucketing, zero-fill, and the cost/mergedivision guard. The two warehouse scans are mocked (curated fully faked), so this tests the- Python fold — the runner-tier cost model, the bucket join, the empty-bucket handling — without- a warehouse. The tier multiplier stays server-side; only group columns cross the mock boundary."""+ Python fold — the bucket join, the trailing-window ratio, the empty-bucket handling — without a+ warehouse. Cost is aggregated in SQL over the shared cost source, so only the per-bucket dollar+ figure crosses the mock boundary."""@staticmethoddef _curated(cost_rows: list[tuple], merges_rows: list[tuple], *, jobs_synced: bool = True) -> mock.Mock:curated = mock.Mock()- curated.jobs_source.return_value = "px_github_workflow_jobs" if jobs_synced else None- curated.run_source.return_value = "px_github_workflow_runs"+ curated.job_cost_source.return_value = "(cost_source)" if jobs_synced else Nonecurated.pr_source.return_value = "px_github_pull_requests"# Cost scan first, then the merges scan — the call order in query_cost_per_merge_series.curated.run.side_effect = [_resp(cost_rows), _resp(merges_rows)]@@ -416,12 +416,12 @@ class TestCostPerMergeSeries(BaseTest):def test_buckets_cost_per_merge_and_zero_fills(self) -> None:date_from = _dt("2026-06-01T00:00:00")date_to = _dt("2026-06-30T00:00:00") # 29-day window -> day granularity, deterministic buckets.- # Columns: bucket_start, labels, finished, elapsed, unfinished. depot-4 (4-core) bills at 2x, so- # 2 min -> 2 * 0.004 * 2 = 0.016; 1 min -> 0.008.+ # Columns: bucket_start, billable_seconds, cost_sum, costed, unsettled, excluded — the SQL cost+ # aggregates. depot-4 (4-core) bills at 2x, so 2 min -> 2 * 0.004 * 2 = 0.016; 1 min -> 0.008.cost_rows = [- (datetime(2026, 6, 2), '["depot-ubuntu-22.04-4"]', 1, 120.0, 0),- (datetime(2026, 6, 3), '["depot-ubuntu-22.04-4"]', 1, 60.0, 0),- (datetime(2026, 6, 6), '["depot-ubuntu-22.04-4"]', 1, 120.0, 0), # cost but no merges below+ (datetime(2026, 6, 2), 120.0, 0.016, 1, 0, 0),+ (datetime(2026, 6, 3), 60.0, 0.008, 1, 0, 0),+ (datetime(2026, 6, 6), 120.0, 0.016, 1, 0, 0), # cost but no merges below]# Columns: bucket_start, merges.merges_rows = [diff --git a/products/engineering_analytics/backend/tests/test_warehouse_view_sync.py b/products/engineering_analytics/backend/tests/test_warehouse_view_sync.pynew file mode 100644index 000000000000..d2c8f06ca40a--- /dev/null+++ b/products/engineering_analytics/backend/tests/test_warehouse_view_sync.py@@ -0,0 +1,120 @@+from posthog.test.base import BaseTest+from unittest.mock import 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.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++PREFIX = "myprefix"+++class TestSyncEngineeringAnalyticsViews(BaseTest):+ def _github_source(self) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=self.team,+ source_id="gh",+ connection_id="gh",+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.GITHUB,+ prefix=PREFIX,+ )++ def _table(self, name: str, source: ExternalDataSource) -> DataWarehouseTable:+ return DataWarehouseTable.objects.create(+ team=self.team,+ name=name,+ format=DataWarehouseTable.TableFormat.CSVWithNames,+ url_pattern="",+ external_data_source=source,+ columns={},+ )++ def _schema(self, source: ExternalDataSource, name: str, table: DataWarehouseTable | None) -> ExternalDataSchema:+ return ExternalDataSchema.objects.create(+ team=self.team, source=source, name=name, table=table, should_sync=True+ )++ def _qualifying_source(self) -> ExternalDataSource:+ source = self._github_source()+ self._schema(source, WORKFLOW_RUNS_SCHEMA, self._table(f"{PREFIX}github_workflow_runs", source))+ self._schema(source, WORKFLOW_JOBS_SCHEMA, self._table(f"{PREFIX}github_workflow_jobs", source))+ return source++ def _has_viewset(self) -> bool:+ return DataWarehouseManagedViewSet.objects.filter(+ team=self.team, kind=DataWarehouseManagedViewSetKind.ENGINEERING_ANALYTICS+ ).exists()++ @patch.object(DataWarehouseManagedViewSet, "sync_views")+ def test_noop_for_non_github_source(self, mock_sync) -> None:+ source = self._qualifying_source()+ source.source_type = ExternalDataSourceType.STRIPE+ source.save()+ schema = ExternalDataSchema.objects.get(source=source, name=WORKFLOW_JOBS_SCHEMA)++ sync_engineering_analytics_views(schema, source)++ mock_sync.assert_not_called()+ assert not self._has_viewset()++ @patch.object(DataWarehouseManagedViewSet, "sync_views")+ def test_noop_for_irrelevant_schema(self, mock_sync) -> None:+ source = self._qualifying_source()+ schema = self._schema(source, "pull_requests", self._table(f"{PREFIX}github_pull_requests", source))++ sync_engineering_analytics_views(schema, source)++ mock_sync.assert_not_called()+ assert not self._has_viewset()++ @patch.object(DataWarehouseManagedViewSet, "sync_views")+ def test_noop_when_jobs_endpoint_not_synced(self, mock_sync) -> None:+ # A GitHub source with only workflow_runs synced has no view to expose yet — don't even+ # create the viewset row until both endpoints exist.+ source = self._github_source()+ schema = self._schema(source, WORKFLOW_RUNS_SCHEMA, self._table(f"{PREFIX}github_workflow_runs", source))++ sync_engineering_analytics_views(schema, source)++ mock_sync.assert_not_called()+ assert not self._has_viewset()++ @patch.object(DataWarehouseManagedViewSet, "sync_views")+ def test_creates_viewset_and_syncs_for_qualifying_source(self, mock_sync) -> None:+ source = self._qualifying_source()+ schema = ExternalDataSchema.objects.get(source=source, name=WORKFLOW_JOBS_SCHEMA)++ sync_engineering_analytics_views(schema, source)++ mock_sync.assert_called_once()+ assert self._has_viewset()++ @parameterized.expand([("operational", OperationalError), ("interface", InterfaceError)])+ @patch("products.engineering_analytics.backend.warehouse_view_sync.capture_exception")+ @patch.object(DataWarehouseManagedViewSet, "sync_views")+ def test_transient_db_error_is_not_captured(self, _name, error_cls, mock_sync, mock_capture) -> None:+ mock_sync.side_effect = error_cls("server closed the connection")+ source = self._qualifying_source()+ schema = ExternalDataSchema.objects.get(source=source, name=WORKFLOW_JOBS_SCHEMA)++ sync_engineering_analytics_views(schema, source)++ mock_capture.assert_not_called()++ @patch("products.engineering_analytics.backend.warehouse_view_sync.capture_exception")+ @patch.object(DataWarehouseManagedViewSet, "sync_views")+ def test_unexpected_error_is_captured(self, mock_sync, mock_capture) -> None:+ error = ValueError("something actually broke")+ mock_sync.side_effect = error+ source = self._qualifying_source()+ schema = ExternalDataSchema.objects.get(source=source, name=WORKFLOW_JOBS_SCHEMA)++ sync_engineering_analytics_views(schema, source)++ mock_capture.assert_called_once_with(error)diff --git a/products/engineering_analytics/backend/warehouse_view_sync.py b/products/engineering_analytics/backend/warehouse_view_sync.pynew file mode 100644index 000000000000..aabc579dbc66--- /dev/null+++ b/products/engineering_analytics/backend/warehouse_view_sync.py@@ -0,0 +1,90 @@+"""Re-sync the engineering-analytics per-job CI cost view after a warehouse data load completes.++Registered into the data-import pipeline via warehouse_sources' external_product_hooks at+app-ready (see apps.py), so the pipeline can trigger it without importing this product+(engineering_analytics depends on warehouse_sources, not the other way round).+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from django.db import InterfaceError, OperationalError++import structlog++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.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKind, ExternalDataSourceType++if TYPE_CHECKING:+ from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource++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)+++def sync_engineering_analytics_views(schema: ExternalDataSchema, source: ExternalDataSource) -> None:+ """Called after validate_schema_and_update_table links a DataWarehouseTable to the schema.++ Returns early unless a GitHub runs/jobs endpoint just loaded. In the steady state the team's+ viewset already exists, so it re-syncs directly (``sync_views`` recomputes the expected views).+ The expected-views guard runs only on first provisioning: a team whose jobs source isn't synced+ 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:+ return++ managed_viewset = DataWarehouseManagedViewSet.objects.filter(+ team=schema.team,+ kind=DataWarehouseManagedViewSetKind.ENGINEERING_ANALYTICS,+ ).first()++ # Only on first provisioning: computing the expected views is the expensive part, so once the+ # viewset exists we skip this guard and re-sync directly (one compute inside sync_views). A+ # team whose jobs source isn't synced yet has no view to expose — don't create the viewset row.+ if managed_viewset is None:+ if not get_expected_warehouse_views(schema.team):+ return+ managed_viewset, _ = DataWarehouseManagedViewSet.objects.get_or_create(+ team=schema.team,+ kind=DataWarehouseManagedViewSetKind.ENGINEERING_ANALYTICS,+ )++ logger.info(+ "sync_engineering_analytics_views_starting",+ team_id=schema.team_id,+ source_id=str(source.id),+ schema_name=schema.name,+ )+ managed_viewset.sync_views()+ logger.info(+ "sync_engineering_analytics_views_completed",+ team_id=schema.team_id,+ source_id=str(source.id),+ )+ except (OperationalError, InterfaceError) as e:+ # Transient pooler connection drop — swallowed, so the view stays stale until the next+ # runs/jobs load re-runs this hook on a fresh connection. Log for visibility but don't+ # spin up an error-tracking issue for a momentary pooler blip.+ logger.warning(+ "sync_engineering_analytics_views_transient_db_error",+ team_id=schema.team_id,+ source_id=str(source.id),+ error=str(e),+ )+ except Exception as e:+ logger.exception(+ "sync_engineering_analytics_views_failed",+ team_id=schema.team_id,+ source_id=str(source.id),+ error=str(e),+ )+ capture_exception(e)diff --git a/products/warehouse_sources/backend/facade/hooks.py b/products/warehouse_sources/backend/facade/hooks.pyindex c21c1b76af21..5d80f0183bcc 100644--- a/products/warehouse_sources/backend/facade/hooks.py+++ b/products/warehouse_sources/backend/facade/hooks.py@@ -11,11 +11,13 @@ on the startup path does not drag the whole pipeline onto every process boot.from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (EmitSignalsActivityInputs,register_emit_signals_gate,+ register_engineering_analytics_view_sync,register_revenue_view_sync,)__all__ = ["EmitSignalsActivityInputs","register_emit_signals_gate",+ "register_engineering_analytics_view_sync","register_revenue_view_sync",]diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py b/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.pyindex 955f1f803ec7..84813ca5a8e5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_product_hooks.py@@ -82,3 +82,19 @@ def run_revenue_view_sync(schema: "ExternalDataSchema", source: "ExternalDataSouif _revenue_view_sync is None:return_revenue_view_sync(schema, source)+++# --- Engineering-analytics view sync --------------------------------------------------+EngineeringAnalyticsViewSync = Callable[["ExternalDataSchema", "ExternalDataSource"], None]+_engineering_analytics_view_sync: Optional[EngineeringAnalyticsViewSync] = None+++def register_engineering_analytics_view_sync(fn: EngineeringAnalyticsViewSync) -> None:+ global _engineering_analytics_view_sync+ _engineering_analytics_view_sync = fn+++def run_engineering_analytics_view_sync(schema: "ExternalDataSchema", source: "ExternalDataSource") -> None:+ if _engineering_analytics_view_sync is None:+ return+ _engineering_analytics_view_sync(schema, source)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.pyindex 99c90c62aaef..5e94e0642d20 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/load.py@@ -14,7 +14,10 @@ from posthog.temporal.common.logger import get_loggerfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema, process_incremental_valuefrom products.warehouse_sources.backend.models.table import DataWarehouseTable-from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import sync_revenue_analytics_views+from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import (+ sync_engineering_analytics_views,+ sync_revenue_analytics_views,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.utils import normalize_column_namefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import set_initial_sync_completefrom products.warehouse_sources.backend.temporal.data_imports.util import prepare_s3_files_for_querying@@ -412,6 +415,9 @@ async def run_post_load_operations(logger.debug("Syncing revenue analytics views if needed")await database_sync_to_async_pool(sync_revenue_analytics_views)(schema, source)+ logger.debug("Syncing engineering analytics views if needed")+ await database_sync_to_async_pool(sync_engineering_analytics_views)(schema, source)+# Measure partition sizes and flag the table for an in-place repartition if a partition has grown# past the memory-safe budget. CDC tables are excluded for now (their companion-table semantics# need separate validation). Detection never raises — it must not break post-load.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/helpers.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/helpers.pyindex 8e8aa75b6614..79807f61e667 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/helpers.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/helpers.py@@ -9,7 +9,10 @@ from django.db.models import Ffrom posthog.sync import database_sync_to_async_poolfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource-from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import run_revenue_view_sync+from products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (+ run_engineering_analytics_view_sync,+ run_revenue_view_sync,+)from products.warehouse_sources.backend.types import IncrementalFieldTypeif TYPE_CHECKING:@@ -99,3 +102,13 @@ def sync_revenue_analytics_views(schema: ExternalDataSchema, source: ExternalDathere). No-ops if revenue_analytics hasn't registered."""run_revenue_view_sync(schema, source)+++def sync_engineering_analytics_views(schema: ExternalDataSchema, source: ExternalDataSource) -> None:+ """Re-sync the engineering-analytics per-job CI cost view after a data load completes.++ Same inversion as the revenue sync above: owned by the engineering_analytics product (which+ depends on warehouse_sources, so it can't be imported here) and registered via+ external_product_hooks. No-ops if engineering_analytics hasn't registered.+ """+ run_engineering_analytics_view_sync(schema, source)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.pyindex 14c7b54acf24..3cdebad99c0c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/pipeline.py@@ -43,7 +43,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.lnotify_revenue_analytics_that_sync_has_completed,supports_partial_data_loading,)-from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import sync_revenue_analytics_views+from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import (+ sync_engineering_analytics_views,+ sync_revenue_analytics_views,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcherfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.cdp_producer import CDPProducerfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.delta_table_helper import (@@ -552,6 +555,9 @@ class PipelineNonDLT(Generic[ResumableData]):await self._logger.adebug("Syncing revenue analytics views")await database_sync_to_async_pool(sync_revenue_analytics_views)(self._schema, self._source)+ await self._logger.adebug("Syncing engineering analytics views")+ await database_sync_to_async_pool(sync_engineering_analytics_views)(self._schema, self._source)+def _estimate_size(obj: Any) -> int:if isinstance(obj, dict):diff --git a/products/warehouse_sources/backend/types.py b/products/warehouse_sources/backend/types.pyindex d32d8644a233..c8cccedb2f2e 100644--- a/products/warehouse_sources/backend/types.py+++ b/products/warehouse_sources/backend/types.py@@ -813,3 +813,4 @@ DIRECT_ENGINE_BY_SOURCE_TYPE: dict[str, str] = {class DataWarehouseManagedViewSetKind(models.TextChoices):REVENUE_ANALYTICS = "revenue_analytics", "Revenue Analytics"+ ENGINEERING_ANALYTICS = "engineering_analytics", "Engineering Analytics"diff --git a/tach.toml b/tach.tomlindex 7590a35ba39b..7bb163091ff6 100644--- a/tach.toml+++ b/tach.toml@@ -234,6 +234,7 @@ depends_on = ["posthog","products.data_tools","products.data_warehouse",+ "products.engineering_analytics","products.revenue_analytics","products.warehouse_sources",]@@ -1001,7 +1002,7 @@ from = [[[modules]]path = "products.engineering_analytics"-depends_on = ["posthog", "products.warehouse_sources"]+depends_on = ["posthog", "products.data_modeling", "products.warehouse_sources"]layer = "modules"[[interfaces]]