Skip to content

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

fix(eng-analytics): resolve warehouse tables per team (#63612)

Raúl Negrón-Otero2a9bb5a25bd9
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 102c30ca5336..2038769a6004 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -51,11 +51,11 @@ graph TB
Rules:
-- **Curated read layer = curated query builders** over the warehouse tables: `backend/logic/views/{pull_requests,workflow_runs}.py` each expose `build_query()` returning a curated `SELECT` over the raw `github_*` table. Query modules (`backend/logic/queries/`) embed those as parenthesised subqueries (via `_curated`) and run them with `execute_hogql_query`. Repo identity (`base.repo.full_name`), labels, `is_bot`, and the PR↔CI head-SHA join are mapped here **from the JSON the source already lands — no new ingestion**. Domain rules (bot detection, default exclusions, the join, honest metric naming) are defined exactly **once**, here. **Nothing is registered in `Database.create_for`** — the product is not a global-catalog citizen, which keeps it off the per-query hot path and means `posthog/hogql` never imports it (the viewset registration in `posthog/api/` is the normal product edge, loaded once at URL-conf time).
+- **Curated read layer = curated query builders** over the warehouse tables: `backend/logic/views/{pull_requests,workflow_runs}.py` each expose `build_query(table_name)` returning a curated `SELECT` over the team's GitHub table. The table's real name is `ExternalDataSource.prefix + "github_<endpoint>"` and the prefix is user-chosen, so the name is **resolved per-team at request time** by `backend/logic/sources.py` (walking the team's GitHub source → its `pull_requests`/`workflow_runs` schemas → `schema.table.name`) — never hardcoded. Query modules (`backend/logic/queries/`) embed the builders as parenthesised subqueries (via `_curated`) and run them with `execute_hogql_query`. Repo identity (`base.repo.full_name`), labels, `is_bot`, and the PR↔CI head-SHA join are mapped here **from the JSON the source already lands — no new ingestion**. Domain rules (bot detection, default exclusions, the join, honest metric naming) are defined exactly **once**, here. **Nothing is registered in `Database.create_for`** — the product is not a global-catalog citizen, which keeps it off the per-query hot path and means `posthog/hogql` never imports it (the viewset registration in `posthog/api/` is the normal product edge, loaded once at URL-conf time).
- **MCP is the official surface, via named typed endpoints.** Each capability is a DRF action with `@extend_schema` that flows to an MCP tool through OpenAPI codegen (`ci_cards`, `pull_requests`, `workflow_health`, `pr_lifecycle`). This is the `visual_review` shape: core imports only the viewset; everything else stays in the product.
- **The UI reads the same endpoints** via the generated typed API client (kea loaders) — not client-side HogQL, and not bespoke report endpoints distinct from the MCP ones. One endpoint set, two consumers.
- HogQL only, via `execute_hogql_query`. No raw ClickHouse `sync_execute()`. No product Postgres DB.
-- The curated builders (and `logic/queries/`) are the only place that names warehouse tables or GitHub-shaped columns. Canonical types stay above them.
+- Warehouse table names are resolved per-team in `logic/sources.py`; the curated builders (and `logic/queries/`) are the only place that maps GitHub-shaped columns. Canonical types stay above them.
- Every named-tool PR ships a matching `skills/<name>/SKILL.md` teaching tool selection and carrying the metric caveats — same pattern as `products/visual_review/skills/triaging-visual-review-runs/`.
- Provider abstraction (`CodeHostProvider` Protocol) is **deferred**. GitHub-specific HogQL lives in the curated builders; when a second provider lands, the Protocol is extracted then. See §7.
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index 23bc0f934e9e..c584dccd3ec9 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -7,8 +7,16 @@ parameters and return canonical contract types.
``repo`` is an optional ``owner/name`` filter, applied against the curated repo
identity (mapped from ``base.repo.full_name``). ``date_from`` / ``date_to`` accept
relative strings (``-30d``) or ISO8601 and are resolved against the team timezone.
+``source_id`` selects a specific connected GitHub source when the team has more than
+one; it defaults to the oldest connected source. ``user_access_control`` enforces the
+requesting user's per-source warehouse access (pass the request's; ``None`` for system
+contexts). Each function resolves the team's authorized curated read handle once, here,
+then delegates to the read layer — source selection and access control live in this layer,
+not in the query builders below it.
"""
+from typing import TYPE_CHECKING
+
from posthog.models.team import Team
from products.engineering_analytics.backend import logic
@@ -19,26 +27,52 @@ from products.engineering_analytics.backend.facade.contracts import (
WorkflowHealthItem,
)
+if TYPE_CHECKING:
+ from posthog.rbac.user_access_control import UserAccessControl
+
+ from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+
+
+def _authorized_source(
+ team: Team, source_id: str | None, user_access_control: "UserAccessControl | None"
+) -> "CuratedGitHubSource":
+ """Resolve this caller's curated read handle — the single place source selection and per-source
+ warehouse access control happen. ``user_access_control`` (None for system/Temporal/CLI contexts)
+ filters out sources the requesting user can't access; ``source_id`` selects a specific source,
+ else the oldest connected. Raises ``GitHubSourceNotConnectedError`` / ``ValueError`` (bad source_id).
+ """
+ return logic.CuratedGitHubSource.for_team(team, source_id=source_id, user_access_control=user_access_control)
+
def get_pr_lifecycle(
*,
team: Team,
pr_number: int,
repo: str | None = None,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
) -> PRLifecycle | None:
- return logic.build_pr_lifecycle(team=team, pr_number=pr_number, repo=repo)
+ return logic.build_pr_lifecycle(
+ curated=_authorized_source(team, source_id, user_access_control), pr_number=pr_number, repo=repo
+ )
-def get_ci_cards(*, team: Team) -> CICardSummary:
- return logic.build_ci_cards(team=team)
+def get_ci_cards(
+ *, team: Team, source_id: str | None = None, user_access_control: "UserAccessControl | None" = None
+) -> CICardSummary:
+ return logic.build_ci_cards(curated=_authorized_source(team, source_id, user_access_control))
def list_pull_requests(
*,
team: Team,
date_from: str | None = None,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
) -> PullRequestList:
- return logic.build_pull_request_list(team=team, date_from=date_from)
+ return logic.build_pull_request_list(
+ curated=_authorized_source(team, source_id, user_access_control), date_from=date_from
+ )
def list_workflow_health(
@@ -46,5 +80,9 @@ def list_workflow_health(
team: Team,
date_from: str | None = None,
date_to: str | None = None,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
) -> list[WorkflowHealthItem]:
- return logic.build_workflow_health(team=team, date_from=date_from, date_to=date_to)
+ return logic.build_workflow_health(
+ curated=_authorized_source(team, source_id, user_access_control), date_from=date_from, date_to=date_to
+ )
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index 1f6b71404a89..ff6f65ddf74f 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -1,9 +1,10 @@
"""Orchestration for engineering_analytics.
-Resolves caller inputs (PostHog-convention date strings, ``owner/name`` repo) into
-the values the query layer needs and returns canonical contract types. The curated
-query builders (``backend/logic/views``) own all GitHub-shaped mapping and domain
-rules; this layer deals only in canonical types.
+Resolves caller inputs (PostHog-convention date strings, ``owner/name`` repo) and binds the
+team to its curated GitHub read layer (``CuratedGitHubSource``, which resolves the warehouse
+table names), then returns canonical contract types. The curated query builders
+(``backend/logic/views``) own all GitHub-shaped mapping and domain rules; this layer deals
+only in canonical types.
"""
from datetime import datetime
@@ -17,6 +18,7 @@ from products.engineering_analytics.backend.facade.contracts import (
PullRequestList,
WorkflowHealthItem,
)
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
from products.engineering_analytics.backend.logic.queries.ci_cards import query_ci_cards
from products.engineering_analytics.backend.logic.queries.pr_lifecycle import query_pr_lifecycle
from products.engineering_analytics.backend.logic.queries.pull_request_list import query_pull_request_list
@@ -31,31 +33,32 @@ _DEFAULT_WINDOW = "-30d"
_MAX_WINDOW_DAYS = 366
-def build_pr_lifecycle(*, team: Team, pr_number: int, repo: str | None) -> PRLifecycle | None:
+# Each builder operates on an already-resolved CuratedGitHubSource: source selection and per-source
+# warehouse access control happen once at the facade, which hands these builders the authorized
+# handle. They validate their own inputs (dates, repo) and read PR/CI data through the handle.
+def build_pr_lifecycle(*, curated: CuratedGitHubSource, pr_number: int, repo: str | None) -> PRLifecycle | None:
owner, name = _split_repo(repo)
- return query_pr_lifecycle(team=team, pr_number=pr_number, repo_owner=owner, repo_name=name)
+ return query_pr_lifecycle(curated=curated, pr_number=pr_number, repo_owner=owner, repo_name=name)
-def build_ci_cards(*, team: Team) -> CICardSummary:
- return query_ci_cards(team=team)
+def build_ci_cards(*, curated: CuratedGitHubSource) -> CICardSummary:
+ return query_ci_cards(curated=curated)
-def build_pull_request_list(*, team: Team, date_from: str | None = None) -> PullRequestList:
- return query_pull_request_list(team=team, date_from=_parse_date(team, date_from or _DEFAULT_WINDOW))
+def build_pull_request_list(*, curated: CuratedGitHubSource, date_from: str | None = None) -> PullRequestList:
+ parsed_from = _parse_date(curated.team, date_from or _DEFAULT_WINDOW)
+ return query_pull_request_list(curated=curated, date_from=parsed_from)
def build_workflow_health(
- *,
- team: Team,
- date_from: str | None = None,
- date_to: str | None = None,
+ *, curated: CuratedGitHubSource, date_from: str | None = None, date_to: str | None = None
) -> list[WorkflowHealthItem]:
- parsed_from = _parse_date(team, date_from or _DEFAULT_WINDOW)
- parsed_to = _parse_date(team, date_to) if date_to else None
+ parsed_from = _parse_date(curated.team, date_from or _DEFAULT_WINDOW)
+ parsed_to = _parse_date(curated.team, date_to) if date_to else None
span_days = ((parsed_to or datetime.now(tz=parsed_from.tzinfo)) - parsed_from).days
if span_days > _MAX_WINDOW_DAYS:
raise ValueError(f"date window spans {span_days} days; the maximum is {_MAX_WINDOW_DAYS}")
- return query_workflow_health(team=team, date_from=parsed_from, date_to=parsed_to)
+ return query_workflow_health(curated=curated, date_from=parsed_from, date_to=parsed_to)
def _parse_date(team: Team, value: str) -> datetime:
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index 87b0ef8527e9..12828e3f60d8 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -1,101 +1,119 @@
-"""Shared helpers for the curated query modules.
-
-The ``pull_requests`` / ``workflow_runs`` builders return a curated ``SELECT``
-over the raw ``github_*`` warehouse tables. Query modules embed those as
-parenthesised subqueries (``FROM {pr_source()} AS pr``) and run them with
-``run_query`` — the product reads its data privately rather than registering a
-global HogQL view, keeping it off the per-query catalog hot path.
-
-Every fragment here is built from trusted constants. User-supplied values must
-always flow through ``ast.Constant`` placeholders in the calling query, never be
-string-substituted into these fragments.
+"""The curated read layer over a team's GitHub warehouse tables.
+
+``CuratedGitHubSource`` binds one team to its resolved ``pull_requests`` / ``workflow_runs``
+table names (see ``logic.sources``) and is the single object the query modules use: it hands
+out the curated ``SELECT`` subqueries and the CI rollup CTE, and runs the assembled HogQL.
+The resolved table names live inside it, so the query layer never threads or re-derives them.
+The product reads its data privately this way — nothing is registered as a global HogQL view,
+keeping it off the per-query catalog hot path.
+
+Every SQL fragment is built from trusted constants and the resolved table identifiers (which
+the resolver has validated to ``[A-Za-z_][A-Za-z0-9_]*``). User-supplied values must always
+flow through ``ast.Constant`` placeholders in the calling query, never be string-substituted
+into these fragments.
"""
+from typing import TYPE_CHECKING
+
from posthog.schema import HogQLQueryResponse
from posthog.hogql import ast
-from posthog.hogql.errors import QueryError
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.models.team import Team
-from products.engineering_analytics.backend.facade.contracts import GitHubSourceNotConnectedError
+from products.engineering_analytics.backend.logic.sources import GitHubTables, resolve_github_tables
from products.engineering_analytics.backend.logic.views import pull_requests, workflow_runs
-# The curated builders are the only place a warehouse table is named; reuse their
-# constants so "which tables mean a GitHub source is connected" is defined once.
-_SOURCE_TABLES = (pull_requests.SOURCE_TABLE, workflow_runs.SOURCE_TABLE)
+if TYPE_CHECKING:
+ from posthog.rbac.user_access_control import UserAccessControl
-def pr_source() -> str:
- """Curated pull-requests ``SELECT``, parenthesised for use as a subquery."""
- return f"({pull_requests.build_query()})"
+class CuratedGitHubSource:
+ """A team's curated GitHub read layer, bound to its resolved warehouse tables.
+ Construct once per request with ``for_team`` — it resolves the table names and raises
+ ``GitHubSourceNotConnectedError`` when the team has no connected GitHub source, so the
+ "is a source connected" decision lives in exactly one place (the resolver). The query
+ modules then ask the returned instance for the curated subqueries and run HogQL through it.
+ """
-def run_source() -> str:
- """Curated workflow-runs ``SELECT``, parenthesised for use as a subquery."""
- return f"({workflow_runs.build_query()})"
+ def __init__(self, *, team: Team, tables: GitHubTables) -> None:
+ self._team = team
+ self._tables = tables
+
+ @property
+ def team(self) -> Team:
+ """The team this handle reads for — query builders need it for timezone-aware date parsing."""
+ return self._team
+
+ @classmethod
+ def for_team(
+ cls, team: Team, *, source_id: str | None = None, user_access_control: "UserAccessControl | None" = None
+ ) -> "CuratedGitHubSource":
+ return cls(
+ team=team,
+ tables=resolve_github_tables(team=team, source_id=source_id, user_access_control=user_access_control),
+ )
+ def pr_source(self) -> str:
+ """Curated pull-requests ``SELECT``, parenthesised for use as a subquery."""
+ return f"({pull_requests.build_query(self._tables.pull_requests)})"
-def ci_rollup_cte() -> str:
- """CTE collapsing each head SHA's workflow runs into pass/fail/pending counts.
+ def run_source(self) -> str:
+ """Curated workflow-runs ``SELECT``, parenthesised for use as a subquery."""
+ return f"({workflow_runs.build_query(self._tables.workflow_runs)})"
- Takes the latest run per ``(head_sha, workflow_name)`` via ``argMax`` (a PR's
- CI status is its newest run per workflow), then aggregates per SHA. The join
- target for the cards and pull-request-list queries; ``head_sha`` is the only
- link between a PR and its CI.
- """
- return f"""
- ci_rollup AS (
- SELECT
- head_sha,
- count() AS runs,
- countIf(s = 'completed' AND c = 'success') AS passing,
- countIf(s = 'completed' AND c IN ('failure', 'timed_out')) AS failing,
- countIf(s != 'completed') AS pending
- FROM (
+ def ci_rollup_cte(self) -> str:
+ """CTE collapsing each head SHA's workflow runs into pass/fail/pending counts.
+
+ Takes the latest run per ``(head_sha, workflow_name)`` via ``argMax`` (a PR's CI status
+ is its newest run per workflow), then aggregates per SHA. The join target for the cards
+ and pull-request-list queries; ``head_sha`` is the only link between a PR and its CI.
+ """
+ return f"""
+ ci_rollup AS (
SELECT
head_sha,
- workflow_name,
- argMax(status, run_started_at) AS s,
- argMax(conclusion, run_started_at) AS c
- FROM {run_source()} AS r
- GROUP BY head_sha, workflow_name
+ count() AS runs,
+ countIf(s = 'completed' AND c = 'success') AS passing,
+ countIf(s = 'completed' AND c IN ('failure', 'timed_out')) AS failing,
+ countIf(s != 'completed') AS pending
+ FROM (
+ SELECT
+ head_sha,
+ workflow_name,
+ argMax(status, run_started_at) AS s,
+ argMax(conclusion, run_started_at) AS c
+ FROM {self.run_source()} AS r
+ GROUP BY head_sha, workflow_name
+ )
+ GROUP BY head_sha
)
- GROUP BY head_sha
- )
- """
-
-
-def run_query(
- sql: str,
- *,
- team: Team,
- query_type: str,
- placeholders: dict[str, ast.Expr] | None = None,
-) -> HogQLQueryResponse:
- """Parse + execute a curated HogQL query.
-
- Raises ``GitHubSourceNotConnectedError`` when the team has no GitHub warehouse
- source: the curated subqueries reference the ``github_*`` tables, which aren't in
- the catalog, so the resolver raises ``Unknown table``. The presentation layer
- turns that into a clear 4xx. Any other query error is a real bug and propagates.
- """
- try:
- with tags_context(product=Product.ENGINEERING_ANALYTICS, feature=Feature.QUERY, team_id=team.pk):
+ """
+
+ def pr_rollup_query(self, select: str) -> str:
+ """Compose a pull-requests query that reads ``FROM __PR_SOURCE__ AS pr LEFT JOIN ci_rollup``.
+
+ Prefixes ``select`` with the CI rollup CTE and fills its ``__PR_SOURCE__`` placeholder
+ with the curated pull-requests source — the two steps the cards and PR-list queries always
+ do together.
+ """
+ return f"WITH {self.ci_rollup_cte()} {select}".replace("__PR_SOURCE__", self.pr_source())
+
+ def run(
+ self,
+ sql: str,
+ *,
+ query_type: str,
+ placeholders: dict[str, ast.Expr] | None = None,
+ ) -> HogQLQueryResponse:
+ """Parse + execute a curated HogQL query for this team."""
+ with tags_context(product=Product.ENGINEERING_ANALYTICS, feature=Feature.QUERY, team_id=self._team.pk):
return execute_hogql_query(
query=parse_select(sql, placeholders=placeholders),
- team=team,
+ team=self._team,
query_type=query_type,
)
- except QueryError as err:
- message = str(err)
- # HogQL raises ``Unknown table `<name>`.`` for any table missing from the
- # catalog. Only the absence of OUR source tables means "no GitHub source";
- # any other unknown table is a real bug (e.g. a typo in a curated builder)
- # and must surface unchanged rather than masquerade as a missing-source 4xx.
- if any(f"Unknown table `{table}`" in message for table in _SOURCE_TABLES):
- raise GitHubSourceNotConnectedError() from err
- raise
diff --git a/products/engineering_analytics/backend/logic/queries/ci_cards.py b/products/engineering_analytics/backend/logic/queries/ci_cards.py
index 909fee94615e..63569eaa5435 100644
--- a/products/engineering_analytics/backend/logic/queries/ci_cards.py
+++ b/products/engineering_analytics/backend/logic/queries/ci_cards.py
@@ -5,10 +5,8 @@ is a fixed rule (open, non-draft, non-bot, older than 7 days), so there is no
window parameter.
"""
-from posthog.models.team import Team
-
from products.engineering_analytics.backend.facade.contracts import CICardSummary
-from products.engineering_analytics.backend.logic.queries import _curated
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
_EMPTY = CICardSummary(open_prs=0, repos=0, stuck=0, failing_ci=0)
@@ -25,9 +23,8 @@ _SELECT = """
"""
-def query_ci_cards(*, team: Team) -> CICardSummary:
- sql = f"WITH {_curated.ci_rollup_cte()} {_SELECT}".replace("__PR_SOURCE__", _curated.pr_source())
- response = _curated.run_query(sql, team=team, query_type="engineering_analytics.ci_cards")
+def query_ci_cards(*, curated: CuratedGitHubSource) -> CICardSummary:
+ response = curated.run(curated.pr_rollup_query(_SELECT), query_type="engineering_analytics.ci_cards")
if not response.results:
return _EMPTY
open_prs, repos, stuck, failing_ci = response.results[0]
diff --git a/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py b/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py
index 7721bff58b5a..c42511d350aa 100644
--- a/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py
+++ b/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py
@@ -10,8 +10,6 @@ live here.
from posthog.hogql import ast
-from posthog.models.team import Team
-
from products.engineering_analytics.backend.facade.contracts import (
Author,
PRLifecycle,
@@ -21,7 +19,7 @@ from products.engineering_analytics.backend.facade.contracts import (
PullRequest,
RepoRef,
)
-from products.engineering_analytics.backend.logic.queries import _curated
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
# The curated subqueries and the repo filter are filled with str.replace (trusted
# constants), leaving the HogQL {value} placeholders untouched for parse_select.
@@ -47,7 +45,7 @@ _RUNS = """
def query_pr_lifecycle(
*,
- team: Team,
+ curated: CuratedGitHubSource,
pr_number: int,
repo_owner: str | None,
repo_name: str | None,
@@ -59,10 +57,9 @@ def query_pr_lifecycle(
placeholders["repo_owner"] = ast.Constant(value=repo_owner)
placeholders["repo_name"] = ast.Constant(value=repo_name)
- header_sql = _HEADER.replace("__PR_SOURCE__", _curated.pr_source()).replace("__REPO_FILTER__", repo_filter)
- header = _curated.run_query(
+ header_sql = _HEADER.replace("__PR_SOURCE__", curated.pr_source()).replace("__REPO_FILTER__", repo_filter)
+ header = curated.run(
header_sql,
- team=team,
query_type="engineering_analytics.pr_lifecycle.header",
placeholders=placeholders,
)
@@ -106,9 +103,8 @@ def query_pr_lifecycle(
events = [PRLifecycleEvent(kind=PRLifecycleEventKind.OPENED, at=created_at)]
runs = (
- _curated.run_query(
- _RUNS.replace("__RUNS_SOURCE__", _curated.run_source()),
- team=team,
+ curated.run(
+ _RUNS.replace("__RUNS_SOURCE__", curated.run_source()),
query_type="engineering_analytics.pr_lifecycle.runs",
placeholders={"head_sha": ast.Constant(value=head_sha)},
)
diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_list.py b/products/engineering_analytics/backend/logic/queries/pull_request_list.py
index d2dc4982edd8..07526c459d3a 100644
--- a/products/engineering_analytics/backend/logic/queries/pull_request_list.py
+++ b/products/engineering_analytics/backend/logic/queries/pull_request_list.py
@@ -11,8 +11,6 @@ from datetime import datetime
from posthog.hogql import ast
-from posthog.models.team import Team
-
from products.engineering_analytics.backend.facade.contracts import (
Author,
CIStatusRollup,
@@ -21,7 +19,7 @@ from products.engineering_analytics.backend.facade.contracts import (
PullRequestListItem,
RepoRef,
)
-from products.engineering_analytics.backend.logic.queries import _curated
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
_LIMIT = 1000
@@ -45,11 +43,9 @@ _SELECT = f"""
"""
-def query_pull_request_list(*, team: Team, date_from: datetime) -> PullRequestList:
- sql = f"WITH {_curated.ci_rollup_cte()} {_SELECT}".replace("__PR_SOURCE__", _curated.pr_source())
- response = _curated.run_query(
- sql,
- team=team,
+def query_pull_request_list(*, curated: CuratedGitHubSource, date_from: datetime) -> PullRequestList:
+ response = curated.run(
+ curated.pr_rollup_query(_SELECT),
query_type="engineering_analytics.pull_request_list",
placeholders={"date_from": ast.Constant(value=date_from)},
)
diff --git a/products/engineering_analytics/backend/logic/queries/workflow_health.py b/products/engineering_analytics/backend/logic/queries/workflow_health.py
index 57aa7673a8cf..3ce8264a440d 100644
--- a/products/engineering_analytics/backend/logic/queries/workflow_health.py
+++ b/products/engineering_analytics/backend/logic/queries/workflow_health.py
@@ -11,10 +11,8 @@ from datetime import date, datetime, timedelta
from posthog.hogql import ast
-from posthog.models.team import Team
-
from products.engineering_analytics.backend.facade.contracts import RepoRef, WorkflowHealthDay, WorkflowHealthItem
-from products.engineering_analytics.backend.logic.queries import _curated
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
_LIMIT = 100
# Generous bound: _LIMIT workflows x ~1 row per day for windows up to a quarter.
@@ -55,7 +53,7 @@ _DAILY_SELECT = f"""
def query_workflow_health(
*,
- team: Team,
+ curated: CuratedGitHubSource,
date_from: datetime,
date_to: datetime | None,
) -> list[WorkflowHealthItem]:
@@ -64,20 +62,19 @@ def query_workflow_health(
if date_to is not None:
placeholders["date_to"] = ast.Constant(value=date_to)
- sql = _SELECT.replace("__RUNS_SOURCE__", _curated.run_source()).replace("__DATE_TO__", date_to_clause)
- response = _curated.run_query(
+ runs_source = curated.run_source()
+ sql = _SELECT.replace("__RUNS_SOURCE__", runs_source).replace("__DATE_TO__", date_to_clause)
+ response = curated.run(
sql,
- team=team,
query_type="engineering_analytics.workflow_health",
placeholders=placeholders,
)
if not response.results:
return []
- daily_sql = _DAILY_SELECT.replace("__RUNS_SOURCE__", _curated.run_source()).replace("__DATE_TO__", date_to_clause)
- daily_response = _curated.run_query(
+ daily_sql = _DAILY_SELECT.replace("__RUNS_SOURCE__", runs_source).replace("__DATE_TO__", date_to_clause)
+ daily_response = curated.run(
daily_sql,
- team=team,
query_type="engineering_analytics.workflow_health_daily",
placeholders=placeholders,
)
diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.py
new file mode 100644
index 000000000000..4d5136f5b095
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/sources.py
@@ -0,0 +1,121 @@
+"""Resolve a team's GitHub warehouse tables at query time.
+
+A warehouse table's real name is ``ExternalDataSource.prefix + <synced endpoint table>``,
+and ``prefix`` is free text the user sets when connecting the source. The product can
+therefore never assume a fixed ``github_*`` table name — a team that connected GitHub
+with prefix ``devex_eng_analytics`` lands its data in ``devex_eng_analyticsgithub_pull_requests``.
+
+This resolver walks the team's connected GitHub source(s) to their ``pull_requests`` /
+``workflow_runs`` schemas and returns the actual ``DataWarehouseTable`` names the curated
+builders should read. Names are resolved exactly once per request (in the logic layer)
+and threaded down into the builders, so a request hits the warehouse models a single time.
+
+A team can connect GitHub more than once (e.g. one source per repository). A caller may pass
+``source_id`` to read a specific source; otherwise the oldest connected source with both
+endpoints synced is used.
+"""
+
+import re
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+from uuid import UUID
+
+from posthog.models.team import Team
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+from products.engineering_analytics.backend.facade.contracts import GitHubSourceNotConnectedError
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+if TYPE_CHECKING:
+ from posthog.rbac.user_access_control import UserAccessControl
+
+# GitHub source endpoints (``ExternalDataSchema.name``) backing the curated builders. The
+# materialized table for each is ``prefix + "github_" + endpoint``, e.g. with prefix
+# ``devex_eng_analytics`` the pull-requests table is ``devex_eng_analyticsgithub_pull_requests``.
+PULL_REQUESTS_SCHEMA = "pull_requests"
+WORKFLOW_RUNS_SCHEMA = "workflow_runs"
+
+# Resolved names are interpolated into HogQL ``FROM`` clauses. Warehouse table names are
+# always plain identifiers (the prefix is validated to ``[A-Za-z0-9_]`` at connect time and
+# the rest is the fixed ``github_<endpoint>`` suffix), so reject anything else defensively
+# rather than trust an unexpected name into SQL.
+_IDENTIFIER = re.compile(r"\A[A-Za-z_][A-Za-z0-9_]*\Z")
+
+
+@dataclass(frozen=True)
+class GitHubTables:
+ """The per-team warehouse table names the curated builders read from."""
+
+ pull_requests: str
+ workflow_runs: str
+
+
+def resolve_github_tables(
+ *, team: Team, source_id: str | None = None, user_access_control: "UserAccessControl | None" = None
+) -> GitHubTables:
+ """Resolve the team's curated GitHub table names from its warehouse models.
+
+ With ``source_id``, reads that specific connected GitHub source; otherwise picks the
+ oldest source with both endpoints synced (oldest = the team's first/established connection)
+ — deterministic when a team has more than one GitHub source (e.g. one per repository).
+ Raises ``GitHubSourceNotConnectedError`` when no matching usable source exists (the
+ presentation layer maps it to a 400, so the UI prompts to connect a source and an agent gets
+ an actionable error), or ``ValueError`` when ``source_id`` is not a UUID.
+
+ ``user_access_control`` enforces the requesting user's per-source warehouse RBAC: a source the
+ user can't access is filtered out before resolution, so a denied ``source_id`` raises (400) and
+ the default-oldest path skips it. The curated HogQL runs team-scoped with no user and HogQL does
+ not enforce per-user ACL on warehouse tables, so this is the only place that can honor it. None
+ (system/Temporal/CLI contexts with no request user) skips filtering — team scoping still holds.
+ """
+ sources = (
+ ExternalDataSource.objects.filter(team_id=team.pk, source_type=ExternalDataSourceType.GITHUB)
+ .exclude(deleted=True)
+ .order_by("created_at", "id")
+ )
+ if source_id is not None:
+ sources = sources.filter(id=_as_source_uuid(source_id))
+ if user_access_control is not None:
+ sources = user_access_control.filter_queryset_by_access_level(sources)
+ for source in sources:
+ tables = _synced_table_names(team=team, source=source)
+ pull_requests = tables.get(PULL_REQUESTS_SCHEMA)
+ workflow_runs = tables.get(WORKFLOW_RUNS_SCHEMA)
+ if pull_requests and workflow_runs:
+ return GitHubTables(pull_requests=pull_requests, workflow_runs=workflow_runs)
+ if source_id is not None:
+ raise GitHubSourceNotConnectedError(_NO_SELECTED_SOURCE)
+ raise GitHubSourceNotConnectedError()
+
+
+# Distinct from the no-source message: the caller picked a source that isn't a usable GitHub
+# source for this team (wrong id, another team's source, or its endpoints aren't synced).
+_NO_SELECTED_SOURCE = "The selected GitHub source isn't connected or has no synced pull_requests/workflow_runs tables."
+
+
+def _as_source_uuid(source_id: str) -> UUID:
+ try:
+ return UUID(source_id)
+ except ValueError as err:
+ raise ValueError(f"source_id must be a UUID, got: {source_id!r}") from err
+
+
+def _synced_table_names(*, team: Team, source: ExternalDataSource) -> dict[str, str]:
+ """Map ``{endpoint: table name}`` for a source's actively-synced PR/CI schemas."""
+ schemas = (
+ ExternalDataSchema.objects.filter(
+ team_id=team.pk,
+ source_id=source.id,
+ should_sync=True,
+ name__in=(PULL_REQUESTS_SCHEMA, WORKFLOW_RUNS_SCHEMA),
+ )
+ .exclude(deleted=True)
+ .select_related("table")
+ )
+ resolved: dict[str, str] = {}
+ for schema in schemas:
+ table = schema.table
+ if table is not None and not table.deleted and _IDENTIFIER.match(table.name):
+ resolved[schema.name] = table.name
+ return resolved
diff --git a/products/engineering_analytics/backend/logic/views/__init__.py b/products/engineering_analytics/backend/logic/views/__init__.py
index ba535bf7bfd3..a043b7b43fbd 100644
--- a/products/engineering_analytics/backend/logic/views/__init__.py
+++ b/products/engineering_analytics/backend/logic/views/__init__.py
@@ -1,8 +1,9 @@
"""Curated query builders over the GitHub warehouse snapshots.
-``pull_requests`` and ``workflow_runs`` each expose a ``build_query()`` returning
-the curated ``SELECT`` over the raw ``github_*`` table. All PR/CI domain rules
-(bot detection, repo identity, label extraction, honest metric naming) are
-defined here exactly once. Query modules embed these as subqueries via
-``logic.queries._curated`` — nothing is registered as a global HogQL view.
+``pull_requests`` and ``workflow_runs`` each expose a ``build_query(table_name)``
+returning the curated ``SELECT`` over the raw GitHub table whose per-team name is
+resolved by ``logic.sources`` and passed in. All PR/CI domain rules (bot detection,
+repo identity, label extraction, honest metric naming) are defined here exactly once.
+Query modules embed these as subqueries via ``logic.queries._curated`` — nothing is
+registered as a global HogQL view.
"""
diff --git a/products/engineering_analytics/backend/logic/views/pull_requests.py b/products/engineering_analytics/backend/logic/views/pull_requests.py
index 5582d8c7599e..009d64e6ec02 100644
--- a/products/engineering_analytics/backend/logic/views/pull_requests.py
+++ b/products/engineering_analytics/backend/logic/views/pull_requests.py
@@ -1,16 +1,16 @@
-"""Curated ``github_pull_requests`` query builder.
+"""Curated pull-requests query builder.
-Maps the raw ``github_pull_requests`` warehouse snapshot (GitHub's PR JSON,
-landed verbatim) into honest, query-able columns. This is the ONLY place PR
-domain rules live — bot detection, repo identity from ``base.repo.full_name``,
-label extraction, the canonical PR state, and the coarse open-to-merge duration.
-Every query module embeds this ``SELECT`` as a subquery (see ``_curated``) rather
-than re-deriving the columns from JSON; nothing registers it as a global HogQL
-view, so the product stays off the per-query catalog hot path.
+Maps the raw GitHub pull-requests warehouse snapshot (GitHub's PR JSON, landed
+verbatim) into honest, query-able columns. This is the ONLY place PR domain rules
+live — bot detection, repo identity from ``base.repo.full_name``, label extraction,
+the canonical PR state, and the coarse open-to-merge duration. The source table name
+is resolved per-team and passed in (see ``logic.sources``); it is never hardcoded,
+because a warehouse table's name is ``prefix + "github_pull_requests"`` and the prefix
+is user-chosen. Every query module embeds this ``SELECT`` as a subquery (see
+``_curated``) rather than re-deriving the columns from JSON; nothing registers it as a
+global HogQL view, so the product stays off the per-query catalog hot path.
"""
-SOURCE_TABLE = "github_pull_requests"
-
# Bots whose handle does not carry GitHub's automatic ``[bot]`` suffix. Kept
# deliberately small; per-team configuration is deferred.
KNOWN_BOT_HANDLES: frozenset[str] = frozenset(
@@ -28,7 +28,7 @@ def _bot_handle_in_list() -> str:
return ", ".join(f"'{handle}'" for handle in sorted(KNOWN_BOT_HANDLES))
-def build_query() -> str:
+def build_query(table_name: str) -> str:
handle = "JSONExtractString(user, 'login')"
repo_full_name = "JSONExtractString(base, 'repo', 'full_name')"
return f"""
@@ -49,5 +49,5 @@ def build_query() -> str:
closed_at,
JSONExtractString(head, 'sha') AS head_sha,
if(merged_at IS NOT NULL, dateDiff('second', created_at, merged_at), NULL) AS open_to_merge_seconds
- FROM {SOURCE_TABLE}
+ FROM {table_name}
"""
diff --git a/products/engineering_analytics/backend/logic/views/workflow_runs.py b/products/engineering_analytics/backend/logic/views/workflow_runs.py
index a98ba945466f..0f5dec3858d0 100644
--- a/products/engineering_analytics/backend/logic/views/workflow_runs.py
+++ b/products/engineering_analytics/backend/logic/views/workflow_runs.py
@@ -1,19 +1,19 @@
-"""Curated ``github_workflow_runs`` query builder.
+"""Curated workflow-runs query builder.
-Maps the raw ``github_workflow_runs`` warehouse snapshot into honest CI columns:
+Maps the raw GitHub workflow-runs warehouse snapshot into honest CI columns:
``status`` and ``conclusion`` are passed through unchanged (a conclusion can be
stale until the ``workflow_run`` webhook settles it — see SPEC §9), and
``duration_seconds`` is only computed for completed runs. ``head_sha`` is the
-canonical join key back to the pull-requests builder for a PR's CI status.
+canonical join key back to the pull-requests builder for a PR's CI status. The
+source table name is resolved per-team and passed in (see ``logic.sources``); it is
+never hardcoded, because a warehouse table's name carries the user-chosen source prefix.
Every query module embeds this ``SELECT`` as a subquery (see ``_curated``);
nothing registers it as a global HogQL view.
"""
-SOURCE_TABLE = "github_workflow_runs"
-
-def build_query() -> str:
+def build_query(table_name: str) -> str:
repo_full_name = "JSONExtractString(repository, 'full_name')"
return f"""
SELECT
@@ -28,5 +28,5 @@ def build_query() -> str:
if(status = 'completed', dateDiff('second', run_started_at, updated_at), NULL) AS duration_seconds,
arrayElement(splitByChar('/', {repo_full_name}), 1) AS repo_owner,
arrayElement(splitByChar('/', {repo_full_name}), 2) AS repo_name
- FROM {SOURCE_TABLE}
+ FROM {table_name}
"""
diff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
index 4a7ace88c076..ebb18a8db5eb 100644
--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
@@ -2,19 +2,25 @@
Loads ``products/engineering_analytics/fixtures/github_pull_requests.json`` and
``github_workflow_runs.json`` (a real PostHog/posthog snapshot captured with
-``fixtures/fetch.py``) into the team's data warehouse as the
-``github_pull_requests`` and ``github_workflow_runs`` tables the product queries.
+``fixtures/fetch.py``) into the team's data warehouse behind a connected GitHub
+source, exactly as a real sync would: a GitHub ``ExternalDataSource`` with a
+``--prefix``, plus ``pull_requests`` / ``workflow_runs`` ``ExternalDataSchema`` rows
+pointing at the materialized ``<prefix>github_pull_requests`` /
+``<prefix>github_workflow_runs`` tables. The product resolves those names per team
+(``logic.sources``), so seeding under a non-default prefix exercises the resolver
+rather than the old hardcoded ``github_*`` names.
Timestamps are rebased so the newest fixture row lands at "now" — the queries
window on server-side now(), so an unshifted old snapshot would render empty.
Pass --keep-dates for the faithful snapshot instead.
-Re-running replaces previously seeded tables, but tables owned by a connected
-GitHub warehouse source are never touched. Local/dev only: requires the dev
-object storage and ClickHouse from the hogli stack.
+Re-running replaces this seed source's tables, but a table owned by a different
+(real) connected source is never touched. Local/dev only: requires the dev object
+storage and ClickHouse from the hogli stack.
Usage:
python manage.py seed_engineering_analytics --team-id 1
+ python manage.py seed_engineering_analytics --team-id 1 --prefix devex_eng_analytics
python manage.py seed_engineering_analytics --team-id 1 --keep-dates
"""
@@ -34,18 +40,29 @@ from posthog.models import Team
from posthog.models.scoping import team_scope
from posthog.storage import object_storage
+from products.data_warehouse.backend.types import ExternalDataSourceType
+from products.engineering_analytics.backend.logic.sources import PULL_REQUESTS_SCHEMA, WORKFLOW_RUNS_SCHEMA
from products.engineering_analytics.backend.logic.views.source_schema import (
PULL_REQUESTS_COLUMNS,
WORKFLOW_RUNS_COLUMNS,
)
from products.warehouse_sources.backend.models.credential import get_or_create_datawarehouse_credential
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
+from products.warehouse_sources.backend.models.util import validate_source_prefix
FIXTURE_DIR = Path(__file__).parents[3] / "fixtures"
PR_DATE_FIELDS = ("created_at", "updated_at", "merged_at", "closed_at")
RUN_DATE_FIELDS = ("created_at", "run_started_at", "updated_at")
+# Marks the GitHub source this command owns, so re-seeding never clobbers a real source.
+SEED_SOURCE_ID = "engineering_analytics_seed"
+# Default prefix is non-trivial on purpose: it proves the product resolves the real
+# per-team table name rather than assuming the bare ``github_*`` names.
+DEFAULT_PREFIX = "eng_analytics_seed"
+
def _flatten_pr(pr: dict[str, Any]) -> dict[str, Any]:
return {
@@ -77,7 +94,7 @@ def _warehouse_endpoint() -> str:
class Command(BaseCommand):
- help = "Seed the engineering analytics github_pull_requests/github_workflow_runs warehouse tables from the fixture."
+ help = "Seed the engineering analytics warehouse tables behind a connected GitHub source from the fixture."
def add_arguments(self, parser: Any) -> None:
parser.add_argument("--team-id", type=int, required=True, help="Team to seed the warehouse tables into.")
@@ -89,12 +106,22 @@ class Command(BaseCommand):
action="store_true",
help="Load the snapshot's original timestamps instead of rebasing them to now.",
)
+ parser.add_argument(
+ "--prefix",
+ type=str,
+ default=DEFAULT_PREFIX,
+ help="Source prefix for the seeded GitHub tables (table name is <prefix>github_<endpoint>).",
+ )
def handle(self, *args: Any, **options: Any) -> None:
if not settings.DEBUG:
raise CommandError("This command can only be run with DEBUG=True (local/dev only).")
if not settings.OBJECT_STORAGE_ENABLED or not settings.OBJECT_STORAGE_ACCESS_KEY_ID:
raise CommandError("Object storage is not configured — start the dev stack first (hogli start).")
+ prefix = options["prefix"]
+ prefix_valid, prefix_error = validate_source_prefix(prefix)
+ if not prefix_valid:
+ raise CommandError(f"Invalid --prefix {prefix!r}: {prefix_error}")
try:
team = Team.objects.get(pk=options["team_id"])
except Team.DoesNotExist:
@@ -116,11 +143,19 @@ class Command(BaseCommand):
access_key=settings.OBJECT_STORAGE_ACCESS_KEY_ID,
access_secret=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,
)
- self._upsert_table(team, credential, "github_pull_requests", PULL_REQUESTS_COLUMNS, map(_flatten_pr, prs))
- self._upsert_table(team, credential, "github_workflow_runs", WORKFLOW_RUNS_COLUMNS, map(_flatten_run, runs))
+ source = self._get_or_create_seed_source(team, prefix)
+ self._upsert_schema_table(
+ team, source, credential, prefix, PULL_REQUESTS_SCHEMA, PULL_REQUESTS_COLUMNS, map(_flatten_pr, prs)
+ )
+ self._upsert_schema_table(
+ team, source, credential, prefix, WORKFLOW_RUNS_SCHEMA, WORKFLOW_RUNS_COLUMNS, map(_flatten_run, runs)
+ )
self.stdout.write(
- self.style.SUCCESS(f"Seeded {len(prs)} pull requests and {len(runs)} workflow runs into team {team.pk}.")
+ self.style.SUCCESS(
+ f"Seeded {len(prs)} pull requests and {len(runs)} workflow runs into team {team.pk} "
+ f"under GitHub source prefix '{prefix}'."
+ )
)
def _load_fixture(self, fixture_dir: Path, filename: str) -> list[dict[str, Any]]:
@@ -148,48 +183,83 @@ class Command(BaseCommand):
shifted[field] = moved.strftime("%Y-%m-%d %H:%M:%S")
return shifted
- def _upsert_table(
+ def _get_or_create_seed_source(self, team: Team, prefix: str) -> ExternalDataSource:
+ source = ExternalDataSource.objects.filter(
+ team=team, source_id=SEED_SOURCE_ID, source_type=ExternalDataSourceType.GITHUB
+ ).first()
+ if source is None:
+ return ExternalDataSource.objects.create(
+ team=team,
+ source_id=SEED_SOURCE_ID,
+ connection_id=SEED_SOURCE_ID,
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=ExternalDataSourceType.GITHUB,
+ prefix=prefix,
+ )
+ if source.prefix != prefix:
+ source.prefix = prefix
+ source.save(update_fields=["prefix", "updated_at"])
+ return source
+
+ def _upsert_schema_table(
self,
team: Team,
+ source: ExternalDataSource,
credential: Any,
- name: str,
+ prefix: str,
+ schema_name: str,
columns: dict[str, dict[str, str]],
rows: Any,
) -> None:
records = list(rows)
+ # The materialized table name is exactly what a real sync produces: <prefix>github_<endpoint>.
+ table_name = f"{prefix}github_{schema_name}"
headers = list(columns.keys())
output = StringIO()
writer = csv.writer(output)
writer.writerow(headers)
writer.writerows([record[header] for header in headers] for record in records)
- s3_prefix = f"data-warehouse/engineering_analytics_{name}/team_{team.pk}"
- object_storage.write(f"{s3_prefix}/{name}.csv", output.getvalue())
+ s3_prefix = f"data-warehouse/engineering_analytics_{table_name}/team_{team.pk}"
+ object_storage.write(f"{s3_prefix}/{table_name}.csv", output.getvalue())
url_pattern = f"{_warehouse_endpoint()}/{settings.OBJECT_STORAGE_BUCKET}/{s3_prefix}/*.csv"
- existing = DataWarehouseTable.objects.filter(team=team, name=name).first()
- if existing is not None and existing.external_data_source is not None:
+ existing = DataWarehouseTable.objects.filter(team=team, name=table_name).first()
+ if existing is not None and existing.external_data_source_id not in (None, source.id):
raise CommandError(
- f"Table {name} belongs to a connected warehouse source — refusing to overwrite it. "
- "Delete the source (or use another team) to seed fixture data."
+ f"Table {table_name} belongs to another warehouse source — refusing to overwrite it. "
+ "Use a different --prefix (or another team) to seed fixture data."
)
if existing is not None:
existing.format = DataWarehouseTable.TableFormat.CSVWithNames
existing.url_pattern = url_pattern
existing.credential = credential
+ existing.external_data_source = source
existing.columns = columns
existing.options = {**(existing.options or {}), "csv_allow_double_quotes": True}
existing.deleted = False
existing.deleted_at = None
existing.save()
+ table = existing
else:
- DataWarehouseTable.objects.create(
+ table = DataWarehouseTable.objects.create(
team=team,
- name=name,
+ name=table_name,
format=DataWarehouseTable.TableFormat.CSVWithNames,
url_pattern=url_pattern,
credential=credential,
+ external_data_source=source,
columns=columns,
options={"csv_allow_double_quotes": True},
)
- self.stdout.write(f"Created warehouse table {name} ({len(records)} rows).")
+
+ schema = ExternalDataSchema.objects.filter(team=team, source=source, name=schema_name).first()
+ if schema is None:
+ ExternalDataSchema.objects.create(team=team, source=source, name=schema_name, table=table, should_sync=True)
+ elif schema.table_id != table.id or not schema.should_sync or schema.deleted:
+ schema.table = table
+ schema.should_sync = True
+ schema.deleted = False
+ schema.deleted_at = None
+ schema.save()
+ self.stdout.write(f"Seeded warehouse table {table_name} ({len(records)} rows) as schema '{schema_name}'.")
diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.py
index 39b146aa5038..996faa0d9d90 100644
--- a/products/engineering_analytics/backend/presentation/views.py
+++ b/products/engineering_analytics/backend/presentation/views.py
@@ -55,10 +55,18 @@ _DATE_TO = OpenApiParameter(
description="Window end: relative or ISO8601. Defaults to now.",
)
+_SOURCE_ID = OpenApiParameter(
+ name="source_id",
+ type=OpenApiTypes.UUID,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub "
+ "source when the team has more than one.",
+)
-def _invalid_date(exc: ValueError | None = None) -> Response:
- detail = str(exc) if exc is not None and str(exc) else "Invalid date_from or date_to"
- return Response({"detail": detail}, status=status.HTTP_400_BAD_REQUEST)
+
+def _bad_request(exc: ValueError, *, fallback: str) -> Response:
+ return Response({"detail": str(exc) or fallback}, status=status.HTTP_400_BAD_REQUEST)
@extend_schema(tags=[ENGINEERING_ANALYTICS_TAG])
@@ -77,7 +85,11 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
@extend_schema(
operation_id="engineering_analytics_ci_cards",
- responses={200: CICardSummarySerializer},
+ parameters=[_SOURCE_ID],
+ responses={
+ 200: CICardSummarySerializer,
+ 400: OpenApiResponse(description="Invalid source_id."),
+ },
description=(
"Headline counts for the open-PR backlog: open PRs, distinct repos, stuck PRs (open, non-draft, "
"non-bot, older than 7 days), and PRs with failing CI. The failing-CI count rests on the head-SHA "
@@ -86,15 +98,22 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
)
@action(detail=False, methods=["get"], pagination_class=None)
def ci_cards(self, request: Request, **kwargs) -> Response:
- result = api.get_ci_cards(team=self.team)
+ try:
+ result = api.get_ci_cards(
+ team=self.team,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid source_id")
return Response(CICardSummarySerializer(instance=result).data)
@extend_schema(
operation_id="engineering_analytics_pull_requests",
- parameters=[_DATE_FROM],
+ parameters=[_DATE_FROM, _SOURCE_ID],
responses={
200: PullRequestListSerializer,
- 400: OpenApiResponse(description="Invalid date_from."),
+ 400: OpenApiResponse(description="Invalid date_from or source_id."),
},
description=(
"Open pull requests plus any merged or closed since date_from (default -30d), newest first, each with "
@@ -106,17 +125,24 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
@action(detail=False, methods=["get"], pagination_class=None)
def pull_requests(self, request: Request, **kwargs) -> Response:
try:
- result = api.list_pull_requests(team=self.team, date_from=request.query_params.get("date_from") or None)
- except ValueError:
- return _invalid_date()
+ result = api.list_pull_requests(
+ team=self.team,
+ date_from=request.query_params.get("date_from") or None,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid date_from or source_id")
return Response(PullRequestListSerializer(instance=result).data)
@extend_schema(
operation_id="engineering_analytics_workflow_health",
- parameters=[_DATE_FROM, _DATE_TO],
+ parameters=[_DATE_FROM, _DATE_TO, _SOURCE_ID],
responses={
200: WorkflowHealthItemSerializer(many=True),
- 400: OpenApiResponse(description="Invalid date_from or date_to, or a window longer than 366 days."),
+ 400: OpenApiResponse(
+ description="Invalid date_from, date_to, or source_id, or a window longer than 366 days."
+ ),
},
description=(
"Per-workflow CI health over a window (default last 30 days, maximum 366 days): run count, success "
@@ -132,9 +158,11 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
team=self.team,
date_from=request.query_params.get("date_from") or None,
date_to=request.query_params.get("date_to") or None,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
)
except ValueError as exc:
- return _invalid_date(exc)
+ return _bad_request(exc, fallback="Invalid date_from, date_to, or source_id")
return Response(WorkflowHealthItemSerializer(instance=result, many=True).data)
@extend_schema(
@@ -148,10 +176,11 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
description="Pull request number to inspect.",
),
_REPO,
+ _SOURCE_ID,
],
responses={
200: PRLifecycleSerializer,
- 400: OpenApiResponse(description="Missing or non-integer pr_number."),
+ 400: OpenApiResponse(description="Missing or non-integer pr_number, or invalid repo or source_id."),
404: OpenApiResponse(description="No pull request with that number in the warehouse."),
},
description=(
@@ -175,9 +204,11 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
team=self.team,
pr_number=pr_number,
repo=request.query_params.get("repo") or None,
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
)
- except ValueError as err:
- return Response({"detail": str(err)}, status=status.HTTP_400_BAD_REQUEST)
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid repo or source_id")
if result is None:
return Response({"detail": "Pull request not found"}, status=status.HTTP_404_NOT_FOUND)
return Response(PRLifecycleSerializer(instance=result).data)
diff --git a/products/engineering_analytics/backend/tests/test_access_control.py b/products/engineering_analytics/backend/tests/test_access_control.py
new file mode 100644
index 000000000000..b61ffee03ec8
--- /dev/null
+++ b/products/engineering_analytics/backend/tests/test_access_control.py
@@ -0,0 +1,80 @@
+"""Per-user warehouse RBAC on the engineering_analytics read endpoints.
+
+The curated queries run via execute_hogql_query(team=...) with no request user, and HogQL does
+not enforce per-user ACL on DataWarehouseTables. So the GitHub-source resolver is the only place
+that can honor a user's per-source warehouse access. These tests assert a non-admin user denied a
+specific GitHub source cannot read its PR/CI data through the endpoint -- neither by naming it via
+source_id nor by it being the default-oldest source -- while an allowed user still can.
+
+The curated HogQL run is stubbed to empty results so the test isolates the resolver's
+access-control decision: a resolved source yields 200, a blocked source raises
+GitHubSourceNotConnectedError -> 400. Whether the resolver lets a denied source through is exactly
+the bug under test, independent of object-storage availability for the real warehouse read.
+"""
+
+from types import SimpleNamespace
+
+import pytest
+from unittest import mock
+
+from rest_framework import status
+
+from products.data_warehouse.backend.api.test._access_control_base import WarehouseAccessControlTestMixin
+from products.engineering_analytics.backend.tests.test_views import connect_github_source_without_data
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+# Every curated query runs HogQL through this method; stub it to empty so a resolved source
+# returns 200 with no rows, leaving the resolver's access-control decision as the only variable.
+_RUN_QUERY = "products.engineering_analytics.backend.logic.queries._curated.CuratedGitHubSource.run"
+
+
+class TestEngineeringAnalyticsAccessControl(WarehouseAccessControlTestMixin):
+ """A team with two connected GitHub sources, A (oldest) and B. ``no_access_user`` is denied
+ object access to B; ``editor_user`` keeps default access."""
+
+ resource = "external_data_source"
+
+ def setUp(self) -> None:
+ super().setUp()
+ # Two usable GitHub sources (both endpoints synced over ORM-only tables, no object storage).
+ # A is created first, so the default-oldest path selects A.
+ connect_github_source_without_data(self.team, prefix="sourcea")
+ connect_github_source_without_data(self.team, prefix="sourceb")
+ self.source_a, self.source_b = ExternalDataSource.objects.order_by("created_at", "id")
+ # created_by is None on both seed sources, so no creator bypass of the deny.
+ self._create_access_control(self.no_access_user, resource_id=str(self.source_b.id), access_level="none")
+
+ def _url(self, action: str) -> str:
+ return f"/api/projects/{self.team.id}/engineering_analytics/{action}/"
+
+ def test_denied_user_cannot_read_source_b_via_source_id(self) -> None:
+ # The resolver must filter B out of the denied user's queryset, so naming B explicitly
+ # resolves to nothing and surfaces as GitHubSourceNotConnectedError -> 400 (not B's data).
+ self.client.force_login(self.no_access_user)
+ with mock.patch(_RUN_QUERY, return_value=SimpleNamespace(results=[])):
+ response = self.client.get(self._url("pull_requests"), {"source_id": str(self.source_b.id)})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "GitHub" in response.json()["detail"]
+
+ def test_denied_user_default_path_never_selects_source_b(self) -> None:
+ # Make B the only otherwise-usable source by soft-deleting A, then hit the default
+ # (no source_id) path. B is denied, so resolution finds nothing -> 400, not B's data.
+ ExternalDataSource.objects.filter(pk=self.source_a.pk).update(deleted=True)
+
+ self.client.force_login(self.no_access_user)
+ with mock.patch(_RUN_QUERY, return_value=SimpleNamespace(results=[])):
+ response = self.client.get(self._url("pull_requests"))
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
+ def test_allowed_user_can_read_source_b_via_source_id(self) -> None:
+ # Control: a user with default access resolves B fine, proving the fix denies B
+ # specifically rather than blocking all access.
+ self.client.force_login(self.editor_user)
+ with mock.patch(_RUN_QUERY, return_value=SimpleNamespace(results=[])):
+ response = self.client.get(self._url("pull_requests"), {"source_id": str(self.source_b.id)})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["truncated"] is False
diff --git a/products/engineering_analytics/backend/tests/test_facade.py b/products/engineering_analytics/backend/tests/test_facade.py
index 3ea7562012fe..6b001b1fbb28 100644
--- a/products/engineering_analytics/backend/tests/test_facade.py
+++ b/products/engineering_analytics/backend/tests/test_facade.py
@@ -1,39 +1,75 @@
from posthog.test.base import BaseTest
from unittest import mock
+from parameterized import parameterized
+
from products.engineering_analytics.backend.facade import api
_LOGIC = "products.engineering_analytics.backend.facade.api.logic"
+_FOR_TEAM = f"{_LOGIC}.CuratedGitHubSource.for_team"
class TestEngineeringAnalyticsFacade(BaseTest):
- def test_get_pr_lifecycle_delegates_with_defaults(self) -> None:
- with mock.patch(f"{_LOGIC}.build_pr_lifecycle", return_value=None) as build:
- assert api.get_pr_lifecycle(team=self.team, pr_number=10) is None
-
- build.assert_called_once_with(team=self.team, pr_number=10, repo=None)
-
- def test_get_pr_lifecycle_forwards_repo(self) -> None:
- with mock.patch(f"{_LOGIC}.build_pr_lifecycle", return_value=mock.sentinel.result) as build:
- result = api.get_pr_lifecycle(team=self.team, pr_number=42, repo="PostHog/posthog")
+ @parameterized.expand(
+ [
+ # Each facade function resolves the authorized handle once (for_team, given the caller's
+ # source_id + access control) and delegates the handle plus its own params to the builder.
+ (
+ "pr_lifecycle_defaults",
+ api.get_pr_lifecycle,
+ "build_pr_lifecycle",
+ {"pr_number": 10},
+ {"source_id": None, "user_access_control": None},
+ {"pr_number": 10, "repo": None},
+ ),
+ (
+ "pr_lifecycle_forwards_repo_source_and_access",
+ api.get_pr_lifecycle,
+ "build_pr_lifecycle",
+ {
+ "pr_number": 42,
+ "repo": "PostHog/posthog",
+ "source_id": "abc",
+ "user_access_control": mock.sentinel.uac,
+ },
+ {"source_id": "abc", "user_access_control": mock.sentinel.uac},
+ {"pr_number": 42, "repo": "PostHog/posthog"},
+ ),
+ (
+ "ci_cards",
+ api.get_ci_cards,
+ "build_ci_cards",
+ {"source_id": "abc"},
+ {"source_id": "abc", "user_access_control": None},
+ {},
+ ),
+ (
+ "pull_requests",
+ api.list_pull_requests,
+ "build_pull_request_list",
+ {"date_from": "-7d", "source_id": "abc"},
+ {"source_id": "abc", "user_access_control": None},
+ {"date_from": "-7d"},
+ ),
+ (
+ "workflow_health",
+ api.list_workflow_health,
+ "build_workflow_health",
+ {"date_from": "-7d", "date_to": "-1d", "source_id": "abc"},
+ {"source_id": "abc", "user_access_control": None},
+ {"date_from": "-7d", "date_to": "-1d"},
+ ),
+ ]
+ )
+ def test_resolves_authorized_handle_then_delegates(
+ self, _name, facade_fn, build_name, call_kwargs, expected_for_team, expected_build
+ ) -> None:
+ with (
+ mock.patch(_FOR_TEAM, return_value=mock.sentinel.curated) as for_team,
+ mock.patch(f"{_LOGIC}.{build_name}", return_value=mock.sentinel.result) as build,
+ ):
+ result = facade_fn(team=self.team, **call_kwargs)
assert result is mock.sentinel.result
- build.assert_called_once_with(team=self.team, pr_number=42, repo="PostHog/posthog")
-
- def test_get_ci_cards_delegates(self) -> None:
- with mock.patch(f"{_LOGIC}.build_ci_cards", return_value=mock.sentinel.result) as build:
- assert api.get_ci_cards(team=self.team) is mock.sentinel.result
-
- build.assert_called_once_with(team=self.team)
-
- def test_list_pull_requests_forwards_date_from(self) -> None:
- with mock.patch(f"{_LOGIC}.build_pull_request_list", return_value=[]) as build:
- api.list_pull_requests(team=self.team, date_from="-7d")
-
- build.assert_called_once_with(team=self.team, date_from="-7d")
-
- def test_list_workflow_health_forwards_window(self) -> None:
- with mock.patch(f"{_LOGIC}.build_workflow_health", return_value=[]) as build:
- api.list_workflow_health(team=self.team, date_from="-7d", date_to="-1d")
-
- build.assert_called_once_with(team=self.team, date_from="-7d", date_to="-1d")
+ for_team.assert_called_once_with(self.team, **expected_for_team)
+ build.assert_called_once_with(curated=mock.sentinel.curated, **expected_build)
diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.py
index 916ab3facb90..ba68f35b973e 100644
--- a/products/engineering_analytics/backend/tests/test_logic.py
+++ b/products/engineering_analytics/backend/tests/test_logic.py
@@ -14,9 +14,10 @@ from django.utils import timezone
import pandas as pd
from parameterized import parameterized
-from posthog.hogql.errors import QueryError
+from posthog.models.team import Team
from products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csv
+from products.data_warehouse.backend.types import ExternalDataSourceType
from products.engineering_analytics.backend.facade import api
from products.engineering_analytics.backend.facade.contracts import (
GitHubSourceNotConnectedError,
@@ -24,22 +25,31 @@ from products.engineering_analytics.backend.facade.contracts import (
PRLifecycleEventKind,
PRState,
)
-from products.engineering_analytics.backend.logic import (
- build_ci_cards,
- build_pr_lifecycle,
- build_pull_request_list,
- build_workflow_health,
+from products.engineering_analytics.backend.logic import build_workflow_health
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.sources import (
+ PULL_REQUESTS_SCHEMA,
+ WORKFLOW_RUNS_SCHEMA,
+ GitHubTables,
+ resolve_github_tables,
)
-from products.engineering_analytics.backend.logic.queries import _curated
from products.engineering_analytics.backend.tests.test_views import (
_PULL_REQUESTS_COLUMNS,
_WORKFLOW_RUNS_COLUMNS,
+ GITHUB_SOURCE_PREFIX,
_pr_row,
_run_row,
+ connect_github_source_without_data,
+ create_github_source,
+ create_warehouse_table_row,
+ link_schema,
)
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
-# All query modules run through this helper; patch it to test row mapping without a warehouse.
-_RUN_QUERY = "products.engineering_analytics.backend.logic.queries._curated.run_query"
+# Every query module runs HogQL through this method; patch it to test row mapping without a
+# warehouse. Patching the unbound method means the mock is called without `self`, so a plain
+# return_value / side_effect works as before.
+_RUN_QUERY = "products.engineering_analytics.backend.logic.queries._curated.CuratedGitHubSource.run"
_PR_LIST = "products.engineering_analytics.backend.logic.queries.pull_request_list"
TEST_BUCKET = "test_storage_bucket-posthog.products.engineering_analytics.logic"
@@ -87,38 +97,54 @@ def _header(
class _WarehouseMixin(ClickhouseTestMixin, BaseTest):
- """Creates warehouse tables from in-memory rows; skips when object storage is
- unreachable so the suite still runs without the dev stack."""
-
- def _create_table(self, name: str, columns: dict, rows: list[dict[str, Any]]) -> None:
+ """Seeds warehouse tables behind a connected GitHub source with a non-default prefix,
+ so the full resolve -> build -> query path runs end to end against `myprefixgithub_*`
+ tables. Skips when object storage is unreachable so the suite still runs without the
+ dev stack."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self._github_source: ExternalDataSource | None = None
+
+ def _create_table(self, base_name: str, columns: dict, rows: list[dict[str, Any]]) -> None:
+ if self._github_source is None:
+ self._github_source = create_github_source(self.team)
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(
+ table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(
csv_path=Path(tmp.name),
- table_name=name,
+ table_name=base_name,
table_columns=columns,
test_bucket=TEST_BUCKET,
team=self.team,
- source_prefix="",
+ source=self._github_source,
+ source_prefix=GITHUB_SOURCE_PREFIX,
)
except PermissionError as err:
self.skipTest(f"object storage unavailable: {err}")
self.addCleanup(cleanup)
+ # base_name is "github_<endpoint>"; the synced schema/endpoint is its suffix.
+ link_schema(self.team, self._github_source, name=base_name.removeprefix("github_"), table=table)
class TestPRLifecycleMapping(BaseTest):
"""HogQL parsing (parse_select runs for real) plus row mapping and event
- assembly, without touching object storage."""
+ assembly, without touching object storage. The query helper is mocked, so a GitHub
+ source is connected (ORM only) just to satisfy the resolver."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ connect_github_source_without_data(self.team)
def test_assembles_ordered_events_and_marks_partial(self) -> None:
header = _header("merged", merged_at=_dt("2026-01-12T15:00:00"))
runs = [(2001, "CI", "completed", "success", _dt("2026-01-11T09:00:00"), _dt("2026-01-11T12:00:00"))]
with mock.patch(_RUN_QUERY, side_effect=[_resp([header]), _resp(runs)]):
- lifecycle = build_pr_lifecycle(team=self.team, pr_number=10, repo="PostHog/posthog")
+ lifecycle = api.get_pr_lifecycle(team=self.team, pr_number=10, repo="PostHog/posthog")
assert lifecycle is not None
assert lifecycle.metric_quality == MetricQuality.PARTIAL
@@ -136,20 +162,20 @@ class TestPRLifecycleMapping(BaseTest):
def test_returns_none_when_not_found(self) -> None:
with mock.patch(_RUN_QUERY, return_value=_resp([])):
- assert build_pr_lifecycle(team=self.team, pr_number=999, repo=None) is None
+ assert api.get_pr_lifecycle(team=self.team, pr_number=999, repo=None) is None
@parameterized.expand(["PostHog", "PostHog/", "/posthog", "/"])
def test_malformed_repo_raises_before_querying(self, repo: str) -> None:
# A half-specified repo must fail loudly, not silently drop the filter and
# return a PR from the wrong repo. Raises in _split_repo before any query.
with self.assertRaises(ValueError):
- build_pr_lifecycle(team=self.team, pr_number=10, repo=repo)
+ api.get_pr_lifecycle(team=self.team, pr_number=10, repo=repo)
def test_passes_through_view_derived_fields(self) -> None:
# is_bot and state come from the curated query as columns; the logic layer does not re-derive them.
header = _header("closed", merged_at=None, closed_at=_dt("2026-01-12T15:00:00"), is_bot=True, head_sha="")
with mock.patch(_RUN_QUERY, return_value=_resp([header])):
- lifecycle = build_pr_lifecycle(team=self.team, pr_number=10, repo=None)
+ lifecycle = api.get_pr_lifecycle(team=self.team, pr_number=10, repo=None)
assert lifecycle is not None
assert lifecycle.pull_request.state == PRState.CLOSED
@@ -166,19 +192,24 @@ class TestPRLifecycleMapping(BaseTest):
def test_state_passthrough(self, state: str, expected: PRState) -> None:
merged_at = _dt("2026-01-12T15:00:00") if state == "merged" else None
with mock.patch(_RUN_QUERY, return_value=_resp([_header(state, merged_at=merged_at, head_sha="")])):
- lifecycle = build_pr_lifecycle(team=self.team, pr_number=10, repo=None)
+ lifecycle = api.get_pr_lifecycle(team=self.team, pr_number=10, repo=None)
assert lifecycle is not None
assert lifecycle.pull_request.state == expected
class TestEndpointMapping(BaseTest):
- """Row mapping for the aggregate endpoints (query helper mocked, no warehouse),
- plus the no-source error path."""
+ """Row mapping for the aggregate endpoints (the query method mocked, no warehouse).
+ A GitHub source is connected (ORM only) so the resolver succeeds before the mocked
+ query runs."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ connect_github_source_without_data(self.team)
def test_ci_cards_maps_counts(self) -> None:
with mock.patch(_RUN_QUERY, return_value=_resp([(5, 2, 1, 1)])):
- cards = build_ci_cards(team=self.team)
+ cards = api.get_ci_cards(team=self.team)
assert (cards.open_prs, cards.repos, cards.stuck, cards.failing_ci) == (5, 2, 1, 1)
def test_pull_request_list_maps_row(self) -> None:
@@ -202,7 +233,7 @@ class TestEndpointMapping(BaseTest):
0,
)
with mock.patch(_RUN_QUERY, return_value=_resp([row])):
- result = build_pull_request_list(team=self.team, date_from="-30d")
+ result = api.list_pull_requests(team=self.team, date_from="-30d")
assert result.truncated is False
assert len(result.items) == 1
@@ -238,7 +269,7 @@ class TestEndpointMapping(BaseTest):
0,
)
with mock.patch(f"{_PR_LIST}._LIMIT", 2), mock.patch(_RUN_QUERY, return_value=_resp([row, row, row])):
- result = build_pull_request_list(team=self.team, date_from="-30d")
+ result = api.list_pull_requests(team=self.team, date_from="-30d")
assert result.truncated is True
assert result.limit == 2
@@ -253,7 +284,7 @@ class TestEndpointMapping(BaseTest):
# Must be inside the -30d window, which is relative to now.
daily_rows = [("PostHog", "posthog", "CI", datetime.now(tz=UTC).date() - timedelta(days=1), 10, 8, 7)]
with mock.patch(_RUN_QUERY, side_effect=[_resp(rows), _resp(daily_rows)]):
- items = build_workflow_health(team=self.team, date_from="-30d", date_to=None)
+ items = api.list_workflow_health(team=self.team, date_from="-30d", date_to=None)
assert items[0].workflow_name == "CI" and items[0].success_rate == 0.9
assert items[0].repo.owner == "PostHog" and items[0].repo.name == "posthog"
@@ -267,27 +298,116 @@ class TestEndpointMapping(BaseTest):
assert items[1].p50_seconds is None and items[1].p95_seconds is None
assert items[1].last_failure_at is None
+
+class TestResolveGitHubTables(BaseTest):
+ """The per-team table resolver over the warehouse models (ORM only, no object storage).
+ No source is connected in setUp so the missing-source path can be exercised."""
+
+ def _connect(
+ self,
+ *,
+ prefix: str,
+ schemas: list[tuple[str, bool, bool]],
+ source_type: ExternalDataSourceType = ExternalDataSourceType.GITHUB,
+ team: Team | None = None,
+ ) -> ExternalDataSource:
+ # schemas: (endpoint name, should_sync, has a backing table)
+ team = team or self.team
+ source = ExternalDataSource.objects.create(
+ team=team,
+ source_id=f"src-{prefix}",
+ connection_id=f"src-{prefix}",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=source_type,
+ prefix=prefix,
+ )
+ for name, should_sync, has_table in schemas:
+ table = (
+ create_warehouse_table_row(team, name=f"{prefix}github_{name}", source=source) if has_table else None
+ )
+ link_schema(team, source, name=name, table=table, should_sync=should_sync)
+ return source
+
+ _BOTH_SYNCED = [(PULL_REQUESTS_SCHEMA, True, True), (WORKFLOW_RUNS_SCHEMA, True, True)]
+
+ def test_resolves_non_default_prefix_tables(self) -> None:
+ self._connect(prefix="myprefix", schemas=self._BOTH_SYNCED)
+ tables = resolve_github_tables(team=self.team)
+ assert tables == GitHubTables(
+ pull_requests="myprefixgithub_pull_requests", workflow_runs="myprefixgithub_workflow_runs"
+ )
+
+ def test_raises_without_a_github_source(self) -> None:
+ with self.assertRaises(GitHubSourceNotConnectedError):
+ resolve_github_tables(team=self.team)
+
+ def test_build_raises_without_a_github_source(self) -> None:
+ # The orchestrator surfaces the resolver's error so the viewset can map it to a 400.
+ with self.assertRaises(GitHubSourceNotConnectedError):
+ api.get_ci_cards(team=self.team)
+
@parameterized.expand(
[
- ("github_pull_requests", GitHubSourceNotConnectedError),
- ("github_workflow_runs", GitHubSourceNotConnectedError),
- # An unrelated missing table is a real bug, not "no GitHub source" — it must
- # surface as the original QueryError rather than masquerade as a 4xx.
- ("some_typo", QueryError),
+ # Same-named schemas on a non-GitHub source must not be mistaken for a GitHub source.
+ ("non_github_source", [(PULL_REQUESTS_SCHEMA, True, True), (WORKFLOW_RUNS_SCHEMA, True, True)], "stripe"),
+ ("endpoint_not_synced", [(PULL_REQUESTS_SCHEMA, False, True), (WORKFLOW_RUNS_SCHEMA, False, True)], "gh"),
+ ("missing_one_endpoint", [(PULL_REQUESTS_SCHEMA, True, True)], "gh"),
+ ("schema_without_table", [(PULL_REQUESTS_SCHEMA, True, False), (WORKFLOW_RUNS_SCHEMA, True, False)], "gh"),
]
)
- def test_unknown_table_only_translates_for_source_tables(self, table: str, expected: type[Exception]) -> None:
- with mock.patch(
- "products.engineering_analytics.backend.logic.queries._curated.execute_hogql_query",
- side_effect=QueryError(f"Unknown table `{table}`."),
- ):
- with self.assertRaises(expected):
- _curated.run_query("SELECT 1", team=self.team, query_type="engineering_analytics.test")
+ def test_raises_when_endpoints_unavailable(
+ self, _name: str, schemas: list[tuple[str, bool, bool]], kind: str
+ ) -> None:
+ source_type = ExternalDataSourceType.STRIPE if kind == "stripe" else ExternalDataSourceType.GITHUB
+ self._connect(prefix="myprefix", schemas=schemas, source_type=source_type)
+ with self.assertRaises(GitHubSourceNotConnectedError):
+ resolve_github_tables(team=self.team)
+
+ def test_prefers_oldest_complete_source(self) -> None:
+ # Two fully-connected GitHub sources (e.g. one per repo): the oldest wins, deterministically.
+ self._connect(prefix="older", schemas=self._BOTH_SYNCED)
+ self._connect(prefix="newer", schemas=self._BOTH_SYNCED)
+ tables = resolve_github_tables(team=self.team)
+ assert tables.pull_requests == "oldergithub_pull_requests"
+
+ def test_skips_incomplete_source_for_a_complete_one(self) -> None:
+ # The oldest source is missing an endpoint; resolution falls through to the complete one.
+ self._connect(prefix="incomplete", schemas=[(PULL_REQUESTS_SCHEMA, True, True)])
+ self._connect(prefix="complete", schemas=self._BOTH_SYNCED)
+ tables = resolve_github_tables(team=self.team)
+ assert tables == GitHubTables(
+ pull_requests="completegithub_pull_requests", workflow_runs="completegithub_workflow_runs"
+ )
+
+ def test_ignores_soft_deleted_source(self) -> None:
+ source = self._connect(prefix="myprefix", schemas=self._BOTH_SYNCED)
+ ExternalDataSource.objects.filter(pk=source.pk).update(deleted=True)
+ with self.assertRaises(GitHubSourceNotConnectedError):
+ resolve_github_tables(team=self.team)
+
+ def test_source_id_selects_a_specific_source(self) -> None:
+ self._connect(prefix="older", schemas=self._BOTH_SYNCED)
+ newer = self._connect(prefix="newer", schemas=self._BOTH_SYNCED)
+ tables = resolve_github_tables(team=self.team, source_id=str(newer.id))
+ assert tables == GitHubTables(
+ pull_requests="newergithub_pull_requests", workflow_runs="newergithub_workflow_runs"
+ )
+
+ def test_unknown_source_id_raises(self) -> None:
+ self._connect(prefix="myprefix", schemas=self._BOTH_SYNCED)
+ with self.assertRaises(GitHubSourceNotConnectedError):
+ resolve_github_tables(team=self.team, source_id="0192f000-0000-7000-8000-000000000000")
+
+ def test_malformed_source_id_raises_value_error(self) -> None:
+ with self.assertRaises(ValueError):
+ resolve_github_tables(team=self.team, source_id="not-a-uuid")
- def test_build_propagates_source_error(self) -> None:
- with mock.patch(_RUN_QUERY, side_effect=GitHubSourceNotConnectedError()):
- with self.assertRaises(GitHubSourceNotConnectedError):
- build_pull_request_list(team=self.team)
+ def test_source_id_is_scoped_to_the_team(self) -> None:
+ # Selecting another team's source id must not leak it — the team filter excludes it.
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ other_source = self._connect(prefix="other", schemas=self._BOTH_SYNCED, team=other_team)
+ with self.assertRaises(GitHubSourceNotConnectedError):
+ resolve_github_tables(team=self.team, source_id=str(other_source.id))
class TestPRLifecycleWarehouse(_WarehouseMixin, BaseTest):
@@ -311,7 +431,7 @@ class TestPRLifecycleWarehouse(_WarehouseMixin, BaseTest):
[_run_row(2001, "CI", "sha10", "completed", "success", "2026-01-11 09:00:00", "2026-01-11 12:00:00")],
)
- lifecycle = build_pr_lifecycle(team=self.team, pr_number=10, repo="PostHog/posthog")
+ lifecycle = api.get_pr_lifecycle(team=self.team, pr_number=10, repo="PostHog/posthog")
assert lifecycle is not None
assert lifecycle.pull_request.state == PRState.MERGED
@@ -329,8 +449,11 @@ class TestPRLifecycleWarehouse(_WarehouseMixin, BaseTest):
class TestWorkflowHealthWindowCap(BaseTest):
@parameterized.expand(["2000-01-01", "-500d"])
def test_rejects_windows_beyond_a_year(self, date_from: str) -> None:
+ # The window cap is build_workflow_health's own guard, reached before it reads any data; a
+ # handle with dummy table names exposes the team (for timezone) and nothing else is touched.
+ curated = CuratedGitHubSource(team=self.team, tables=GitHubTables(pull_requests="pr", workflow_runs="wr"))
with pytest.raises(ValueError, match="the maximum is 366"):
- build_workflow_health(team=self.team, date_from=date_from)
+ build_workflow_health(curated=curated, date_from=date_from)
class TestEndpointsWarehouse(_WarehouseMixin, BaseTest):
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 730b54931aa3..9cc11ec16d1e 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -7,6 +7,7 @@ from parameterized import parameterized
from rest_framework import status
from products.engineering_analytics.backend.facade import contracts
+from products.engineering_analytics.backend.tests.test_views import connect_github_source_without_data
_VIEWS = "products.engineering_analytics.backend.presentation.views.api"
@@ -65,6 +66,13 @@ def _workflow_health() -> contracts.WorkflowHealthItem:
class TestEngineeringAnalyticsAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # Source resolution precedes input validation, so the non-mocked bad-input tests below
+ # (window too large, malformed repo) need a connected source for those errors to surface
+ # rather than the no-source error. The mocked tests bypass resolution entirely.
+ connect_github_source_without_data(self.team, prefix="presentation")
+
def _url(self, action: str) -> str:
return f"/api/projects/{self.team.id}/engineering_analytics/{action}/"
@@ -82,6 +90,20 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "GitHub" in response.json()["detail"]
+ def test_ci_cards_forwards_source_id(self) -> None:
+ source_id = "0192f000-0000-7000-8000-000000000000"
+ with mock.patch(f"{_VIEWS}.get_ci_cards", return_value=_cards()) as get:
+ response = self.client.get(self._url("ci_cards"), {"source_id": source_id})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert get.call_args.kwargs["source_id"] == source_id
+
+ def test_ci_cards_400_on_bad_source_id(self) -> None:
+ with mock.patch(f"{_VIEWS}.get_ci_cards", side_effect=ValueError("source_id must be a UUID")):
+ response = self.client.get(self._url("ci_cards"), {"source_id": "nope"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
def test_pull_requests_serializes(self) -> None:
result = contracts.PullRequestList(items=[_pr_list_item()], truncated=False, limit=1000)
with mock.patch(f"{_VIEWS}.list_pull_requests", return_value=result) as listing:
diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.py
index d2ce7e74fcd0..320c0bb9f5f6 100644
--- a/products/engineering_analytics/backend/tests/test_views.py
+++ b/products/engineering_analytics/backend/tests/test_views.py
@@ -8,15 +8,83 @@ import pandas as pd
from posthog.hogql.query import execute_hogql_query
+from posthog.models.team import Team
+
from products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csv
+from products.data_warehouse.backend.types import ExternalDataSourceType
+from products.engineering_analytics.backend.logic.sources import (
+ PULL_REQUESTS_SCHEMA,
+ WORKFLOW_RUNS_SCHEMA,
+ GitHubTables,
+)
from products.engineering_analytics.backend.logic.views import pull_requests, workflow_runs
from products.engineering_analytics.backend.logic.views.source_schema import (
PULL_REQUESTS_COLUMNS as _PULL_REQUESTS_COLUMNS,
WORKFLOW_RUNS_COLUMNS as _WORKFLOW_RUNS_COLUMNS,
)
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
TEST_BUCKET = "test_storage_bucket-posthog.products.engineering_analytics.views"
+# Non-default prefix on purpose: every fixture below lands tables named
+# `myprefixgithub_*`, so the resolver and builders are proven against a name the old
+# hardcoded `github_*` constants would never have matched.
+GITHUB_SOURCE_PREFIX = "myprefix"
+
+
+def create_github_source(
+ team: Team, *, prefix: str = GITHUB_SOURCE_PREFIX, source_id: str = "gh-source"
+) -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team=team,
+ source_id=source_id,
+ connection_id=source_id,
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=ExternalDataSourceType.GITHUB,
+ prefix=prefix,
+ )
+
+
+def link_schema(
+ team: Team,
+ source: ExternalDataSource,
+ *,
+ name: str,
+ table: DataWarehouseTable | None,
+ should_sync: bool = True,
+) -> ExternalDataSchema:
+ return ExternalDataSchema.objects.create(team=team, source=source, name=name, table=table, should_sync=should_sync)
+
+
+def create_warehouse_table_row(
+ team: Team, *, name: str, source: ExternalDataSource | None = None
+) -> DataWarehouseTable:
+ # ORM-only table (no object storage); for resolver/mapping tests that mock the query.
+ return DataWarehouseTable.objects.create(
+ team=team,
+ name=name,
+ format=DataWarehouseTable.TableFormat.CSVWithNames,
+ url_pattern="",
+ external_data_source=source,
+ columns={},
+ )
+
+
+def connect_github_source_without_data(team: Team, *, prefix: str = GITHUB_SOURCE_PREFIX) -> GitHubTables:
+ """A GitHub source with pull_requests/workflow_runs schemas over empty ORM tables.
+
+ The resolver finds these without touching object storage; pair with a mocked query
+ when only resolution (not real warehouse data) matters.
+ """
+ source = create_github_source(team, prefix=prefix)
+ pr_table = create_warehouse_table_row(team, name=f"{prefix}github_pull_requests", source=source)
+ run_table = create_warehouse_table_row(team, name=f"{prefix}github_workflow_runs", source=source)
+ link_schema(team, source, name=PULL_REQUESTS_SCHEMA, table=pr_table)
+ link_schema(team, source, name=WORKFLOW_RUNS_SCHEMA, table=run_table)
+ return GitHubTables(pull_requests=pr_table.name, workflow_runs=run_table.name)
+
def _user(login: str) -> str:
return f'{{"login": "{login}", "avatar_url": "https://avatars/{login}"}}'
@@ -88,30 +156,33 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
warehouse tables. Skips when object storage is unreachable so the suite still
runs without the dev stack."""
- def _create_table(self, name: str, columns: dict, rows: list[dict[str, Any]]) -> None:
+ def _create_table(self, base_name: str, columns: dict, rows: list[dict[str, Any]]) -> str:
+ # Returns the real table name (prefixed), which the builder is then told to read —
+ # proving build_query honors the resolved name instead of a hardcoded one.
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(
+ table, _source, _credential, _df, cleanup = create_data_warehouse_table_from_csv(
csv_path=Path(tmp.name),
- table_name=name,
+ table_name=base_name,
table_columns=columns,
test_bucket=TEST_BUCKET,
team=self.team,
- source_prefix="",
+ source_prefix=GITHUB_SOURCE_PREFIX,
)
except PermissionError as err:
self.skipTest(f"object storage unavailable: {err}")
self.addCleanup(cleanup)
+ return table.name
def _select(self, sql: str) -> list[tuple]:
return execute_hogql_query(query=sql, team=self.team, query_type="engineering_analytics.test").results
def test_pull_requests_view_maps_columns(self) -> None:
- self._create_table(
+ table_name = self._create_table(
"github_pull_requests",
_PULL_REQUESTS_COLUMNS,
[
@@ -133,7 +204,7 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
rows = self._select(
"SELECT number, author_handle, is_bot, repo_owner, repo_name, labels, state, is_draft, "
"head_sha, open_to_merge_seconds "
- f"FROM ({pull_requests.build_query()}) AS pr ORDER BY number"
+ f"FROM ({pull_requests.build_query(table_name)}) AS pr ORDER BY number"
)
by_number = {row[0]: row for row in rows}
@@ -157,7 +228,7 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
assert by_number[12][9] is None
def test_workflow_runs_view_maps_columns(self) -> None:
- self._create_table(
+ table_name = self._create_table(
"github_workflow_runs",
_WORKFLOW_RUNS_COLUMNS,
[
@@ -169,7 +240,7 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
rows = self._select(
"SELECT workflow_name, status, conclusion, duration_seconds, repo_owner, repo_name "
- f"FROM ({workflow_runs.build_query()}) AS r ORDER BY id"
+ f"FROM ({workflow_runs.build_query(table_name)}) AS r ORDER BY id"
)
# completed runs carry a duration; in-progress run has null duration and null conclusion
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index cc75a5c2c025..20595785f39a 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -248,6 +248,13 @@ export interface WorkflowHealthItemApi {
last_failure_at: string | null
}
+export type EngineeringAnalyticsCiCardsParams = {
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string
+}
+
export type EngineeringAnalyticsPrLifecycleParams = {
/**
* Pull request number to inspect.
@@ -257,6 +264,10 @@ export type EngineeringAnalyticsPrLifecycleParams = {
* Optional 'owner/name' repository to disambiguate when the PR number exists in more than one connected repo.
*/
repo?: string
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string
}
export type EngineeringAnalyticsPullRequestsParams = {
@@ -264,6 +275,10 @@ export type EngineeringAnalyticsPullRequestsParams = {
* Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
*/
date_from?: string
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string
}
export type EngineeringAnalyticsWorkflowHealthParams = {
@@ -275,4 +290,8 @@ export type EngineeringAnalyticsWorkflowHealthParams = {
* Window end: relative or ISO8601. Defaults to now.
*/
date_to?: string
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string
}
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index f070d595fda1..262ff2549550 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -10,6 +10,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
CICardSummaryApi,
+ EngineeringAnalyticsCiCardsParams,
EngineeringAnalyticsPrLifecycleParams,
EngineeringAnalyticsPullRequestsParams,
EngineeringAnalyticsWorkflowHealthParams,
@@ -18,8 +19,20 @@ import type {
WorkflowHealthItemApi,
} from './api.schemas'
-export const getEngineeringAnalyticsCiCardsUrl = (projectId: string) => {
- return `/api/projects/${projectId}/engineering_analytics/ci_cards/`
+export const getEngineeringAnalyticsCiCardsUrl = (projectId: string, params?: EngineeringAnalyticsCiCardsParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/engineering_analytics/ci_cards/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/ci_cards/`
}
/**
@@ -27,9 +40,10 @@ export const getEngineeringAnalyticsCiCardsUrl = (projectId: string) => {
*/
export const engineeringAnalyticsCiCards = async (
projectId: string,
+ params?: EngineeringAnalyticsCiCardsParams,
options?: RequestInit
): Promise<CICardSummaryApi> => {
- return apiMutator<CICardSummaryApi>(getEngineeringAnalyticsCiCardsUrl(projectId), {
+ return apiMutator<CICardSummaryApi>(getEngineeringAnalyticsCiCardsUrl(projectId, params), {
...options,
method: 'GET',
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1828a5171bbc..21a78225ebe4 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -55671,6 +55671,13 @@ export namespace Schemas {
offset?: number;
};
+ export type EngineeringAnalyticsCiCardsParams = {
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string;
+ };
+
export type EngineeringAnalyticsPrLifecycleParams = {
/**
* Pull request number to inspect.
@@ -55680,6 +55687,10 @@ export namespace Schemas {
* Optional 'owner/name' repository to disambiguate when the PR number exists in more than one connected repo.
*/
repo?: string;
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string;
};
export type EngineeringAnalyticsPullRequestsParams = {
@@ -55687,6 +55698,10 @@ export namespace Schemas {
* Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
*/
date_from?: string;
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string;
};
export type EngineeringAnalyticsWorkflowHealthParams = {
@@ -55698,6 +55713,10 @@ export namespace Schemas {
* Window end: relative or ISO8601. Defaults to now.
*/
date_to?: string;
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string;
};
export type EnvironmentsListParams = {
diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.ts
index 3de473126ad8..405e097d9c99 100644
--- a/services/mcp/src/generated/engineering_analytics/api.ts
+++ b/services/mcp/src/generated/engineering_analytics/api.ts
@@ -27,6 +27,12 @@ export const EngineeringAnalyticsPrLifecycleQueryParams = /* @__PURE__ */ zod.ob
.describe(
"Optional 'owner/name' repository to disambiguate when the PR number exists in more than one connected repo."
),
+ source_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.'
+ ),
})
/**
@@ -42,6 +48,12 @@ export const EngineeringAnalyticsPullRequestsParams = /* @__PURE__ */ zod.object
export const EngineeringAnalyticsPullRequestsQueryParams = /* @__PURE__ */ zod.object({
date_from: zod.string().optional().describe("Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d."),
+ source_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.'
+ ),
})
/**
@@ -58,4 +70,10 @@ export const EngineeringAnalyticsWorkflowHealthParams = /* @__PURE__ */ zod.obje
export const EngineeringAnalyticsWorkflowHealthQueryParams = /* @__PURE__ */ zod.object({
date_from: zod.string().optional().describe("Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d."),
date_to: zod.string().optional().describe('Window end: relative or ISO8601. Defaults to now.'),
+ source_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.'
+ ),
})
diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.ts
index 3fb175840ff0..79c0adb8cdee 100644
--- a/services/mcp/src/tools/generated/engineering_analytics.ts
+++ b/services/mcp/src/tools/generated/engineering_analytics.ts
@@ -30,6 +30,7 @@ const prLifecycle = (): ToolBase<typeof PrLifecycleSchema, Schemas.PRLifecycle>
query: {
pr_number: params.pr_number,
repo: params.repo,
+ source_id: params.source_id,
},
})
return result
@@ -52,6 +53,7 @@ const pullRequests = (): ToolBase<typeof PullRequestsSchema, WithPostHogUrl<Sche
path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/pull_requests/`,
query: {
date_from: params.date_from,
+ source_id: params.source_id,
},
})
return await withPostHogUrl(context, result, '/engineering-analytics')
@@ -78,6 +80,7 @@ const workflowHealth = (): ToolBase<typeof WorkflowHealthSchema, WithPostHogUrl<
query: {
date_from: params.date_from,
date_to: params.date_to,
+ source_id: params.source_id,
},
})
return await withPostHogUrl(context, result, '/engineering-analytics/workflows')
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/pr-lifecycle.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/pr-lifecycle.json
index 1e87341f8e0a..2b50921c66a5 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/pr-lifecycle.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/pr-lifecycle.json
@@ -8,6 +8,10 @@
"repo": {
"description": "Optional 'owner/name' repository to disambiguate when the PR number exists in more than one connected repo.",
"type": "string"
+ },
+ "source_id": {
+ "description": "Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.",
+ "type": "string"
}
},
"required": ["pr_number"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/pull-requests.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/pull-requests.json
index 5e3bdc2305a9..76bd6f563859 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/pull-requests.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/pull-requests.json
@@ -4,6 +4,10 @@
"date_from": {
"description": "Recency floor for merged/closed PRs — relative ('-30d', '-8w') or ISO8601. Open PRs are always included regardless of age. Defaults to -30d.",
"type": "string"
+ },
+ "source_id": {
+ "description": "Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.",
+ "type": "string"
}
},
"type": "object"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflow-health.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflow-health.json
index 84375af3ceb2..f09cb5d85b56 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflow-health.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflow-health.json
@@ -8,6 +8,10 @@
"date_to": {
"description": "Window end — relative or ISO8601. Defaults to now.",
"type": "string"
+ },
+ "source_id": {
+ "description": "Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.",
+ "type": "string"
}
},
"type": "object"
diff --git a/tach.toml b/tach.toml
index 32ecaa07254c..4023888cba4d 100644
--- a/tach.toml
+++ b/tach.toml
@@ -862,7 +862,7 @@ from = [
[[modules]]
path = "products.engineering_analytics"
-depends_on = ["posthog", "products.warehouse_sources"]
+depends_on = ["posthog", "products.warehouse_sources", "products.data_warehouse"]
layer = "modules"
[[interfaces]]