Skip to content

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

feat(engineering-analytics): read multi-repo github warehouse sources (#71450)

Julian Bez2e7aad37b94e
diff --git a/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsx b/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsx
index 288b961660b7..8f73f1a97d3f 100644
--- a/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/IntegrationAccountSelector.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
import { FormContext } from 'kea-forms'
-import { useContext, useEffect, useMemo } from 'react'
+import { useContext, useEffect, useMemo, useRef } from 'react'
import { LemonInput, LemonInputSelect, LemonTag } from '@posthog/lemon-ui'
@@ -69,15 +69,19 @@ function IntegrationAccountSelectorInner({
// Seed the multi field's form state from the legacy single-value field (e.g. a pre-multi-repo
// GitHub source's `repository`) so an untouched edit still validates and saves the full list.
+ // Seed at most once per mount: re-seeding whenever the field is empty would instantly undo a
+ // user removing the last chip (e.g. to swap the single repo for another one).
const { fieldName, multiple } = props
+ const seededLegacyValue = useRef(false)
useEffect(() => {
- if (!multiple || normalizeMultiValue(ownValue).length > 0) {
+ if (!multiple || seededLegacyValue.current || normalizeMultiValue(ownValue).length > 0) {
return
}
const seeded = normalizeMultiValue(undefined, legacySingleValue)
if (seeded.length === 0) {
return
}
+ seededLegacyValue.current = true
const setValueAction = formLogic.actions[`set${formKey.charAt(0).toUpperCase()}${formKey.slice(1)}Value`]
setValueAction?.(['payload', fieldName], seeded)
}, [multiple, ownValue, legacySingleValue, formLogic, formKey, fieldName])
@@ -96,7 +100,6 @@ function IntegrationAccountSelectorInner({
<MultiAccountField
{...props}
integrationId={integrationIsValid && integrationId ? integrationId : undefined}
- legacySingleValue={legacySingleValue}
/>
)
}
@@ -201,8 +204,7 @@ function MultiAccountField({
fieldLabel,
placeholder,
caption,
- legacySingleValue,
-}: IntegrationAccountSelectorProps & { integrationId?: number; legacySingleValue?: unknown }): JSX.Element {
+}: IntegrationAccountSelectorProps & { integrationId?: number }): JSX.Element {
if (integrationId) {
return (
<MultiAccountFieldWithOptions
@@ -212,7 +214,6 @@ function MultiAccountField({
fieldLabel={fieldLabel}
placeholder={placeholder}
caption={caption}
- legacySingleValue={legacySingleValue}
/>
)
}
@@ -222,7 +223,6 @@ function MultiAccountField({
fieldLabel={fieldLabel}
placeholder={placeholder}
caption={caption}
- legacySingleValue={legacySingleValue}
options={[]}
/>
)
@@ -235,7 +235,6 @@ function MultiAccountFieldWithOptions({
fieldLabel,
placeholder,
caption,
- legacySingleValue,
}: {
integrationId: number
sourceType: string
@@ -243,7 +242,6 @@ function MultiAccountFieldWithOptions({
fieldLabel: string
placeholder?: string
caption?: string
- legacySingleValue?: unknown
}): JSX.Element {
const { accounts, accountsLoading, accountsError } = useValues(
integrationAccountsLogic({ id: integrationId, sourceType })
@@ -270,7 +268,6 @@ function MultiAccountFieldWithOptions({
fieldLabel={fieldLabel}
placeholder={placeholder}
caption={caption}
- legacySingleValue={legacySingleValue}
options={options}
loading={accountsLoading}
onInputChange={setSearch}
@@ -284,7 +281,6 @@ function MultiAccountFieldInner({
fieldLabel,
placeholder,
caption,
- legacySingleValue,
options,
loading,
onInputChange,
@@ -294,7 +290,6 @@ function MultiAccountFieldInner({
fieldLabel: string
placeholder?: string
caption?: string
- legacySingleValue?: unknown
options: LemonInputSelectOption[]
loading?: boolean
onInputChange?: (value: string) => void
@@ -303,7 +298,9 @@ function MultiAccountFieldInner({
return (
<LemonField name={fieldName} label={fieldLabel} help={captionHelp(caption)}>
{({ value, onChange }) => {
- const selected = normalizeMultiValue(value, legacySingleValue)
+ // The legacy single value is seeded into form state once (see IntegrationAccountSelectorInner),
+ // so render the form value as-is — falling back here would resurrect a chip the user removed.
+ const selected = normalizeMultiValue(value)
const malformed = selected.filter((entry) => !OWNER_REPO_PATTERN.test(entry))
return (
<div className="flex flex-col gap-2">
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index dcd5206ca700..b7c4de1ceaff 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -51,7 +51,7 @@ 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(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).
+- **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. A source may sync **one repo or several** (the multi-repo GitHub source names added repos' rows `owner/repo.endpoint` and keeps its original repo's rows bare); each row is grouped under its repo via the warehouse_sources facade, so resolution is per `(source, repo)` and a `source_id` + `repo` pair reads one repo's tables. The picker (`list_github_sources`) lists one entry per configured repo, each flagged `synced` when its endpoints are ready to read. 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.
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index b53a60536c6b..a68bf86bf224 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -109,9 +109,12 @@ def get_workflow_run(
team: Team,
run_id: int,
source_id: str | None = None,
+ repo: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> WorkflowRunDetail | None:
- return logic.build_workflow_run(curated=_authorized_source(team, source_id, user_access_control), run_id=run_id)
+ return logic.build_workflow_run(
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo), run_id=run_id
+ )
def list_pr_runs(
@@ -233,10 +236,11 @@ def list_author_workflow_costs(
date_from: str | None = None,
date_to: str | None = None,
source_id: str | None = None,
+ repo: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> list[WorkflowCost]:
return logic.build_author_workflow_costs(
- curated=_authorized_source(team, source_id, user_access_control),
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
author=author,
date_from=date_from,
date_to=date_to,
@@ -249,17 +253,24 @@ def list_workflow_jobs(
run_id: int,
run_attempt: int | None = None,
source_id: str | None = None,
+ repo: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> list[WorkflowJob]:
return logic.build_workflow_jobs(
- curated=_authorized_source(team, source_id, user_access_control), run_id=run_id, run_attempt=run_attempt
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
+ run_id=run_id,
+ run_attempt=run_attempt,
)
def get_ci_cards(
- *, team: Team, source_id: str | None = None, user_access_control: "UserAccessControl | None" = None
+ *,
+ team: Team,
+ source_id: str | None = None,
+ repo: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
) -> CICardSummary:
- return logic.build_ci_cards(curated=_authorized_source(team, source_id, user_access_control))
+ return logic.build_ci_cards(curated=_authorized_source(team, source_id, user_access_control, repo=repo))
def list_pull_requests(
@@ -268,10 +279,11 @@ def list_pull_requests(
date_from: str | None = None,
author: str | None = None,
source_id: str | None = None,
+ repo: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> PullRequestList:
return logic.build_pull_request_list(
- curated=_authorized_source(team, source_id, user_access_control), date_from=date_from, author=author
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo), date_from=date_from, author=author
)
@@ -283,10 +295,11 @@ def list_workflow_health(
branch: str | None = None,
run_scope: str | None = None,
source_id: str | None = None,
+ repo: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> list[WorkflowHealthItem]:
return logic.build_workflow_health(
- curated=_authorized_source(team, source_id, user_access_control),
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
date_from=date_from,
date_to=date_to,
branch=branch,
@@ -303,10 +316,11 @@ def list_flaky_tests(
min_failed_prs: int | None = None,
limit: int | None = None,
source_id: str | None = None,
+ repo: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> FlakyTestList:
return logic.build_flaky_tests(
- curated=_authorized_source(team, source_id, user_access_control),
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
date_from=date_from,
date_to=date_to,
min_rerun_passes=min_rerun_passes,
@@ -376,9 +390,10 @@ def get_broken_tests(
*,
team: Team,
source_id: str | None = None,
+ repo: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> BrokenTestsResult:
- return logic.build_broken_tests(curated=_authorized_source(team, source_id, user_access_control))
+ return logic.build_broken_tests(curated=_authorized_source(team, source_id, user_access_control, repo=repo))
def list_github_sources(*, team: Team, user_access_control: "UserAccessControl | None" = None) -> list[GitHubSource]:
@@ -414,10 +429,11 @@ def get_repo_overview(
date_to: str | None = None,
include_series: bool = True,
source_id: str | None = None,
+ repo: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> RepoOverview:
return logic.build_repo_overview(
- curated=_authorized_source(team, source_id, user_access_control),
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
date_from=date_from,
date_to=date_to,
include_series=include_series,
@@ -428,9 +444,12 @@ def get_current_branch_health(
*,
team: Team,
source_id: str | None = None,
+ repo: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> CurrentBranchHealth:
- return logic.build_current_branch_health(curated=_authorized_source(team, source_id, user_access_control))
+ return logic.build_current_branch_health(
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo)
+ )
def get_repo_run_activity(
@@ -440,10 +459,11 @@ def get_repo_run_activity(
date_to: str | None = None,
branch: str | None = None,
source_id: str | None = None,
+ repo: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> WorkflowRunActivity:
return logic.build_repo_run_activity(
- curated=_authorized_source(team, source_id, user_access_control),
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
date_from=date_from,
date_to=date_to,
branch=branch,
@@ -457,10 +477,11 @@ def list_master_failures(
date_to: str | None = None,
branch: str | None = None,
source_id: str | None = None,
+ repo: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> list[MasterFailureGroup]:
return logic.build_master_failures(
- curated=_authorized_source(team, source_id, user_access_control),
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
date_from=date_from,
date_to=date_to,
branch=branch,
@@ -472,9 +493,12 @@ def get_run_failure_logs(
team: Team,
run_id: int,
source_id: str | None = None,
+ repo: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> RunFailureLogs:
- return logic.build_run_failure_logs(curated=_authorized_source(team, source_id, user_access_control), run_id=run_id)
+ return logic.build_run_failure_logs(
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo), run_id=run_id
+ )
def list_job_aggregates(
@@ -485,10 +509,11 @@ def list_job_aggregates(
date_to: str | None = None,
branch: str | None = None,
source_id: str | None = None,
+ repo: str | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> list[WorkflowJobAggregate]:
return logic.build_job_aggregates(
- curated=_authorized_source(team, source_id, user_access_control),
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
workflow_name=workflow_name,
date_from=date_from,
date_to=date_to,
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index fde93787c9fc..c68a3d7c42af 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -163,16 +163,21 @@ class QuarantineRequestAction(StrEnum):
@dataclass(frozen=True)
class GitHubSource:
- """A connected GitHub warehouse source the team can analyze. ``id`` is what a
- caller passes back as ``source_id`` to select this source; ``repo`` and
- ``prefix`` are display labels so a picker can tell two sources apart.
+ """A selectable ``(source, repo)`` the team can analyze — one entry per repository a source is
+ configured to sync, so a source syncing several repositories appears once per repo. A caller
+ passes ``id`` back as ``source_id`` and ``repo`` back as ``repo`` to read that specific repo;
+ ``prefix`` is a display label so a picker can tell two entries of the same source apart.
"""
id: str
- # Connected repository as 'owner/name' (from the source's job inputs), or '' if unknown.
+ # Configured repository as 'owner/name' (from the source's job inputs), or '' if unknown.
repo: str
# User-chosen warehouse table-name prefix for this source, or '' when none was set.
prefix: str
+ # True when this repo has both pull_requests and workflow_runs synced (what the resolver needs to
+ # read it). The default (unscoped) page should select the first synced entry, so its label matches
+ # the repo the backend actually resolves — a still-backfilling repo listed first must not mislabel it.
+ synced: bool = False
@dataclass(frozen=True)
diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.py
index 6256274f6fd5..2295fe8915e8 100644
--- a/products/engineering_analytics/backend/logic/sources.py
+++ b/products/engineering_analytics/backend/logic/sources.py
@@ -10,15 +10,19 @@ This resolver walks the team's connected GitHub source(s) to their ``pull_reques
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, or — when a ``repo`` ('owner/name') is passed — the source whose
-``job_inputs.repository`` matches that repo, so a repo-scoped call reads the right source.
+A team reaches a repo in one of two ways, handled uniformly here: one source per repository
+(each with its own bare endpoint names), or one source syncing several repositories (the
+multi-repo GitHub source, whose added repos carry repo-qualified ``owner/repo.endpoint`` schema
+names while its original repo keeps bare names). Every schema row is grouped under its repo via
+the warehouse_sources facade, so both shapes resolve the same way. A caller may pass ``source_id``
+to read a specific source; otherwise the oldest source's repos are tried first, or — when a
+``repo`` ('owner/name') is passed — the matching repo across all sources is preferred.
"""
import re
+from collections.abc import Iterable, Iterator
from dataclasses import dataclass
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, NamedTuple
from uuid import UUID
from django.db.models import Q, QuerySet
@@ -28,6 +32,7 @@ from posthog.rbac.user_access_control import NO_ACCESS_LEVEL
from products.engineering_analytics.backend.facade.contracts import GitHubSource, GitHubSourceNotConnectedError
from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
+from products.warehouse_sources.backend.facade.sources import github_schema_repo_endpoint
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
if TYPE_CHECKING:
@@ -46,6 +51,10 @@ WORKFLOW_JOBS_SCHEMA = "workflow_jobs"
# must degrade gracefully (no membership data) exactly like workflow_jobs.
TEAM_MEMBERS_SCHEMA = "team_members"
+# The curated endpoints we resolve per repo. A source's other synced endpoints (issues, commits,
+# teams, …) are irrelevant to the CI/PR read layer and dropped during grouping.
+_CURATED_ENDPOINTS = frozenset({PULL_REQUESTS_SCHEMA, WORKFLOW_RUNS_SCHEMA, WORKFLOW_JOBS_SCHEMA, TEAM_MEMBERS_SCHEMA})
+
# 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
@@ -76,19 +85,19 @@ def resolve_github_tables(
) -> 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
+ With ``source_id``, reads that specific connected GitHub source; otherwise picks the oldest
+ source's first usable repo with both endpoints synced (oldest = the team's first/established
+ connection) — deterministic when a team has more than one source or a source syncs more than
+ one repo. Raises ``GitHubSourceNotConnectedError`` when no matching usable repo 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.
- ``repo`` ('owner/name') scopes a repo-specific call — a team with one source per repository
- otherwise always resolves the oldest, so a repo-scoped read (e.g. ``resolve_branch``) would
- search the wrong repo's tables. When ``repo`` is given (and ``source_id`` is not), sources
- whose ``job_inputs.repository`` equals it (case-insensitively) are tried first; the remaining
- sources still follow as a fallback, since the ``repository`` input can be empty and the
- per-source data may still hold the repo.
+ ``repo`` ('owner/name') scopes a repo-specific call — a team with several repos otherwise always
+ resolves the oldest, so a repo-scoped read (e.g. ``resolve_branch``, or the picker selecting a
+ specific repo of a multi-repo source) would search the wrong repo's tables. Repos whose resolved
+ identity equals it (case-insensitively) are tried first — including within a chosen ``source_id``,
+ so a ``(source_id, repo)`` pair reads that exact repo; the rest still follow as a fallback, since
+ a bare row's repo can be empty while its data holds the repo.
``user_access_control`` enforces the requesting user's per-source warehouse RBAC (applied in
``_github_sources``): a denied ``source_id`` raises (400) and the default-oldest path skips it.
@@ -99,15 +108,28 @@ def resolve_github_tables(
queryset = _github_sources(team, user_access_control)
if source_id is not None:
queryset = queryset.filter(id=_as_source_uuid(source_id))
- sources: list[ExternalDataSource] = _repo_first(queryset, repo) if repo and source_id is None else list(queryset)
- for source in sources:
- tables = _synced_table_names(team=team, source=source)
+ # Lazy by default so the common path (no `repo`) stops querying sources on the first usable repo.
+ candidates: Iterable[_RepoCandidate] = _repo_candidates(team=team, sources=queryset)
+ if repo:
+ # An explicit repo must never silently resolve a *different* named repo: the picker lists a
+ # source's repos before they finish syncing, so a not-yet-complete pick should surface the
+ # not-connected 400 rather than fall through to a sibling repo (mixing two repos' metrics).
+ # Keep exact matches; only when there is none, fall back to bare/unattributed ('' repo)
+ # rows — a legacy single-repo source's rows carry no repo, so a branch-hint read still
+ # reaches them. Once an exact match exists, bare rows are off the table too: a half-synced
+ # exact match must surface not-connected, not another source's unattributed data.
+ wanted = repo.casefold()
+ materialized = list(candidates)
+ exact = [c for c in materialized if c.repository.casefold() == wanted]
+ candidates = exact if exact else [c for c in materialized if c.repository == ""]
+ for candidate in candidates:
+ tables = candidate.tables
pull_requests = tables.get(PULL_REQUESTS_SCHEMA)
workflow_runs = tables.get(WORKFLOW_RUNS_SCHEMA)
# Both endpoints are required together, by design: every read surface (cards, PR list,
- # lifecycle) joins workflow_runs for CI status and the push / re-run rollup, so a source
+ # lifecycle) joins workflow_runs for CI status and the push / re-run rollup, so a repo
# with only pull_requests synced can't serve a complete result. The trade-off is that a
- # half-synced source makes the whole product 400 (e.g. while workflow_runs is still
+ # half-synced repo makes the whole product 400 (e.g. while workflow_runs is still
# backfilling) instead of degrading to PRs-without-CI. Relaxing this to a graceful
# PR-only mode (null CI columns) is a deliberate future change, not handled here.
if pull_requests and workflow_runs:
@@ -118,7 +140,7 @@ def resolve_github_tables(
workflow_runs=workflow_runs,
workflow_jobs=tables.get(WORKFLOW_JOBS_SCHEMA),
team_members=tables.get(TEAM_MEMBERS_SCHEMA),
- repository=_source_repository(source),
+ repository=candidate.repository,
)
if source_id is not None:
raise GitHubSourceNotConnectedError(_NO_SELECTED_SOURCE)
@@ -126,59 +148,96 @@ def resolve_github_tables(
def resolve_job_cost_source_pairs(team: Team) -> list[tuple[str, str]]:
- """``(jobs_table, runs_table)`` for every GitHub source with BOTH the jobs and runs endpoints synced.
+ """``(jobs_table, runs_table)`` for every synced repo with BOTH the jobs and runs endpoints.
Used to build the exposed per-job cost view, which unions across all of a team's qualifying
- sources. Unlike ``resolve_github_tables`` (which needs pull_requests + workflow_runs and returns
- one source), this needs workflow_jobs + workflow_runs and returns all of them — the cost view has
- no PR dependency and shouldn't collapse a team's repos to one. Userless (the view sync runs in a
- system/Temporal context); team scoping is the boundary.
+ repos. Unlike ``resolve_github_tables`` (which needs pull_requests + workflow_runs and returns
+ one repo), this needs workflow_jobs + workflow_runs and returns all of them — the cost view has
+ no PR dependency and shouldn't collapse a team's repos to one. A multi-repo source contributes
+ one pair per repo, so the view stays complete when one source syncs several repos. Userless
+ (the view sync runs in a system/Temporal context); team scoping is the boundary.
"""
pairs: list[tuple[str, str]] = []
for source in _github_sources(team):
- tables = _synced_table_names(team=team, source=source)
- runs = tables.get(WORKFLOW_RUNS_SCHEMA)
- jobs = tables.get(WORKFLOW_JOBS_SCHEMA)
- if runs and jobs:
- pairs.append((jobs, runs))
+ for tables in _synced_tables_by_repo(team=team, source=source).values():
+ runs = tables.get(WORKFLOW_RUNS_SCHEMA)
+ jobs = tables.get(WORKFLOW_JOBS_SCHEMA)
+ if runs and jobs:
+ pairs.append((jobs, runs))
return pairs
def list_github_sources(*, team: Team, user_access_control: "UserAccessControl | None" = None) -> list[GitHubSource]:
- """The team's connected GitHub sources the caller may access, as selectable refs, oldest first.
-
- Lists every non-deleted GitHub source the user can access — including ones whose endpoints aren't
- fully synced yet — so a source picker shows everything they connected; selecting an unusable one
- surfaces the same connect prompt ``resolve_github_tables`` drives. Sources the user can't access
- (``user_access_control``) are filtered out, so the picker can't enumerate them. Each ``id`` is
- what the caller passes back as ``source_id`` to read that source.
+ """The team's selectable ``(source, repo)`` refs the caller may access, oldest source first.
+
+ One entry per repository a source is configured to sync, so a multi-repo source contributes one
+ entry per repo — the picker lists the handful of repos actually wired to the team's sources, not
+ the whole GitHub App's repo catalog. Configured (not just synced) repos are listed, including a
+ source still backfilling, so a just-connected source shows up; selecting a not-yet-synced repo
+ surfaces the same connect prompt ``resolve_github_tables`` drives. A source with no configured
+ repo still yields one blank-repo entry so it never vanishes. Sources the user can't access
+ (``user_access_control``) are filtered out. Each entry's ``id`` + ``repo`` are what the caller
+ passes back as ``source_id`` + ``repo`` to read that specific repo, and ``synced`` says whether that
+ repo has both endpoints the resolver needs — so the default (unscoped) page selects the first synced
+ entry and labels it with the repo the backend actually resolves, not a still-backfilling one listed
+ first.
"""
- return [
- GitHubSource(
- id=str(source.id),
- repo=_source_repository(source),
- prefix=source.prefix or "",
- )
- for source in _github_sources(team, user_access_control)
- ]
-
-
-def _repo_first(sources: QuerySet[ExternalDataSource], repo: str) -> list[ExternalDataSource]:
- """Sources whose ``job_inputs.repository`` matches ``repo`` (case-insensitive), then the rest.
-
- Both groups keep the queryset's oldest-first order, so among equal candidates the established
- connection still wins; the non-matching tail is a fallback for sources with an empty
- ``repository`` input whose data may still hold the repo.
+ entries: list[GitHubSource] = []
+ for source in _github_sources(team, user_access_control):
+ by_repo = _synced_tables_by_repo(team=team, source=source)
+ synced_repos = {
+ repo
+ for repo, tables in by_repo.items()
+ if PULL_REQUESTS_SCHEMA in tables and WORKFLOW_RUNS_SCHEMA in tables
+ }
+ for repo in _configured_repositories(source) or [""]:
+ entries.append(
+ GitHubSource(
+ id=str(source.id),
+ repo=repo,
+ prefix=source.prefix or "",
+ synced=repo.casefold() in synced_repos,
+ )
+ )
+ return entries
+
+
+class _RepoCandidate(NamedTuple):
+ # Display repo: the source's original-case ``repository`` for its legacy/bare repo (``''`` when
+ # a bare row has no repo to attribute it to); the parsed ``owner/repo`` for a qualified repo.
+ repository: str
+ # ``{endpoint: table name}`` for this one repo's synced curated schemas.
+ tables: dict[str, str]
+
+
+def _repo_candidates(*, team: Team, sources: QuerySet[ExternalDataSource]) -> Iterator[_RepoCandidate]:
+ """Every ``(repo, tables)`` a team's GitHub sources expose, in default-resolution order.
+
+ Sources keep their oldest-first order (the established connection wins), and within a source
+ repos follow the source's configured ``repositories`` order — the legacy/bare repo has no
+ inherent priority, so whichever repo the multi-select lists first is the default; unknown
+ leftovers trail, sorted. A multi-repo source contributes one entry
+ per repo, so a repo-scoped read can reach a repo that isn't the source's legacy one. Lazy (one
+ ``ExternalDataSchema`` query per source, on demand) so the default resolve path stops at the
+ first usable repo instead of querying every source up front.
"""
- wanted = repo.casefold()
- matching: list[ExternalDataSource] = []
- others: list[ExternalDataSource] = []
for source in sources:
- if _source_repository(source).casefold() == wanted:
- matching.append(source)
- else:
- others.append(source)
- return matching + others
+ display = _source_repository(source)
+ legacy_key = display.casefold()
+ # Order strictly by the source's configured repo order, so the default (first) repo matches what
+ # the picker labels as githubSources[0]. The legacy/bare repo gets no priority here — if the
+ # `repositories` multi-select puts another repo first, that repo is the default on both sides;
+ # legacy_key is only used below to map the bare row's display name. Unknown leftovers trail.
+ configured = [repo.casefold() for repo in _configured_repositories(source)]
+
+ def order_key(repo_key: str, *, configured: list[str] = configured) -> tuple:
+ position = configured.index(repo_key) if repo_key in configured else len(configured)
+ return (position, repo_key)
+
+ by_repo = _synced_tables_by_repo(team=team, source=source)
+ for repo_key in sorted(by_repo, key=order_key):
+ repository = display if repo_key == legacy_key else repo_key
+ yield _RepoCandidate(repository=repository, tables=by_repo[repo_key])
def _github_sources(team: Team, user_access_control: "UserAccessControl | None" = None) -> QuerySet[ExternalDataSource]:
@@ -227,6 +286,34 @@ def _source_repository(source: ExternalDataSource) -> str:
return str(job_inputs.get("repository") or "").strip()
+def _configured_repositories(source: ExternalDataSource) -> list[str]:
+ """The ``owner/repo`` names a source is configured to sync, in order, original case, deduped.
+
+ Reads the multi-repo ``repositories`` list, falling back to the legacy single ``repository`` —
+ the same precedence the source-side ``effective_repositories`` parser uses, but tolerant (never
+ raises) since this only drives a display picker. Case is preserved for the label; duplicates are
+ dropped case-insensitively (GitHub full names are case-insensitive). ``job_inputs`` is an
+ ``EncryptedJSONField`` that can hold any JSON value, so a non-dict yields no repos.
+ """
+ job_inputs = source.job_inputs
+ if not isinstance(job_inputs, dict):
+ return []
+ repositories = job_inputs.get("repositories")
+ # An empty `repositories` list means "unset" — the sync-side parser falls back to the single
+ # `repository` and still syncs it, so treat it the same here or a working single-repo source
+ # would list as a blank, unsynced entry.
+ raw = repositories if isinstance(repositories, list) and repositories else [job_inputs.get("repository")]
+ seen: set[str] = set()
+ result: list[str] = []
+ for value in raw:
+ name = str(value or "").strip()
+ key = name.casefold()
+ if name and key not in seen:
+ seen.add(key)
+ result.append(name)
+ return result
+
+
def _as_source_uuid(source_id: str) -> UUID:
try:
return UUID(source_id)
@@ -234,21 +321,28 @@ def _as_source_uuid(source_id: str) -> UUID:
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."""
+def _synced_tables_by_repo(*, team: Team, source: ExternalDataSource) -> dict[str, dict[str, str]]:
+ """Map ``{repository: {endpoint: table name}}`` for a source's actively-synced curated schemas.
+
+ A source syncs one repo (legacy bare endpoint names like ``pull_requests``) or several
+ (repo-qualified names like ``owner/repo.pull_requests``, the multi-repo GitHub source). Each
+ row resolves to its ``(repository, endpoint)`` through the warehouse_sources facade — persisted
+ metadata first, qualified-name parse second, the source's legacy ``repository`` for bare rows
+ last. Repo keys are normalized (lowercased, since GitHub full names are case-insensitive); a
+ bare row with no legacy repo groups under ``''`` — the pre-multi-repo single-repo shape.
+ """
+ legacy_repo = _source_repository(source) or None
schemas = (
- ExternalDataSchema.objects.filter(
- team_id=team.pk,
- source_id=source.id,
- should_sync=True,
- name__in=(PULL_REQUESTS_SCHEMA, WORKFLOW_RUNS_SCHEMA, WORKFLOW_JOBS_SCHEMA, TEAM_MEMBERS_SCHEMA),
- )
+ ExternalDataSchema.objects.filter(team_id=team.pk, source_id=source.id, should_sync=True)
.exclude(deleted=True)
.select_related("table")
)
- resolved: dict[str, str] = {}
+ by_repo: dict[str, dict[str, str]] = {}
for schema in schemas:
+ repository, endpoint = github_schema_repo_endpoint(schema.schema_metadata, schema.name, legacy_repo)
+ if endpoint not in _CURATED_ENDPOINTS:
+ continue
table = schema.table
if table is not None and not table.deleted and _IDENTIFIER.match(table.name):
- resolved[schema.name] = table.name
- return resolved
+ by_repo.setdefault(repository or "", {})[endpoint] = table.name
+ return by_repo
diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.py
index 349901234a01..727fba17d42b 100644
--- a/products/engineering_analytics/backend/presentation/serializers.py
+++ b/products/engineering_analytics/backend/presentation/serializers.py
@@ -66,9 +66,16 @@ class GitHubSourceSerializer(DataclassSerializer):
class Meta:
dataclass = GitHubSource
extra_kwargs = {
- "id": {"help_text": "Source id — pass as `source_id` to the other endpoints to read this source."},
- "repo": {"help_text": "Connected repository as 'owner/name', or '' if unknown."},
+ "id": {"help_text": "Source id — pass back as `source_id` (with `repo`) to read this repository."},
+ "repo": {
+ "help_text": "Repository as 'owner/name' — pass back as `repo` to scope to it. One entry per "
+ "repository a source syncs; '' if unknown."
+ },
"prefix": {"help_text": "User-chosen warehouse table-name prefix for this source, or '' when none."},
+ "synced": {
+ "help_text": "Whether this repo has both pull_requests and workflow_runs synced (readable "
+ "now). Default the picker to the first synced entry so its label matches the resolved repo."
+ },
}
diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.py
index 35250f221372..7d0767e19c7d 100644
--- a/products/engineering_analytics/backend/presentation/views.py
+++ b/products/engineering_analytics/backend/presentation/views.py
@@ -119,6 +119,15 @@ _SOURCE_ID = OpenApiParameter(
"source when the team has more than one.",
)
+_REPO = OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="'owner/name' repository to scope to when the selected source syncs several repositories "
+ "(from the `sources` list). Defaults to the source's first repository.",
+)
+
def _bad_request(exc: ValueError, *, fallback: str) -> Response:
return Response({"detail": str(exc) or fallback}, status=status.HTTP_400_BAD_REQUEST)
@@ -220,10 +229,11 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
operation_id="engineering_analytics_sources",
responses={200: GitHubSourceSerializer(many=True)},
description=(
- "The team's connected GitHub data warehouse sources, oldest first. Populate a source picker "
- "from this and pass a chosen `id` back as `source_id` to the other endpoints. A team can connect "
- "GitHub more than once (e.g. one source per repository); this lists them all, including any whose "
- "tables aren't fully synced yet."
+ "The team's selectable GitHub repositories, oldest source first — one entry per repository a "
+ "source is configured to sync, so a source syncing several repositories appears once per repo. "
+ "Populate a repo picker from this and pass a chosen entry's `id` back as `source_id` and its "
+ "`repo` back as `repo` to the other endpoints. Includes repositories whose tables aren't fully "
+ "synced yet."
),
)
@action(detail=False, methods=["get"], pagination_class=None)
@@ -233,7 +243,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
@extend_schema(
operation_id="engineering_analytics_ci_cards",
- parameters=[_SOURCE_ID],
+ parameters=[_SOURCE_ID, _REPO],
responses={
200: CICardSummarySerializer,
400: OpenApiResponse(description="Invalid source_id."),
@@ -250,6 +260,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
result = api.get_ci_cards(
team=self.team,
source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
)
except ValueError as exc:
@@ -268,6 +279,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
description="Optional GitHub login to scope the list to one author's pull requests.",
),
_SOURCE_ID,
+ _REPO,
],
responses={
200: PullRequestListSerializer,
@@ -288,6 +300,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
date_from=request.query_params.get("date_from") or None,
author=request.query_params.get("author") or None,
source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
)
except ValueError as exc:
@@ -296,7 +309,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
@extend_schema(
operation_id="engineering_analytics_workflow_health",
- parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _RUN_SCOPE, _SOURCE_ID],
+ parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _RUN_SCOPE, _SOURCE_ID, _REPO],
responses={
200: WorkflowHealthItemSerializer(many=True),
400: OpenApiResponse(
@@ -322,6 +335,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
branch=request.query_params.get("branch") or None,
run_scope=request.query_params.get("run_scope") or None,
source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
)
except ValueError as exc:
@@ -593,6 +607,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
description="GitHub Actions run id to inspect.",
),
_SOURCE_ID,
+ _REPO,
],
responses={
200: WorkflowRunDetailSerializer,
@@ -611,6 +626,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
team=self.team,
run_id=_require_int_param(request, "run_id"),
source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
)
except ValueError as exc:
@@ -795,6 +811,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
_DATE_FROM,
_DATE_TO,
_SOURCE_ID,
+ _REPO,
],
responses={
200: WorkflowCostSerializer(many=True),
@@ -818,6 +835,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
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,
+ repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
)
except ValueError as exc:
@@ -843,6 +861,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
"explicit attempt to avoid mixing jobs across a re-run's attempts.",
),
_SOURCE_ID,
+ _REPO,
],
responses={
200: WorkflowJobSerializer(many=True),
@@ -862,6 +881,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
run_id=_require_int_param(request, "run_id"),
run_attempt=_optional_int_param(request, "run_attempt"),
source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
)
except ValueError as exc:
@@ -904,6 +924,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
description="Maximum number of tests to return (1-200). Defaults to 50.",
),
_SOURCE_ID,
+ _REPO,
],
responses={
200: FlakyTestListSerializer,
@@ -928,6 +949,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
min_failed_prs=_optional_int_param(request, "min_failed_prs"),
limit=_optional_int_param(request, "limit"),
source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
)
except ValueError as exc:
@@ -1117,7 +1139,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
@extend_schema(
operation_id="engineering_analytics_broken_tests",
- parameters=[_SOURCE_ID],
+ parameters=[_SOURCE_ID, _REPO],
responses={
200: BrokenTestsResultSerializer,
400: OpenApiResponse(description="Invalid source_id."),
@@ -1140,6 +1162,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
result = api.get_broken_tests(
team=self.team,
source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
)
except ValueError as exc:
@@ -1161,6 +1184,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
"headline-only consumers like the weekly digest. Defaults to true.",
),
_SOURCE_ID,
+ _REPO,
],
responses={
200: RepoOverviewSerializer,
@@ -1184,6 +1208,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
date_to=request.query_params.get("date_to") or None,
include_series=_bool_param(request, "include_series", default=True),
source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
)
except ValueError as exc:
@@ -1192,7 +1217,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
@extend_schema(
operation_id="engineering_analytics_current_branch_health",
- parameters=[_SOURCE_ID],
+ parameters=[_SOURCE_ID, _REPO],
responses={
200: CurrentBranchHealthSerializer,
400: OpenApiResponse(description="Invalid source_id."),
@@ -1209,6 +1234,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
result = api.get_current_branch_health(
team=self.team,
source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
)
except ValueError as exc:
@@ -1231,6 +1257,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
"Omit or leave blank to use the repo's detected default branch.",
),
_SOURCE_ID,
+ _REPO,
],
responses={
200: WorkflowRunActivitySerializer,
@@ -1255,6 +1282,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
date_to=request.query_params.get("date_to") or None,
branch=request.query_params.get("branch") or None,
source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
)
except ValueError as exc:
@@ -1263,7 +1291,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
@extend_schema(
operation_id="engineering_analytics_master_failures",
- parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _SOURCE_ID],
+ parameters=[_WORKFLOW_DATE_FROM, _DATE_TO, _BRANCH, _SOURCE_ID, _REPO],
responses={
200: MasterFailureGroupSerializer(many=True),
400: OpenApiResponse(description="Invalid date_from, date_to, or source_id, or a window over 366 days."),
@@ -1285,6 +1313,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
date_to=request.query_params.get("date_to") or None,
branch=request.query_params.get("branch") or None,
source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
)
except ValueError as exc:
@@ -1302,6 +1331,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
description="Workflow run id whose failure logs to fetch.",
),
_SOURCE_ID,
+ _REPO,
],
responses={
200: RunFailureLogsSerializer,
@@ -1320,6 +1350,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
team=self.team,
run_id=_require_int_param(request, "run_id"),
source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
)
except ValueError as exc:
@@ -1340,6 +1371,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
_DATE_TO,
_BRANCH,
_SOURCE_ID,
+ _REPO,
],
responses={
200: WorkflowJobAggregateSerializer(many=True),
@@ -1366,6 +1398,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
date_to=request.query_params.get("date_to") or None,
branch=request.query_params.get("branch") or None,
source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
user_access_control=self.user_access_control,
)
except ValueError as exc:
diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.py
index 93239a0bec36..b420d6625513 100644
--- a/products/engineering_analytics/backend/tests/test_logic.py
+++ b/products/engineering_analytics/backend/tests/test_logic.py
@@ -28,10 +28,12 @@ from products.engineering_analytics.backend.logic.queries._curated import Curate
from products.engineering_analytics.backend.logic.queries.pr_cost import query_cost_per_merge_series
from products.engineering_analytics.backend.logic.sources import (
PULL_REQUESTS_SCHEMA,
+ WORKFLOW_JOBS_SCHEMA,
WORKFLOW_RUNS_SCHEMA,
GitHubTables,
list_github_sources,
resolve_github_tables,
+ resolve_job_cost_source_pairs,
)
from products.engineering_analytics.backend.logic.views.source_schema import WORKFLOW_JOBS_COLUMNS
from products.engineering_analytics.backend.tests.test_views import (
@@ -45,7 +47,7 @@ from products.engineering_analytics.backend.tests.test_views import (
create_warehouse_table_row,
link_schema,
)
-from products.warehouse_sources.backend.facade.models import ExternalDataSource
+from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
from products.warehouse_sources.backend.test.utils import create_data_warehouse_table_from_csv
@@ -701,6 +703,18 @@ class TestListGitHubSources(BaseTest):
ExternalDataSource.objects.filter(pk=source.pk).update(job_inputs=["not", "a", "dict"])
assert list_github_sources(team=self.team) == [GitHubSource(id=str(source.id), repo="", prefix="weird")]
+ def test_empty_repositories_list_falls_back_to_legacy_repository(self) -> None:
+ # A legacy source with `repository` set but `repositories: []` (empty) — the sync parser treats
+ # the empty list as unset and still syncs the legacy repo, so the picker must list that repo, not
+ # a blank unknown entry.
+ source = self._source(prefix="emptylist", repository="PostHog/posthog")
+ ExternalDataSource.objects.filter(pk=source.pk).update(
+ job_inputs={"repository": "PostHog/posthog", "repositories": []}
+ )
+ assert list_github_sources(team=self.team) == [
+ GitHubSource(id=str(source.id), repo="PostHog/posthog", prefix="emptylist")
+ ]
+
def test_excludes_non_github_and_soft_deleted_sources(self) -> None:
self._source(prefix="stripe", source_type=ExternalDataSourceType.STRIPE)
deleted = self._source(prefix="gone", repository="PostHog/posthog")
@@ -717,6 +731,234 @@ class TestListGitHubSources(BaseTest):
assert list_github_sources(team=self.team) == []
+class TestMultiRepoGitHubResolution(BaseTest):
+ """One GitHub source can sync several repositories: its added repos carry repo-qualified schema
+ rows (``owner/repo.endpoint`` + location metadata) while its original repo keeps bare names.
+ These guard the regression where the resolver only matched bare endpoint names — which made
+ every repo-qualified row (including a new source's single day-one-qualified repo) invisible, so
+ the product 400'd, and silently dropped a multi-repo source's added repos from the cost view."""
+
+ @staticmethod
+ def _slug(repo: str) -> str:
+ return repo.replace("/", "_").replace(".", "_").lower()
+
+ def _multi_repo_source(
+ self,
+ *,
+ prefix: str,
+ legacy_repository: str = "",
+ repos: dict[str, list[tuple[str, bool]]],
+ ) -> ExternalDataSource:
+ # repos: {repo_full_name: [(endpoint, has_table), ...]}. The repo equal to
+ # legacy_repository keeps bare endpoint names (the source's pre-multi-repo repo); every
+ # other repo is qualified as ``owner/repo.endpoint`` with location metadata, exactly as the
+ # multi-repo GitHub source lands them.
+ job_inputs: dict[str, Any] = {"repositories": list(repos.keys())}
+ if legacy_repository:
+ job_inputs["repository"] = legacy_repository
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id=f"src-{prefix}",
+ connection_id=f"src-{prefix}",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=ExternalDataSourceType.GITHUB,
+ prefix=prefix,
+ job_inputs=job_inputs,
+ )
+ for repo, endpoints in repos.items():
+ is_legacy = bool(legacy_repository) and repo.casefold() == legacy_repository.casefold()
+ for endpoint, has_table in endpoints:
+ name = endpoint if is_legacy else f"{repo}.{endpoint}"
+ table = (
+ create_warehouse_table_row(
+ self.team, name=f"{prefix}github_{self._slug(repo)}_{endpoint}", source=source
+ )
+ if has_table
+ else None
+ )
+ ExternalDataSchema.objects.create(
+ team=self.team,
+ source=source,
+ name=name,
+ table=table,
+ should_sync=True,
+ sync_type_config={}
+ if is_legacy
+ else {"schema_metadata": {"source_repository": repo.lower(), "source_endpoint": endpoint}},
+ )
+ return source
+
+ def test_new_source_single_qualified_repo_resolves(self) -> None:
+ # A source created via the multi-repo `repositories` field has no legacy `repository`, so its
+ # one repo is qualified from day one. Bare-name matching would 400 this — the onboarding break.
+ self._multi_repo_source(
+ prefix="fresh",
+ repos={"PostHog/posthog": [(PULL_REQUESTS_SCHEMA, True), (WORKFLOW_RUNS_SCHEMA, True)]},
+ )
+ tables = resolve_github_tables(team=self.team)
+ assert tables == GitHubTables(
+ pull_requests="freshgithub_posthog_posthog_pull_requests",
+ workflow_runs="freshgithub_posthog_posthog_workflow_runs",
+ repository="posthog/posthog",
+ )
+
+ @parameterized.expand(
+ [
+ # (repo arg, expected resolved repo, expected pull_requests table)
+ (None, "PostHog/posthog", "mixgithub_posthog_posthog_pull_requests"),
+ ("posthog/posthog.com", "posthog/posthog.com", "mixgithub_posthog_posthog_com_pull_requests"),
+ ("POSTHOG/POSTHOG", "PostHog/posthog", "mixgithub_posthog_posthog_pull_requests"),
+ ]
+ )
+ def test_multi_repo_source_scopes_by_repo(self, repo: str | None, expected_repo: str, expected_pr: str) -> None:
+ # One source, two repos: the legacy repo keeps bare names, the added repo is qualified. A
+ # `repo`-scoped read must reach the added repo's own tables, never mix them with the legacy
+ # repo's; the default (no repo) resolves the legacy repo first, as a single-repo source did.
+ self._multi_repo_source(
+ prefix="mix",
+ legacy_repository="PostHog/posthog",
+ repos={
+ "PostHog/posthog": [(PULL_REQUESTS_SCHEMA, True), (WORKFLOW_RUNS_SCHEMA, True)],
+ "posthog/posthog.com": [(PULL_REQUESTS_SCHEMA, True), (WORKFLOW_RUNS_SCHEMA, True)],
+ },
+ )
+ tables = resolve_github_tables(team=self.team, repo=repo)
+ assert tables.repository == expected_repo
+ assert tables.pull_requests == expected_pr
+
+ def test_picker_marks_repos_with_both_endpoints_synced(self) -> None:
+ # `synced` drives the default page's label: a repo is synced only with both pull_requests and
+ # workflow_runs, so a still-backfilling repo (only pull_requests) is flagged unsynced and the
+ # default selection skips it — matching what the resolver reads.
+ self._multi_repo_source(
+ prefix="mark",
+ legacy_repository="PostHog/posthog",
+ repos={
+ "PostHog/posthog": [(PULL_REQUESTS_SCHEMA, True), (WORKFLOW_RUNS_SCHEMA, True)],
+ "posthog/posthog.com": [(PULL_REQUESTS_SCHEMA, True)],
+ },
+ )
+ assert {source.repo: source.synced for source in list_github_sources(team=self.team)} == {
+ "PostHog/posthog": True,
+ "posthog/posthog.com": False,
+ }
+
+ def test_default_repo_follows_configured_order_not_alphabetical(self) -> None:
+ # A new source with no legacy repo: the default (unscoped) resolve must pick the first
+ # *configured* repo, matching what the picker labels as githubSources[0] — an alphabetical
+ # pick would query one repo while the UI names another.
+ self._multi_repo_source(
+ prefix="ordered",
+ repos={
+ "z/org": [(PULL_REQUESTS_SCHEMA, True), (WORKFLOW_RUNS_SCHEMA, True)],
+ "a/org": [(PULL_REQUESTS_SCHEMA, True), (WORKFLOW_RUNS_SCHEMA, True)],
+ },
+ )
+ # _multi_repo_source stores repositories in dict order (z/org, a/org), so z/org is configured first.
+ assert resolve_github_tables(team=self.team).repository == "z/org"
+
+ def test_default_follows_configured_order_even_over_the_legacy_repo(self) -> None:
+ # A legacy source (bare `repository`) whose `repositories` multi-select puts another repo first:
+ # the default must resolve that configured-first repo, matching the picker's first entry — the
+ # legacy repo gets no priority, or the UI would label repo A while the backend queried the legacy.
+ self._multi_repo_source(
+ prefix="legacyorder",
+ legacy_repository="PostHog/posthog",
+ repos={
+ # posthog.com configured first (qualified); the legacy posthog repo second (bare names).
+ "posthog/posthog.com": [(PULL_REQUESTS_SCHEMA, True), (WORKFLOW_RUNS_SCHEMA, True)],
+ "PostHog/posthog": [(PULL_REQUESTS_SCHEMA, True), (WORKFLOW_RUNS_SCHEMA, True)],
+ },
+ )
+ assert resolve_github_tables(team=self.team).repository == "posthog/posthog.com"
+
+ def test_explicit_repo_does_not_fall_through_to_a_sibling_repo(self) -> None:
+ # The picker lists a repo before it finishes syncing. Selecting one whose pull_requests/
+ # workflow_runs pair is incomplete must surface not-connected — never silently resolve the
+ # source's other (complete) repo, which would mix two repos' metrics.
+ self._multi_repo_source(
+ prefix="partial",
+ legacy_repository="PostHog/posthog",
+ repos={
+ "PostHog/posthog": [(PULL_REQUESTS_SCHEMA, True), (WORKFLOW_RUNS_SCHEMA, True)],
+ # workflow_runs still backfilling — no complete pair for this repo yet.
+ "posthog/posthog.com": [(PULL_REQUESTS_SCHEMA, True)],
+ },
+ )
+ with self.assertRaises(GitHubSourceNotConnectedError):
+ resolve_github_tables(team=self.team, repo="posthog/posthog.com")
+ # The complete sibling still resolves on its own.
+ assert resolve_github_tables(team=self.team, repo="PostHog/posthog").repository == "PostHog/posthog"
+
+ def test_incomplete_exact_match_does_not_fall_through_to_a_bare_source(self) -> None:
+ # An explicit repo whose own candidate exists but is half-synced must surface not-connected —
+ # never fall through to another source's bare/unattributed rows, which belong to an unknown
+ # repo. The bare fallback is only for when the requested repo has no candidate at all.
+ self._multi_repo_source(
+ prefix="halfsynced",
+ repos={"posthog/posthog.com": [(PULL_REQUESTS_SCHEMA, True)]},
+ )
+ bare = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id="src-bare",
+ connection_id="src-bare",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=ExternalDataSourceType.GITHUB,
+ prefix="bare",
+ job_inputs={},
+ )
+ for endpoint in (PULL_REQUESTS_SCHEMA, WORKFLOW_RUNS_SCHEMA):
+ ExternalDataSchema.objects.create(
+ team=self.team,
+ source=bare,
+ name=endpoint,
+ table=create_warehouse_table_row(self.team, name=f"baregithub_{endpoint}", source=bare),
+ should_sync=True,
+ sync_type_config={},
+ )
+ with self.assertRaises(GitHubSourceNotConnectedError):
+ resolve_github_tables(team=self.team, repo="posthog/posthog.com")
+ # Without an exact match the bare rows still serve as the fallback (branch-hint reads).
+ assert resolve_github_tables(team=self.team, repo="some/other").pull_requests == "baregithub_pull_requests"
+
+ def test_cost_pairs_include_every_repo_in_a_source(self) -> None:
+ # The cost view unions (jobs, runs) across repos. A multi-repo source must contribute one
+ # pair per fully-synced repo — collapsing it to one repo silently under-counts the view.
+ self._multi_repo_source(
+ prefix="cost",
+ legacy_repository="PostHog/posthog",
+ repos={
+ "PostHog/posthog": [(WORKFLOW_RUNS_SCHEMA, True), (WORKFLOW_JOBS_SCHEMA, True)],
+ "posthog/posthog.com": [(WORKFLOW_RUNS_SCHEMA, True), (WORKFLOW_JOBS_SCHEMA, True)],
+ # runs but no jobs — excluded, the view needs both.
+ "posthog/other": [(WORKFLOW_RUNS_SCHEMA, True)],
+ },
+ )
+ pairs = resolve_job_cost_source_pairs(self.team)
+ assert set(pairs) == {
+ ("costgithub_posthog_posthog_workflow_jobs", "costgithub_posthog_posthog_workflow_runs"),
+ ("costgithub_posthog_posthog_com_workflow_jobs", "costgithub_posthog_posthog_com_workflow_runs"),
+ }
+
+ def test_picker_lists_one_entry_per_configured_repo(self) -> None:
+ # A multi-repo source's `repositories` list drives the picker: one selectable (id, repo) per
+ # configured repo, in order, so a repo picker offers every repo the source syncs — not just
+ # the legacy one, and not the whole GitHub App's repo catalog.
+ source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_id="src-picker",
+ connection_id="src-picker",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=ExternalDataSourceType.GITHUB,
+ prefix="picker",
+ job_inputs={"repository": "PostHog/posthog", "repositories": ["PostHog/posthog", "PostHog/posthog.com"]},
+ )
+ assert list_github_sources(team=self.team) == [
+ GitHubSource(id=str(source.id), repo="PostHog/posthog", prefix="picker"),
+ GitHubSource(id=str(source.id), repo="PostHog/posthog.com", prefix="picker"),
+ ]
+
+
class TestWorkflowHealthWindowCap(BaseTest):
@parameterized.expand(["2000-01-01", "-500d"])
def test_rejects_windows_beyond_a_year(self, date_from: str) -> None:
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 6eade795e7b1..1f3ffe3aff25 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -159,7 +159,9 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
def test_sources_serializes(self) -> None:
sources = [
- contracts.GitHubSource(id="0192f000-0000-7000-8000-000000000000", repo="PostHog/posthog", prefix="older"),
+ contracts.GitHubSource(
+ id="0192f000-0000-7000-8000-000000000000", repo="PostHog/posthog", prefix="older", synced=True
+ ),
contracts.GitHubSource(
id="0192f000-0000-7000-8000-000000000001", repo="PostHog/posthog.com", prefix="website"
),
@@ -170,7 +172,9 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
body = response.json()
assert [s["id"] for s in body] == [sources[0].id, sources[1].id]
- assert body[0] == {"id": sources[0].id, "repo": "PostHog/posthog", "prefix": "older"}
+ assert body[0] == {"id": sources[0].id, "repo": "PostHog/posthog", "prefix": "older", "synced": True}
+ # synced defaults to False when the repo isn't fully synced yet.
+ assert body[1]["synced"] is False
def test_ci_cards_serializes(self) -> None:
with mock.patch(f"{_VIEWS}.get_ci_cards", return_value=_cards()):
diff --git a/products/engineering_analytics/frontend/components/PullRequestTable.tsx b/products/engineering_analytics/frontend/components/PullRequestTable.tsx
index 704d774d8a3f..24aad203b72c 100644
--- a/products/engineering_analytics/frontend/components/PullRequestTable.tsx
+++ b/products/engineering_analytics/frontend/components/PullRequestTable.tsx
@@ -15,6 +15,7 @@ import { compactAgeLabel, compactHoursLabel } from '../lib/format'
import { githubPrUrl } from '../lib/github'
import { pushRoundFromSample } from '../lib/pushRounds'
import { rowNavigationProps } from '../lib/rowNavigation'
+import { withCurrentScope } from '../lib/scope'
import { PullRequestRow, prKeyOf } from '../scenes/engineeringAnalyticsLogic'
import { BillableBadge } from './BillableBadge'
import { CIStatusTag } from './CIStatusTag'
@@ -23,10 +24,7 @@ import { PushHistorySparkline } from './PushHistorySparkline'
/** The PR's detail page, carrying the active source so it opens scoped to the same one. */
function detailUrlOf(row: PullRequestRow, sourceId: string | null): string {
- return combineUrl(
- urls.engineeringAnalyticsPullRequest(row.repoOwner, row.repoName, row.number),
- sourceId ? { source: sourceId } : {}
- ).url
+ return withCurrentScope(urls.engineeringAnalyticsPullRequest(row.repoOwner, row.repoName, row.number), sourceId)
}
/** How long the PR has been (or was) open, in the shared hours/days headline format.
diff --git a/products/engineering_analytics/frontend/components/ScopeBar.tsx b/products/engineering_analytics/frontend/components/ScopeBar.tsx
index 42ac946cc815..808f72d4444b 100644
--- a/products/engineering_analytics/frontend/components/ScopeBar.tsx
+++ b/products/engineering_analytics/frontend/components/ScopeBar.tsx
@@ -14,7 +14,7 @@ import { cn } from 'lib/utils/css-classes'
import { dateMapping } from 'lib/utils/dateFilters'
import { urls } from 'scenes/urls'
-import { withScope } from '../lib/scope'
+import { scopeFromValue, withScope } from '../lib/scope'
import { SHARED_DEFAULT_DATE_FROM, engineeringAnalyticsFiltersLogic } from '../scenes/engineeringAnalyticsFiltersLogic'
import { engineeringAnalyticsLogic } from '../scenes/engineeringAnalyticsLogic'
import { workflowSwitcherLogic } from '../scenes/workflowSwitcherLogic'
@@ -48,18 +48,22 @@ export interface LensChip {
const CHIP_CLASS =
'inline-flex items-center gap-1.5 rounded border border-primary bg-surface-primary px-2.5 py-1 text-xs text-secondary'
-/** A source picker on multi-source teams, otherwise the repo name. `pickerOnly` skips the static chip
- * on pages that already state the repo elsewhere (the hub's entity header). */
+/** A repo picker on multi-repo teams (multiple sources, or one source syncing several repos), otherwise
+ * the repo name. `pickerOnly` skips the static chip on pages that already state the repo elsewhere (the
+ * hub's entity header). */
export function SourceScopeChip({ pickerOnly = false }: { pickerOnly?: boolean }): JSX.Element | null {
- const { hasMultipleSources, sourceOptions, sourceId, activeSource } = useValues(engineeringAnalyticsLogic)
- const { setSourceId } = useActions(engineeringAnalyticsLogic)
+ const { hasMultipleSources, sourceOptions, selectedScope, activeSource } = useValues(engineeringAnalyticsLogic)
+ const { setScope } = useActions(engineeringAnalyticsLogic)
const repoLabel = activeSource?.repo
if (hasMultipleSources) {
return (
<LemonSelect
size="small"
- value={sourceId}
- onChange={setSourceId}
+ value={selectedScope}
+ onChange={(value) => {
+ const { sourceId, repo } = value ? scopeFromValue(value) : { sourceId: null, repo: null }
+ setScope(sourceId, repo)
+ }}
options={sourceOptions}
placeholder={repoLabel || 'Repository'}
allowClear
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index ed2ef1765f8f..0dbb0463fa49 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -896,12 +896,14 @@ export interface RunFailureLogsApi {
}
export interface GitHubSourceApi {
- /** Source id — pass as `source_id` to the other endpoints to read this source. */
+ /** Source id — pass back as `source_id` (with `repo`) to read this repository. */
id: string
- /** Connected repository as 'owner/name', or '' if unknown. */
+ /** Repository as 'owner/name' — pass back as `repo` to scope to it. One entry per repository a source syncs; '' if unknown. */
repo: string
/** User-chosen warehouse table-name prefix for this source, or '' when none. */
prefix: string
+ /** Whether this repo has both pull_requests and workflow_runs synced (readable now). Default the picker to the first synced entry so its label matches the resolved repo. */
+ synced?: boolean
}
export interface TeamTestSignalApi {
@@ -1126,6 +1128,10 @@ export type EngineeringAnalyticsAuthorWorkflowCostsParams = {
* Window end: relative or ISO8601. Defaults to now.
*/
date_to?: string
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -1133,6 +1139,10 @@ export type EngineeringAnalyticsAuthorWorkflowCostsParams = {
}
export type EngineeringAnalyticsBrokenTestsParams = {
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -1140,6 +1150,10 @@ export type EngineeringAnalyticsBrokenTestsParams = {
}
export type EngineeringAnalyticsCiCardsParams = {
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -1162,6 +1176,10 @@ export type EngineeringAnalyticsCiFailureLogsParams = {
}
export type EngineeringAnalyticsCurrentBranchHealthParams = {
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -1189,6 +1207,10 @@ export type EngineeringAnalyticsFlakyTestsParams = {
* A test qualifies once it passed on retry at least this many times in the window (OR-ed with min_failed_prs). Minimum 1. Defaults to 1.
*/
min_rerun_passes?: number
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -1208,6 +1230,10 @@ export type EngineeringAnalyticsJobAggregatesParams = {
* Window end: relative or ISO8601. Defaults to now.
*/
date_to?: string
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -1231,6 +1257,10 @@ export type EngineeringAnalyticsMasterFailuresParams = {
* Window end: relative or ISO8601. Defaults to now.
*/
date_to?: string
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -1291,6 +1321,10 @@ export type EngineeringAnalyticsPullRequestsParams = {
* Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
*/
date_from?: string
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -1321,6 +1355,10 @@ export type EngineeringAnalyticsRepoOverviewParams = {
* Set false to skip the chart series (cost_series, time_to_green_series, success_rate_series, open_to_merge_series return empty) and their query cost — for headline-only consumers like the weekly digest. Defaults to true.
*/
include_series?: boolean
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -1340,6 +1378,10 @@ export type EngineeringAnalyticsRepoRunActivityParams = {
* Window end: relative or ISO8601. Defaults to now.
*/
date_to?: string
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -1366,6 +1408,10 @@ export type EngineeringAnalyticsResolveBranchParams = {
}
export type EngineeringAnalyticsRunFailureLogsParams = {
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string
/**
* Workflow run id whose failure logs to fetch.
*/
@@ -1458,6 +1504,10 @@ export type EngineeringAnalyticsWorkflowHealthParams = {
* Window end: relative or ISO8601. Defaults to now.
*/
date_to?: string
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string
/**
* Run scope for workflow health: 'all' (default) includes every run; 'pull_request' includes runs attributed to pull requests, excluding default-branch (master/main) runs. Fork PRs carry no PR attribution (a GitHub limitation), so 'pull_request' covers same-repo PRs only. Any other value is a 400.
*/
@@ -1477,6 +1527,10 @@ export const EngineeringAnalyticsWorkflowHealthRunScope = {
} as const
export type EngineeringAnalyticsWorkflowJobsParams = {
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string
/**
* Which re-run attempt to scope jobs to. Omit to use the run's latest attempt; pass an explicit attempt to avoid mixing jobs across a re-run's attempts.
*/
@@ -1492,6 +1546,10 @@ export type EngineeringAnalyticsWorkflowJobsParams = {
}
export type EngineeringAnalyticsWorkflowRunParams = {
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string
/**
* GitHub Actions run id to inspect.
*/
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index 78d9c3c29727..eab456742c89 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -642,7 +642,7 @@ export const getEngineeringAnalyticsSourcesUrl = (projectId: string) => {
}
/**
- * The team's connected GitHub data warehouse sources, oldest first. Populate a source picker from this and pass a chosen `id` back as `source_id` to the other endpoints. A team can connect GitHub more than once (e.g. one source per repository); this lists them all, including any whose tables aren't fully synced yet.
+ * The team's selectable GitHub repositories, oldest source first — one entry per repository a source is configured to sync, so a source syncing several repositories appears once per repo. Populate a repo picker from this and pass a chosen entry's `id` back as `source_id` and its `repo` back as `repo` to the other endpoints. Includes repositories whose tables aren't fully synced yet.
*/
export const engineeringAnalyticsSources = async (
projectId: string,
diff --git a/products/engineering_analytics/frontend/lib/scope.ts b/products/engineering_analytics/frontend/lib/scope.ts
index 492293cf8bbc..74dfb14d1aff 100644
--- a/products/engineering_analytics/frontend/lib/scope.ts
+++ b/products/engineering_analytics/frontend/lib/scope.ts
@@ -1,10 +1,10 @@
-import { combineUrl } from 'kea-router'
+import { combineUrl, router } from 'kea-router'
-/** Carry the shared window + branch scope (and active source) onto an internal nav URL, so drilling in,
- * switching workflows, or stepping back never silently resets it. The scope lives in the URL — every
- * cross-page link threads it the same way the tab links do (`?date_from` / `?date_to` / `?q` / `?source`).
- * The pull-request lens (`?run_scope`) is intentionally not carried: only workflow health honors it, so it
- * stays on the Workflows tab rather than following a drill-down that can't apply it. */
+/** Carry the shared window + branch scope (and active source/repo) onto an internal nav URL, so drilling
+ * in, switching workflows, or stepping back never silently resets it. The scope lives in the URL — every
+ * cross-page link threads it the same way the tab links do (`?date_from` / `?date_to` / `?q` / `?source`
+ * / `?repo`). The pull-request lens (`?run_scope`) is intentionally not carried: only workflow health
+ * honors it, so it stays on the Workflows tab rather than following a drill-down that can't apply it. */
export function withScope(
url: string,
searchParams: Record<string, string | undefined>,
@@ -15,5 +15,29 @@ export function withScope(
...(searchParams.date_to ? { date_to: searchParams.date_to } : {}),
...(searchParams.q ? { q: searchParams.q } : {}),
...(sourceId ? { source: sourceId } : {}),
+ // Carry the repo scope of a multi-repo source (set by the picker) the same way as `?q` — from
+ // the current URL — so every withScope-based link preserves it with no caller change.
+ ...(searchParams.repo ? { repo: searchParams.repo } : {}),
}).url
}
+
+/** Like withScope, but reads the live URL for module-level link builders that don't have
+ * searchParams in scope — so a source-only link still carries the current window / branch / repo. */
+export function withCurrentScope(url: string, sourceId: string | null | undefined): string {
+ return withScope(url, router.values.searchParams, sourceId)
+}
+
+/** Encode a (source, repo) selection as one string for the repo picker's LemonSelect value, since a
+ * source can offer several repos. `::` never appears in a UUID or an 'owner/name', so the split is safe. */
+export function scopeToValue(sourceId: string, repo: string): string {
+ return `${sourceId}::${repo}`
+}
+
+export function scopeFromValue(value: string): { sourceId: string; repo: string | null } {
+ const sep = value.indexOf('::')
+ if (sep === -1) {
+ return { sourceId: value, repo: null }
+ }
+ // A blank repo (a source with no configured repo) decodes to null → backend default repo.
+ return { sourceId: value.slice(0, sep), repo: value.slice(sep + 2) || null }
+}
diff --git a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
index 797286ca56d5..6e987e07956f 100644
--- a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
@@ -39,6 +39,7 @@ import { compactCount, compactUsd } from '../lib/format'
import { githubCommitUrl, githubPrUrl } from '../lib/github'
import { LifecycleSummary, WorkflowRun, isPassingConclusion } from '../lib/lifecycle'
import { PushRound, pushRoundColor, pushRoundOf, pushRoundVerdictLabel } from '../lib/pushRounds'
+import { withCurrentScope } from '../lib/scope'
import {
PrCommitRuns,
PrRunRow,
@@ -366,12 +367,10 @@ function PerPushRunsTable({
render: (_, run) =>
run.runId != null ? (
<Link
- to={
- combineUrl(
- urls.engineeringAnalyticsWorkflowRun(repoOwner, repoName, run.runId),
- sourceId ? { source: sourceId } : {}
- ).url
- }
+ to={withCurrentScope(
+ urls.engineeringAnalyticsWorkflowRun(repoOwner, repoName, run.runId),
+ sourceId
+ )}
className="font-mono text-xs"
>
#{run.runId}
@@ -535,12 +534,10 @@ function PrWorkflowsTable({
)}
/>
<Link
- to={
- combineUrl(
- urls.engineeringAnalyticsWorkflowRuns(repoOwner, repoName, row.workflowName),
- sourceId ? { source: sourceId } : {}
- ).url
- }
+ to={withCurrentScope(
+ urls.engineeringAnalyticsWorkflowRuns(repoOwner, repoName, row.workflowName),
+ sourceId
+ )}
>
{row.workflowName}
</Link>
@@ -722,12 +719,12 @@ export function PullRequestDetailScene(): JSX.Element {
repoSlot={
<RepoScopeChip
label={`${repoOwner}/${repoName}`}
- to={combineUrl(urls.engineeringAnalytics(), sourceId ? { source: sourceId } : {}).url}
+ to={withCurrentScope(urls.engineeringAnalytics(), sourceId)}
/>
}
lensFilter={{
label: `pr: #${pullRequest?.number ?? ''}`,
- to: combineUrl(urls.engineeringAnalytics(), sourceId ? { source: sourceId } : {}).url,
+ to: withCurrentScope(urls.engineeringAnalytics(), sourceId),
}}
showDate={false}
/>
diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
index 06b79622a4d2..e09624b07249 100644
--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx
@@ -2,7 +2,7 @@
// attention, workflows, and cost as sections on one page.
import { useActions, useValues } from 'kea'
-import { combineUrl, router } from 'kea-router'
+import { router } from 'kea-router'
import { LemonButton, LemonCard, LemonSkeleton, LemonTable, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
import { TimeSeriesLineChart, useChartTheme } from '@posthog/quill-charts'
@@ -29,11 +29,12 @@ import type { MasterFailureGroupApi } from '../generated/api.schemas'
import { compactHoursLabel, compactMinutes, compactUsd, percent } from '../lib/format'
import { githubCommitUrl } from '../lib/github'
import { HUB_PREVIEW_MAX } from '../lib/preview'
+import { withCurrentScope, withScope } from '../lib/scope'
import { engineeringAnalyticsLogic } from './engineeringAnalyticsLogic'
import { repoOverviewLogic } from './repoOverviewLogic'
function withSource(url: string, sourceId: string | null): string {
- return combineUrl(url, sourceId ? { source: sourceId } : {}).url
+ return withCurrentScope(url, sourceId)
}
/** The page's thesis: is the pipeline healthy right now? Default-branch verdict plus open-PR backlog
@@ -516,14 +517,9 @@ export function RepoOverviewScene(): JSX.Element {
)}
<Link
to={
- // A bare link would reset the shared window/branch scope (the filters logic
- // re-hydrates from the URL on every route) — carry it, plus the source.
- combineUrl(urls.engineeringAnalyticsWorkflows(), {
- ...(searchParams.date_from ? { date_from: searchParams.date_from } : {}),
- ...(searchParams.date_to ? { date_to: searchParams.date_to } : {}),
- ...(searchParams.q ? { q: searchParams.q } : {}),
- ...(sourceId ? { source: sourceId } : {}),
- }).url
+ // A bare link would reset the shared window / branch / repo scope (the filters
+ // logic re-hydrates from the URL on every route) — carry it, plus the source.
+ withScope(urls.engineeringAnalyticsWorkflows(), searchParams, sourceId)
}
>
View all →
diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
index f00deab610fd..36578b302d53 100644
--- a/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunDetailScene.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { combineUrl, router } from 'kea-router'
+import { router } from 'kea-router'
import { IconCheckCircle, IconExternal, IconHourglass, IconPause, IconXCircle } from '@posthog/icons'
import { LemonButton, LemonSkeleton, Link } from '@posthog/lemon-ui'
@@ -66,10 +66,11 @@ export function WorkflowRunDetailScene(): JSX.Element {
const verdict = run ? verdictTag(run.conclusion) : null
const prUrl =
run && run.pr_number > 0
- ? combineUrl(
+ ? withScope(
urls.engineeringAnalyticsPullRequest(run.repo.owner, run.repo.name, run.pr_number),
- sourceId ? { source: sourceId } : {}
- ).url
+ searchParams,
+ sourceId
+ )
: null
// Run started → first job started: the runner-capacity wait before anything executed.
const jobStarts = (jobs ?? []).map((job) => job.started_at).filter((at): at is string => !!at)
diff --git a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
index 00bfd0a8f6ef..61d1ce10c07b 100644
--- a/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/WorkflowRunsScene.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { combineUrl, router } from 'kea-router'
+import { router } from 'kea-router'
import { IconExternal, IconGear } from '@posthog/icons'
import { LemonButton, LemonTable, LemonTableColumns, LemonTag, Link } from '@posthog/lemon-ui'
@@ -200,12 +200,11 @@ export function WorkflowRunsScene(): JSX.Element {
render: (_, run) =>
run.prNumber > 0 ? (
<Link
- to={
- combineUrl(
- urls.engineeringAnalyticsPullRequest(run.repoOwner, run.repoName, run.prNumber),
- sourceId ? { source: sourceId } : {}
- ).url
- }
+ to={withScope(
+ urls.engineeringAnalyticsPullRequest(run.repoOwner, run.repoName, run.prNumber),
+ searchParams,
+ sourceId
+ )}
onClick={(e) => e.stopPropagation()}
>
#{run.prNumber}
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
index bf3a3a2f1f5a..6a61b3a744d6 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.test.ts
@@ -226,8 +226,8 @@ function makeWorkflow(overrides: Partial<WorkflowHealthRow> = {}): WorkflowHealt
}
const SOURCES: GitHubSourceApi[] = [
- { id: 'src-older', repo: 'posthog/posthog', prefix: 'older' },
- { id: 'src-newer', repo: 'posthog/posthog.com', prefix: 'website' },
+ { id: 'src-older', repo: 'posthog/posthog', prefix: 'older', synced: true },
+ { id: 'src-newer', repo: 'posthog/posthog.com', prefix: 'website', synced: true },
]
describe('engineeringAnalyticsLogic', () => {
@@ -431,12 +431,35 @@ describe('engineeringAnalyticsLogic', () => {
await expectLogic(logic).toDispatchActions(['loadGithubSourcesSuccess'])
expect(logic.values.hasMultipleSources).toBe(true)
+ // The option value encodes (source, repo) so a multi-repo source's repos stay distinct.
expect(logic.values.sourceOptions).toEqual([
- { value: 'src-older', label: 'posthog/posthog' },
- { value: 'src-newer', label: 'posthog/posthog.com' },
+ { value: 'src-older::posthog/posthog', label: 'posthog/posthog' },
+ { value: 'src-newer::posthog/posthog.com', label: 'posthog/posthog.com' },
])
})
+ it('lists one option per configured repo of a multi-repo source and scopes to the picked repo', async () => {
+ // One source syncing two repos → two distinct picker entries; picking one scopes source_id + repo.
+ mockSources.mockResolvedValue([
+ { id: 'src-multi', repo: 'posthog/posthog', prefix: 'multi', synced: true },
+ { id: 'src-multi', repo: 'posthog/posthog.com', prefix: 'multi', synced: true },
+ ])
+ logic = engineeringAnalyticsLogic()
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadGithubSourcesSuccess', 'loadCardsSuccess'])
+
+ expect(logic.values.hasMultipleSources).toBe(true)
+ expect(logic.values.sourceOptions).toEqual([
+ { value: 'src-multi::posthog/posthog', label: 'posthog/posthog' },
+ { value: 'src-multi::posthog/posthog.com', label: 'posthog/posthog.com' },
+ ])
+
+ logic.actions.setScope('src-multi', 'posthog/posthog.com')
+ await expectLogic(logic).toDispatchActions(['setScope', 'loadCardsSuccess'])
+ expect(logic.values.selectedScope).toBe('src-multi::posthog/posthog.com')
+ expect(mockCiCards).toHaveBeenLastCalledWith('1', { source_id: 'src-multi', repo: 'posthog/posthog.com' })
+ })
+
it('hides the picker when the team has a single source', async () => {
mockSources.mockResolvedValue([SOURCES[0]])
logic = engineeringAnalyticsLogic()
@@ -454,8 +477,8 @@ describe('engineeringAnalyticsLogic', () => {
'loadPullRequestsSuccess',
'loadWorkflowHealthSuccess',
])
- // No source picked → omit source_id so the backend resolves its default.
- expect(mockCiCards).toHaveBeenLastCalledWith('1', { source_id: undefined })
+ // No source picked → omit source_id/repo so the backend resolves its default.
+ expect(mockCiCards).toHaveBeenLastCalledWith('1', { source_id: undefined, repo: undefined })
logic.actions.setSourceId('src-newer')
await expectLogic(logic).toDispatchActions([
@@ -467,9 +490,13 @@ describe('engineeringAnalyticsLogic', () => {
])
expect(logic.values.sourceId).toBe('src-newer')
- expect(mockCiCards).toHaveBeenLastCalledWith('1', { source_id: 'src-newer' })
- expect(mockPullRequests).toHaveBeenLastCalledWith('1', { source_id: 'src-newer' })
- expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', { date_from: '-7d', source_id: 'src-newer' })
+ expect(mockCiCards).toHaveBeenLastCalledWith('1', { source_id: 'src-newer', repo: undefined })
+ expect(mockPullRequests).toHaveBeenLastCalledWith('1', { source_id: 'src-newer', repo: undefined })
+ expect(mockWorkflowHealth).toHaveBeenLastCalledWith('1', {
+ date_from: '-7d',
+ source_id: 'src-newer',
+ repo: undefined,
+ })
})
it.each([
@@ -519,13 +546,14 @@ describe('engineeringAnalyticsLogic', () => {
it.each([
['workflows', () => urls.engineeringAnalyticsWorkflows()],
['test health', () => urls.engineeringAnalyticsTestHealth()],
- ])('the %s route applies ?source like the other tabs', async (_label, url) => {
+ ])('the %s route applies ?source and ?repo like the other tabs', async (_label, url) => {
logic = engineeringAnalyticsLogic()
logic.mount()
- router.actions.push(url(), { source: 'src-newer' })
- await expectLogic(logic).toDispatchActions(['setSourceId'])
+ router.actions.push(url(), { source: 'src-newer', repo: 'posthog/posthog.com' })
+ await expectLogic(logic).toDispatchActions(['setScope'])
expect(logic.values.sourceId).toBe('src-newer')
+ expect(logic.values.scopeRepo).toBe('posthog/posthog.com')
})
it('resetFilters returns every filter to defaults and clears hasActiveFilters', async () => {
diff --git a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
index ed8cdcf1439c..5be45d3ae537 100644
--- a/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/engineeringAnalyticsLogic.ts
@@ -43,6 +43,7 @@ import type {
} from '../generated/api.schemas'
import { CIStatus, ciStatusOf } from '../lib/ci'
import { type FleetSummary, computeFleetSummary } from '../lib/runHealth'
+import { scopeToValue } from '../lib/scope'
import { engineeringAnalyticsFiltersLogic } from './engineeringAnalyticsFiltersLogic'
import type { BranchHealthParams } from './engineeringAnalyticsFiltersLogic'
@@ -674,7 +675,9 @@ export interface engineeringAnalyticsLogicValues {
repo: string | null
runFailureLogsByRun: Record<number, RunFailureLogsApi>
runFailureLogsByRunLoading: boolean
+ scopeRepo: string | null
search: string
+ selectedScope: string | null
showPrOnlyBrokenTests: boolean
sourceId: string | null
sourceOptions: {
@@ -876,6 +879,13 @@ export interface engineeringAnalyticsLogicActions {
setRepo: (repo: string | null) => {
repo: string | null
}
+ setScope: (
+ sourceId: string | null,
+ scopeRepo: string | null
+ ) => {
+ scopeRepo: string | null
+ sourceId: string | null
+ }
setSearch: (search: string) => {
search: string
}
@@ -993,11 +1003,20 @@ export interface engineeringAnalyticsLogicMeta {
hiddenBrokenTestCount: (brokenTests: BrokenTestRow[]) => number
visibleBrokenTests: (brokenTests: BrokenTestRow[], showPrOnlyBrokenTests: boolean) => BrokenTestRow[]
hasMultipleSources: (githubSources: GitHubSourceApi[]) => boolean
- activeSource: (githubSources: GitHubSourceApi[], sourceId: string | null) => GitHubSourceApi | null
+ activeSource: (
+ githubSources: GitHubSourceApi[],
+ sourceId: string | null,
+ scopeRepo: string | null
+ ) => GitHubSourceApi | null
sourceOptions: (githubSources: GitHubSourceApi[]) => {
label: string
value: string
}[]
+ selectedScope: (
+ githubSources: GitHubSourceApi[],
+ sourceId: string | null,
+ scopeRepo: string | null
+ ) => string | null
}
}
@@ -1030,6 +1049,8 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
setThrashOnly: (thrash: boolean) => ({ thrash }),
applyCardFilter: (card: CardFilter) => ({ card }),
setSourceId: (sourceId: string | null) => ({ sourceId }),
+ // The picker selects a (source, repo) pair in one action, so both land before a single refresh.
+ setScope: (sourceId: string | null, scopeRepo: string | null) => ({ sourceId, scopeRepo }),
resetFilters: true,
setQuarantineSearch: (search: string) => ({ search }),
setQuarantineLifecycleFilter: (lifecycle: QuarantineLifecycleFilter) => ({ lifecycle }),
@@ -1051,6 +1072,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
loadCards: async (): Promise<CardsData> => {
const data = await engineeringAnalyticsCiCards(projectId(), {
source_id: values.sourceId ?? undefined,
+ repo: values.scopeRepo ?? undefined,
})
return {
openPrs: data.open_prs,
@@ -1067,6 +1089,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
loadPullRequests: async (): Promise<PullRequestRow[]> => {
const response = await engineeringAnalyticsPullRequests(projectId(), {
source_id: values.sourceId ?? undefined,
+ repo: values.scopeRepo ?? undefined,
})
return response.items.map(toPullRequestRow)
},
@@ -1081,6 +1104,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
date_to: values.dateTo ?? undefined,
...values.branchHealthParams,
source_id: values.sourceId ?? undefined,
+ repo: values.scopeRepo ?? undefined,
})
return items.map(
(it): WorkflowHealthRow => ({
@@ -1118,6 +1142,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
loadQuarantine: async (): Promise<QuarantineData> => {
const data = await engineeringAnalyticsQuarantine(projectId(), {
source_id: values.sourceId ?? undefined,
+ repo: values.scopeRepo ?? undefined,
})
return {
available: data.available,
@@ -1152,6 +1177,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
date_from: values.flakyTestWindow,
limit: FLAKY_TEST_LIMIT,
source_id: values.sourceId ?? undefined,
+ repo: values.scopeRepo ?? undefined,
})
return {
rows: data.items.map(
@@ -1178,6 +1204,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
loadBrokenTests: async (): Promise<BrokenTestsData> => {
const data = await engineeringAnalyticsBrokenTests(projectId(), {
source_id: values.sourceId ?? undefined,
+ repo: values.scopeRepo ?? undefined,
})
return {
rows: data.rows.map(toBrokenTestRow),
@@ -1206,6 +1233,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
const result = await engineeringAnalyticsRunFailureLogs(projectId(), {
run_id: runId,
source_id: values.sourceId ?? undefined,
+ repo: values.scopeRepo ?? undefined,
})
return { ...values.runFailureLogsByRun, [runId]: result }
},
@@ -1293,7 +1321,13 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
},
],
// Which GitHub source to read; null = backend default (oldest connected). Synced to `?source=`.
- sourceId: [null as string | null, { setSourceId: (_, { sourceId }) => sourceId }],
+ sourceId: [
+ null as string | null,
+ { setSourceId: (_, { sourceId }) => sourceId, setScope: (_, { sourceId }) => sourceId },
+ ],
+ // Repo scope of a multi-repo source. Cleared when the source changes on its own (the old repo
+ // belongs to the old source); the picker uses setScope to set both together.
+ scopeRepo: [null as string | null, { setScope: (_, { scopeRepo }) => scopeRepo, setSourceId: () => null }],
cardsStatus: [
'ok' as LoaderStatus,
{
@@ -1603,19 +1637,75 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
(githubSources: GitHubSourceApi[]): boolean => githubSources.length > 1,
],
// The source reads resolve to: the picked one, else the backend default (oldest connected = first).
+ // Matched by (source, repo), not source alone: a multi-repo source's entries share one id,
+ // so headers and commit links reading activeSource.repo must reflect the picked repo, not
+ // the first entry with that id.
activeSource: [
- (s) => [s.githubSources, s.sourceId],
- (githubSources: GitHubSourceApi[], sourceId: string | null): GitHubSourceApi | null =>
- (sourceId ? githubSources.find((source) => source.id === sourceId) : githubSources[0]) ?? null,
+ (s) => [s.githubSources, s.sourceId, s.scopeRepo],
+ (
+ githubSources: GitHubSourceApi[],
+ sourceId: string | null,
+ scopeRepo: string | null
+ ): GitHubSourceApi | null => {
+ if (!sourceId) {
+ // A repo-only scope (?repo with no ?source) resolves across sources — label that
+ // repo. Otherwise prefer the first *synced* repo, matching the repo the backend
+ // resolves by default (it skips still-backfilling repos), else the first entry.
+ return (
+ (scopeRepo && githubSources.find((source) => source.repo === scopeRepo)) ||
+ githubSources.find((source) => source.synced) ||
+ githubSources[0] ||
+ null
+ )
+ }
+ const ofSource = githubSources.filter((source) => source.id === sourceId)
+ // Explicit repo wins; otherwise (a bookmarked `?source=` with no `?repo`) prefer the
+ // first synced repo of this source, matching the repo the backend resolves by default —
+ // else the header names an unsynced repo the loaders never read.
+ return (
+ (scopeRepo && ofSource.find((source) => source.repo === scopeRepo)) ||
+ ofSource.find((source) => source.synced) ||
+ ofSource[0] ||
+ null
+ )
+ },
],
+ // One option per selectable (source, repo). The value encodes both so a multi-repo source's
+ // repos are distinct entries; the label is the repo (falling back to prefix).
sourceOptions: [
(s) => [s.githubSources],
(githubSources: GitHubSourceApi[]): { value: string; label: string }[] =>
githubSources.map((source) => ({
- value: source.id,
+ value: scopeToValue(source.id, source.repo),
label: source.repo || source.prefix || `source ${source.id.slice(0, 8)}`,
})),
],
+ // The picker's current value: the entry matching the picked (source, repo), else that source's
+ // first entry, else null (unpicked → placeholder + backend default).
+ selectedScope: [
+ (s) => [s.githubSources, s.sourceId, s.scopeRepo],
+ (
+ githubSources: GitHubSourceApi[],
+ sourceId: string | null,
+ scopeRepo: string | null
+ ): string | null => {
+ if (!sourceId) {
+ // A repo-only scope (?repo, no ?source) highlights that repo across sources; an
+ // unscoped page highlights nothing (placeholder shows the default label).
+ const byRepo = scopeRepo && githubSources.find((source) => source.repo === scopeRepo)
+ return byRepo ? scopeToValue(byRepo.id, byRepo.repo) : null
+ }
+ // Mirror activeSource: with no explicit repo, prefer the synced entry so the picker
+ // highlights the repo the loaders actually read — else it shows an unsynced repo whose
+ // selection would flip the page to not-connected.
+ const ofSource = githubSources.filter((source) => source.id === sourceId)
+ const match =
+ (scopeRepo && ofSource.find((source) => source.repo === scopeRepo)) ||
+ ofSource.find((source) => source.synced) ||
+ ofSource[0]
+ return match ? scopeToValue(match.id, match.repo) : null
+ },
+ ],
}),
listeners(({ actions, values }) => ({
@@ -1629,6 +1719,7 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
},
setFlakyTestWindow: () => actions.loadFlakyTests(),
setSourceId: () => actions.refresh(),
+ setScope: () => actions.refresh(),
[engineeringAnalyticsFiltersLogic.actionTypes.setDateRange]: () => {
actions.loadWorkflowHealth()
},
@@ -1679,31 +1770,46 @@ export const engineeringAnalyticsLogic: LogicWrapper<engineeringAnalyticsLogicTy
},
})),
- actionToUrl(() => ({
- setSourceId: ({ sourceId }) => {
+ actionToUrl(() => {
+ // Write the (source, repo) scope onto the URL. A source change without a repo drops `?repo`
+ // (the old repo belonged to the old source); setScope writes both together.
+ const writeScope = (
+ sourceId: string | null,
+ scopeRepo: string | null
+ ): [string, Record<string, string>, Record<string, string>, { replace: boolean }] => {
const searchParams = { ...router.values.searchParams }
if (sourceId) {
searchParams.source = sourceId
} else {
delete searchParams.source
}
+ if (scopeRepo) {
+ searchParams.repo = scopeRepo
+ } else {
+ delete searchParams.repo
+ }
return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]
- },
- })),
+ }
+ return {
+ setSourceId: ({ sourceId }) => writeScope(sourceId, null),
+ setScope: ({ sourceId, scopeRepo }) => writeScope(sourceId, scopeRepo),
+ }
+ }),
urlToAction(({ actions, values }) => {
// `?q=` (branch scope) is hydrated by engineeringAnalyticsFiltersLogic, not here.
- const applySource = (source: string | undefined): void => {
- const next = source ?? null
- if (next !== values.sourceId) {
- actions.setSourceId(next)
+ const applyScope = (source: string | undefined, repo: string | undefined): void => {
+ const nextSource = source ?? null
+ const nextRepo = repo ?? null
+ if (nextSource !== values.sourceId || nextRepo !== values.scopeRepo) {
+ actions.setScope(nextSource, nextRepo)
}
}
return {
- [urls.engineeringAnalytics()]: (_, searchParams) => applySource(searchParams.source),
- [urls.engineeringAnalyticsPullRequestList()]: (_, searchParams) => applySource(searchParams.source),
- [urls.engineeringAnalyticsWorkflows()]: (_, searchParams) => applySource(searchParams.source),
- [urls.engineeringAnalyticsTestHealth()]: (_, searchParams) => applySource(searchParams.source),
+ [urls.engineeringAnalytics()]: (_, s) => applyScope(s.source, s.repo),
+ [urls.engineeringAnalyticsPullRequestList()]: (_, s) => applyScope(s.source, s.repo),
+ [urls.engineeringAnalyticsWorkflows()]: (_, s) => applyScope(s.source, s.repo),
+ [urls.engineeringAnalyticsTestHealth()]: (_, s) => applyScope(s.source, s.repo),
}
}),
diff --git a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
index f90c82dee844..9a5708eb4ee0 100644
--- a/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/pullRequestDetailLogic.ts
@@ -427,6 +427,7 @@ export const pullRequestDetailLogic = kea<pullRequestDetailLogicType>([
run_id: runId,
run_attempt: runAttempt ?? undefined,
source_id: props.sourceId ?? undefined,
+ repo: `${props.repoOwner}/${props.repoName}`,
})
return { ...values.runJobs, [jobCacheKey(runId, runAttempt)]: jobs }
},
diff --git a/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts b/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts
index 7f86a6f4447e..c6fa3e3d835d 100644
--- a/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/repoOverviewLogic.ts
@@ -52,6 +52,7 @@ export interface repoOverviewLogicValues {
notConnected: boolean // engineeringAnalyticsLogic
pullRequests: PullRequestRow[] // engineeringAnalyticsLogic
pullRequestsLoading: boolean // engineeringAnalyticsLogic
+ scopeRepo: string | null // engineeringAnalyticsLogic
sourceId: string | null // engineeringAnalyticsLogic
workflowHealth: WorkflowHealthRow[] // engineeringAnalyticsLogic
workflowHealthLoading: boolean // engineeringAnalyticsLogic
@@ -246,6 +247,7 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
engineeringAnalyticsLogic,
[
'sourceId',
+ 'scopeRepo',
'pullRequests',
'pullRequestsLoading',
'cards',
@@ -271,6 +273,7 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
date_from: values.dateFrom ?? undefined,
date_to: values.dateTo ?? undefined,
source_id: values.sourceId ?? undefined,
+ repo: values.scopeRepo ?? undefined,
}),
},
],
@@ -281,6 +284,7 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
await engineeringAnalyticsMasterFailures(projectId(), {
date_from: MASTER_FAILURES_WINDOW,
source_id: values.sourceId ?? undefined,
+ repo: values.scopeRepo ?? undefined,
}),
},
],
@@ -290,6 +294,7 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
loadCurrentBranchHealth: async (_: void, breakpoint): Promise<CurrentBranchHealthApi> => {
const health = await engineeringAnalyticsCurrentBranchHealth(projectId(), {
source_id: values.sourceId ?? undefined,
+ repo: values.scopeRepo ?? undefined,
})
breakpoint()
return health
@@ -306,6 +311,7 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
date_from: values.dateFrom ?? undefined,
date_to: values.dateTo ?? undefined,
source_id: values.sourceId ?? undefined,
+ repo: values.scopeRepo ?? undefined,
}),
},
],
@@ -322,6 +328,7 @@ export const repoOverviewLogic = kea<repoOverviewLogicType>([
const logs = await engineeringAnalyticsRunFailureLogs(projectId(), {
run_id: runId,
source_id: values.sourceId ?? undefined,
+ repo: values.scopeRepo ?? undefined,
})
return { ...values.failureLogs, [runId]: logs }
} catch {
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts b/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts
index 73dff77c2a49..fd7d54a45ec7 100644
--- a/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowRunDetailLogic.ts
@@ -121,6 +121,7 @@ export const workflowRunDetailLogic = kea<workflowRunDetailLogicType>([
await engineeringAnalyticsWorkflowRun(projectId(), {
run_id: props.runId,
source_id: props.sourceId ?? undefined,
+ repo: `${props.repoOwner}/${props.repoName}`,
}),
},
],
@@ -134,6 +135,7 @@ export const workflowRunDetailLogic = kea<workflowRunDetailLogicType>([
run_id: props.runId,
run_attempt: values.run?.run_attempt ?? undefined,
source_id: props.sourceId ?? undefined,
+ repo: `${props.repoOwner}/${props.repoName}`,
}),
},
],
@@ -146,6 +148,7 @@ export const workflowRunDetailLogic = kea<workflowRunDetailLogicType>([
return await engineeringAnalyticsRunFailureLogs(projectId(), {
run_id: props.runId,
source_id: props.sourceId ?? undefined,
+ repo: `${props.repoOwner}/${props.repoName}`,
})
} catch {
return 'unavailable'
diff --git a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
index 629ad8255d27..7c68c0d9c45c 100644
--- a/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowRunsLogic.ts
@@ -285,6 +285,7 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
loadJobAggregates: async (): Promise<WorkflowJobAggregateApi[]> =>
await engineeringAnalyticsJobAggregates(projectId(), {
workflow_name: props.workflowName,
+ repo: `${props.repoOwner}/${props.repoName}`,
date_from: values.dateFrom ?? undefined,
date_to: values.dateTo ?? undefined,
branch: values.appliedBranch || undefined,
@@ -307,6 +308,7 @@ export const workflowRunsLogic = kea<workflowRunsLogicType>([
run_id: runId,
run_attempt: runAttempt ?? undefined,
source_id: props.sourceId ?? undefined,
+ repo: `${props.repoOwner}/${props.repoName}`,
})
return { ...values.runJobs, [jobCacheKey(runId, runAttempt)]: jobs }
},
diff --git a/products/engineering_analytics/frontend/scenes/workflowSwitcherLogic.ts b/products/engineering_analytics/frontend/scenes/workflowSwitcherLogic.ts
index 14fa756852fc..4e5938fb43ed 100644
--- a/products/engineering_analytics/frontend/scenes/workflowSwitcherLogic.ts
+++ b/products/engineering_analytics/frontend/scenes/workflowSwitcherLogic.ts
@@ -83,6 +83,7 @@ export const workflowSwitcherLogic = kea<workflowSwitcherLogicType>([
date_to: values.dateTo ?? undefined,
branch: values.appliedBranch || undefined,
source_id: props.sourceId ?? undefined,
+ repo: `${props.repoOwner}/${props.repoName}`,
})
// Server order (top workflows by run count) — the most active ones surface first.
return items
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index 0229a2ce4b0c..e5cfa48fa621 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -159,13 +159,20 @@ tools:
list: true
title: List connected GitHub sources
description: >
- The team's connected GitHub data warehouse sources, oldest first, each with its id, repo (owner/name), and
- table prefix. Call this first when a team may have more than one GitHub source, then pass a chosen id as
- source_id to the pull-requests, workflow-health, ci-cards, or pr-lifecycle tools to read that specific
- source. With a single source you can skip it — the other tools default to the oldest connected source. The
- prefix also names the underlying warehouse tables (prefix + github_pull_requests / github_workflow_runs /
- github_workflow_jobs), which you can query directly with SQL or save as SQL insights and subscriptions when
- the named tools don't fit (timestamps land as strings; parse with parseDateTimeBestEffort).
+ The team's selectable GitHub repositories, oldest source first — one entry per repository a source syncs,
+ each with its source id, repo (owner/name), table prefix, and a synced flag. A source can sync several
+ repositories, so entries can share an id and differ only by repo. Call this first when a team may have more
+ than one source or repo, then pass a chosen entry's id as source_id AND its repo as repo to the
+ pull-requests, workflow-health, ci-cards, or pr-lifecycle tools to read that specific repo — omitting repo
+ on a multi-repo source reads the source's default repo, not the one you picked. With a single source/repo
+ you can skip it — the other tools default to the oldest connected source. The prefix also names the
+ underlying warehouse tables, which you can query directly with SQL or save as SQL insights and subscriptions
+ when the named tools don't fit. The source's original repo uses bare names (prefix + github_pull_requests /
+ github_workflow_runs / github_workflow_jobs); every other repo of a multi-repo source is repo-qualified —
+ the name `owner/repo.endpoint` is flattened for the table (each '/' becomes '_' and each '.' becomes '__',
+ lower-cased), e.g. posthog/posthog.com's pull_requests is prefix +
+ github_posthog_posthog__com__pull_requests — so pick the table for the repo you mean (timestamps land as
+ strings; parse with parseDateTimeBestEffort).
feature_flag: engineering-analytics
engineering-analytics-team-ci-activity:
operation: engineering_analytics_team_ci_activity
diff --git a/products/warehouse_sources/backend/facade/sources.py b/products/warehouse_sources/backend/facade/sources.py
index 661a1e9584cc..e5429be33f66 100644
--- a/products/warehouse_sources/backend/facade/sources.py
+++ b/products/warehouse_sources/backend/facade/sources.py
@@ -11,6 +11,7 @@ facade import path doesn't drag in DB drivers or the Google client libraries.
from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention
from products.warehouse_sources.backend.temporal.data_imports.sources.github.naming import (
+ schema_repo_endpoint,
split_schema_name as github_split_schema_name,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.constants import (
@@ -21,6 +22,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.con
SUBSCRIPTION_RESOURCE_NAME,
)
+github_schema_repo_endpoint = schema_repo_endpoint
+
__all__ = [
"CHARGE_RESOURCE_NAME",
"CUSTOMER_RESOURCE_NAME",
@@ -29,4 +32,5 @@ __all__ = [
"PRODUCT_RESOURCE_NAME",
"SUBSCRIPTION_RESOURCE_NAME",
"github_split_schema_name",
+ "github_schema_repo_endpoint",
]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/naming.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/naming.py
index 25defa238bec..052e90a39562 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/naming.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/naming.py
@@ -42,13 +42,20 @@ def split_schema_name(schema_name: str) -> tuple[str | None, str]:
return None, schema_name
-def resolve_schema_repo_endpoint(
+def schema_repo_endpoint(
schema_metadata: dict[str, Any] | None,
schema_name: str,
- config: "GithubSourceConfig",
-) -> tuple[str, str]:
- """`(repository, endpoint)` for a schema row: metadata first, qualified-name parse second,
- the config's legacy `repository` for bare rows last."""
+ legacy_repository: str | None,
+) -> tuple[str | None, str]:
+ """Config-free `(repository | None, endpoint)` for a schema row: metadata first,
+ qualified-name parse second, `legacy_repository` for bare rows last.
+
+ Repository is `None` only for a bare row with no legacy repo to attribute it to. Repo
+ names are normalized (stripped, lowercased) since GitHub full names are case-insensitive
+ and the repo half of schema names and webhook keys must compare stably. Shared by the
+ sync-side resolver here and cross-product readers (engineering_analytics) via the facade.
+ Argument order mirrors `resolve_schema_repo_endpoint` (metadata, name) so they don't diverge.
+ """
metadata = schema_metadata if isinstance(schema_metadata, dict) else {}
repository = metadata.get(SCHEMA_METADATA_REPOSITORY_KEY)
endpoint = metadata.get(SCHEMA_METADATA_ENDPOINT_KEY)
@@ -59,11 +66,23 @@ def resolve_schema_repo_endpoint(
if parsed_repository is not None:
return parsed_repository.strip().lower(), parsed_endpoint
- if not config.repository:
+ normalized_legacy = (legacy_repository or "").strip().lower()
+ return (normalized_legacy or None), parsed_endpoint
+
+
+def resolve_schema_repo_endpoint(
+ schema_metadata: dict[str, Any] | None,
+ schema_name: str,
+ config: "GithubSourceConfig",
+) -> tuple[str, str]:
+ """`(repository, endpoint)` for a schema row: metadata first, qualified-name parse second,
+ the config's legacy `repository` for bare rows last."""
+ repository, endpoint = schema_repo_endpoint(schema_metadata, schema_name, config.repository)
+ if repository is None:
# Phrase matches get_non_retryable_errors so an unresolvable row fails permanently
# with the curated message instead of retrying forever.
raise ValueError(f"No repositories configured for schema '{schema_name}'")
- return config.repository.strip().lower(), parsed_endpoint
+ return repository, endpoint
def schema_metadata_for(repository: str, endpoint: str) -> dict[str, str]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
index 7dccdf8cd194..d466e3313cf6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
@@ -1,5 +1,7 @@
import secrets
-from typing import TYPE_CHECKING, Any, Optional, cast
+from collections.abc import Callable
+from concurrent.futures import ThreadPoolExecutor
+from typing import TYPE_CHECKING, Any, Optional, TypeVar, cast
if TYPE_CHECKING:
from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
@@ -71,6 +73,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.github.set
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+_R = TypeVar("_R")
+
# Schemas that can be fed by GitHub webhooks, mapped to the X-GitHub-Event header
# value the webhook handler routes on (schema_mapping is keyed by these values).
GITHUB_WEBHOOK_RESOURCE_MAP: dict[str, str] = {
@@ -523,6 +527,19 @@ If automatic creation failed, your token needs webhook permissions — the **adm
def _webhook_repositories(self, config: GithubSourceConfig) -> list[str]:
return self.effective_repositories(config)
+ # The webhook operations run 1-2 GitHub calls per repo inside synchronous request handlers
+ # (create/delete/info actions, and the repo-list reconcile inside the source PATCH). A source
+ # can carry up to MAX_REPOSITORIES repos, so the per-repo calls fan out on a bounded pool
+ # instead of running serially — capping the repo list here would leave webhooks unmanaged.
+ _WEBHOOK_CONCURRENCY = 8
+
+ def _map_webhook_repositories(self, repositories: list[str], fn: Callable[[str], _R]) -> list[_R]:
+ """Run ``fn`` per repo on a bounded thread pool, preserving repo order."""
+ if len(repositories) <= 1:
+ return [fn(repository) for repository in repositories]
+ with ThreadPoolExecutor(max_workers=min(self._WEBHOOK_CONCURRENCY, len(repositories))) as pool:
+ return list(pool.map(fn, repositories))
+
def ensure_webhooks_for_repositories(
self, config: GithubSourceConfig, webhook_url: str, team_id: int, repositories: list[str], secret: str
) -> list[str]:
@@ -532,14 +549,15 @@ If automatic creation failed, your token needs webhook permissions — the **adm
access_token = self._get_access_token(config, team_id)
egress_identity = self._egress_identity(config, team_id)
events = self.get_desired_webhook_events(config, list(GITHUB_WEBHOOK_RESOURCE_MAP.keys())) or []
- failures: list[str] = []
- for repository in repositories:
- result = ensure_repo_webhook(
+ results = self._map_webhook_repositories(
+ repositories,
+ lambda repository: ensure_repo_webhook(
access_token, repository, webhook_url, events, secret=secret, egress_identity=egress_identity
- )
- if not result.success:
- failures.append(f"{repository}: {result.error}")
- return failures
+ ),
+ )
+ return [
+ f"{repository}: {result.error}" for repository, result in zip(repositories, results) if not result.success
+ ]
def delete_webhooks_for_repositories(
self, config: GithubSourceConfig, webhook_url: str, team_id: int, repositories: list[str]
@@ -548,12 +566,15 @@ If automatic creation failed, your token needs webhook permissions — the **adm
Returns per-repo failure messages (empty on full success)."""
access_token = self._get_access_token(config, team_id)
egress_identity = self._egress_identity(config, team_id)
- failures: list[str] = []
- for repository in repositories:
- result = delete_repo_webhook(access_token, repository, webhook_url, egress_identity=egress_identity)
- if not result.success:
- failures.append(f"{repository}: {result.error}")
- return failures
+ results = self._map_webhook_repositories(
+ repositories,
+ lambda repository: delete_repo_webhook(
+ access_token, repository, webhook_url, egress_identity=egress_identity
+ ),
+ )
+ return [
+ f"{repository}: {result.error}" for repository, result in zip(repositories, results) if not result.success
+ ]
def create_webhook(self, config: GithubSourceConfig, webhook_url: str, team_id: int) -> WebhookCreationResult:
access_token = self._get_access_token(config, team_id)
@@ -568,16 +589,17 @@ If automatic creation failed, your token needs webhook permissions — the **adm
# out under runs so the workflow pair travels together, and an unmapped event no-ops in the
# hog function anyway, so over-subscribing is harmless while enabling a table later is free.
events = self.get_desired_webhook_events(config, list(GITHUB_WEBHOOK_RESOURCE_MAP.keys())) or []
- failures: list[str] = []
- any_success = False
- for repository in self._webhook_repositories(config):
- result = ensure_repo_webhook(
+ repositories = self._webhook_repositories(config)
+ results = self._map_webhook_repositories(
+ repositories,
+ lambda repository: ensure_repo_webhook(
access_token, repository, webhook_url, events, secret=secret, egress_identity=egress_identity
- )
- if result.success:
- any_success = True
- else:
- failures.append(f"{repository}: {result.error}")
+ ),
+ )
+ any_success = any(result.success for result in results)
+ failures = [
+ f"{repository}: {result.error}" for repository, result in zip(repositories, results) if not result.success
+ ]
if not failures:
return WebhookCreationResult(success=True, extra_inputs={"signing_secret": secret})
# Partial success still persists the secret: the repos that did get a hook must verify
@@ -603,13 +625,16 @@ If automatic creation failed, your token needs webhook permissions — the **adm
# installation identity so the hook list and PATCH draw from the same shared egress
# budget as the data plane; PAT sources resolve to an empty identity (record-only).
desired_events = self.get_desired_webhook_events(config, list(GITHUB_WEBHOOK_RESOURCE_MAP.keys())) or []
- failures: list[str] = []
- for repository in self._webhook_repositories(config):
- result = update_repo_webhook(
+ repositories = self._webhook_repositories(config)
+ results = self._map_webhook_repositories(
+ repositories,
+ lambda repository: update_repo_webhook(
access_token, repository, webhook_url, desired_events, egress_identity=egress_identity
- )
- if not result.success:
- failures.append(f"{repository}: {result.error}")
+ ),
+ )
+ failures = [
+ f"{repository}: {result.error}" for repository, result in zip(repositories, results) if not result.success
+ ]
if not failures:
return WebhookSyncResult(success=True)
return WebhookSyncResult(success=False, error="; ".join(failures))
@@ -617,11 +642,16 @@ If automatic creation failed, your token needs webhook permissions — the **adm
def delete_webhook(self, config: GithubSourceConfig, webhook_url: str, team_id: int) -> WebhookDeletionResult:
access_token = self._get_access_token(config, team_id)
egress_identity = self._egress_identity(config, team_id)
- failures: list[str] = []
- for repository in self._webhook_repositories(config):
- result = delete_repo_webhook(access_token, repository, webhook_url, egress_identity=egress_identity)
- if not result.success:
- failures.append(f"{repository}: {result.error}")
+ repositories = self._webhook_repositories(config)
+ results = self._map_webhook_repositories(
+ repositories,
+ lambda repository: delete_repo_webhook(
+ access_token, repository, webhook_url, egress_identity=egress_identity
+ ),
+ )
+ failures = [
+ f"{repository}: {result.error}" for repository, result in zip(repositories, results) if not result.success
+ ]
if not failures:
return WebhookDeletionResult(success=True)
return WebhookDeletionResult(success=False, error="; ".join(failures))
@@ -637,8 +667,14 @@ If automatic creation failed, your token needs webhook permissions — the **adm
errors: list[str] = []
merged_events: set[str] = set()
first_info: ExternalWebhookInfo | None = None
- for repository in self._webhook_repositories(config):
- info = get_repo_webhook_info(access_token, repository, webhook_url, egress_identity=egress_identity)
+ repositories = self._webhook_repositories(config)
+ infos = self._map_webhook_repositories(
+ repositories,
+ lambda repository: get_repo_webhook_info(
+ access_token, repository, webhook_url, egress_identity=egress_identity
+ ),
+ )
+ for repository, info in zip(repositories, infos):
if info.error:
errors.append(f"{repository}: {info.error}")
elif not info.exists:
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 22251bed9118..89b16856cc14 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2741,7 +2741,7 @@
"feature_flag": "engineering-analytics"
},
"engineering-analytics-sources": {
- "description": "The team's connected GitHub data warehouse sources, oldest first, each with its id, repo (owner/name), and table prefix. Call this first when a team may have more than one GitHub source, then pass a chosen id as source_id to the pull-requests, workflow-health, ci-cards, or pr-lifecycle tools to read that specific source. With a single source you can skip it — the other tools default to the oldest connected source. The prefix also names the underlying warehouse tables (prefix + github_pull_requests / github_workflow_runs / github_workflow_jobs), which you can query directly with SQL or save as SQL insights and subscriptions when the named tools don't fit (timestamps land as strings; parse with parseDateTimeBestEffort).",
+ "description": "The team's selectable GitHub repositories, oldest source first — one entry per repository a source syncs, each with its source id, repo (owner/name), table prefix, and a synced flag. A source can sync several repositories, so entries can share an id and differ only by repo. Call this first when a team may have more than one source or repo, then pass a chosen entry's id as source_id AND its repo as repo to the pull-requests, workflow-health, ci-cards, or pr-lifecycle tools to read that specific repo — omitting repo on a multi-repo source reads the source's default repo, not the one you picked. With a single source/repo you can skip it — the other tools default to the oldest connected source. The prefix also names the underlying warehouse tables, which you can query directly with SQL or save as SQL insights and subscriptions when the named tools don't fit. The source's original repo uses bare names (prefix + github_pull_requests / github_workflow_runs / github_workflow_jobs); every other repo of a multi-repo source is repo-qualified — the name `owner/repo.endpoint` is flattened for the table (each '/' becomes '_' and each '.' becomes '__', lower-cased), e.g. posthog/posthog.com's pull_requests is prefix + github_posthog_posthog__com__pull_requests — so pick the table for the repo you mean (timestamps land as strings; parse with parseDateTimeBestEffort).",
"category": "Engineering analytics",
"feature": "engineering_analytics",
"summary": "List connected GitHub sources",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index eed37d4a31e6..cb5d5e759fe1 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2784,7 +2784,7 @@
"feature_flag": "engineering-analytics"
},
"engineering-analytics-sources": {
- "description": "The team's connected GitHub data warehouse sources, oldest first, each with its id, repo (owner/name), and table prefix. Call this first when a team may have more than one GitHub source, then pass a chosen id as source_id to the pull-requests, workflow-health, ci-cards, or pr-lifecycle tools to read that specific source. With a single source you can skip it — the other tools default to the oldest connected source. The prefix also names the underlying warehouse tables (prefix + github_pull_requests / github_workflow_runs / github_workflow_jobs), which you can query directly with SQL or save as SQL insights and subscriptions when the named tools don't fit (timestamps land as strings; parse with parseDateTimeBestEffort).",
+ "description": "The team's selectable GitHub repositories, oldest source first — one entry per repository a source syncs, each with its source id, repo (owner/name), table prefix, and a synced flag. A source can sync several repositories, so entries can share an id and differ only by repo. Call this first when a team may have more than one source or repo, then pass a chosen entry's id as source_id AND its repo as repo to the pull-requests, workflow-health, ci-cards, or pr-lifecycle tools to read that specific repo — omitting repo on a multi-repo source reads the source's default repo, not the one you picked. With a single source/repo you can skip it — the other tools default to the oldest connected source. The prefix also names the underlying warehouse tables, which you can query directly with SQL or save as SQL insights and subscriptions when the named tools don't fit. The source's original repo uses bare names (prefix + github_pull_requests / github_workflow_runs / github_workflow_jobs); every other repo of a multi-repo source is repo-qualified — the name `owner/repo.endpoint` is flattened for the table (each '/' becomes '_' and each '.' becomes '__', lower-cased), e.g. posthog/posthog.com's pull_requests is prefix + github_posthog_posthog__com__pull_requests — so pick the table for the repo you mean (timestamps land as strings; parse with parseDateTimeBestEffort).",
"category": "Engineering analytics",
"feature": "engineering_analytics",
"summary": "List connected GitHub sources",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 498034ed544b..bd0e68b4542f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -29123,12 +29123,14 @@ export namespace Schemas {
}
export interface GitHubSource {
- /** Source id — pass as `source_id` to the other endpoints to read this source. */
+ /** Source id — pass back as `source_id` (with `repo`) to read this repository. */
id: string;
- /** Connected repository as 'owner/name', or '' if unknown. */
+ /** Repository as 'owner/name' — pass back as `repo` to scope to it. One entry per repository a source syncs; '' if unknown. */
repo: string;
/** User-chosen warehouse table-name prefix for this source, or '' when none. */
prefix: string;
+ /** Whether this repo has both pull_requests and workflow_runs synced (readable now). Default the picker to the first synced entry so its label matches the resolved repo. */
+ synced?: boolean;
}
export interface GitHubTeam {
@@ -73040,6 +73042,10 @@ export namespace Schemas {
* Window end: relative or ISO8601. Defaults to now.
*/
date_to?: string;
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string;
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -73047,6 +73053,10 @@ export namespace Schemas {
};
export type EngineeringAnalyticsBrokenTestsParams = {
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string;
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -73054,6 +73064,10 @@ export namespace Schemas {
};
export type EngineeringAnalyticsCiCardsParams = {
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string;
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -73076,6 +73090,10 @@ export namespace Schemas {
};
export type EngineeringAnalyticsCurrentBranchHealthParams = {
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string;
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -73103,6 +73121,10 @@ export namespace Schemas {
* A test qualifies once it passed on retry at least this many times in the window (OR-ed with min_failed_prs). Minimum 1. Defaults to 1.
*/
min_rerun_passes?: number;
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string;
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -73122,6 +73144,10 @@ export namespace Schemas {
* Window end: relative or ISO8601. Defaults to now.
*/
date_to?: string;
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string;
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -73145,6 +73171,10 @@ export namespace Schemas {
* Window end: relative or ISO8601. Defaults to now.
*/
date_to?: string;
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string;
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -73205,6 +73235,10 @@ export namespace Schemas {
* Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
*/
date_from?: string;
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string;
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -73235,6 +73269,10 @@ export namespace Schemas {
* Set false to skip the chart series (cost_series, time_to_green_series, success_rate_series, open_to_merge_series return empty) and their query cost — for headline-only consumers like the weekly digest. Defaults to true.
*/
include_series?: boolean;
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string;
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -73254,6 +73292,10 @@ export namespace Schemas {
* Window end: relative or ISO8601. Defaults to now.
*/
date_to?: string;
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string;
/**
* Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
*/
@@ -73280,6 +73322,10 @@ export namespace Schemas {
};
export type EngineeringAnalyticsRunFailureLogsParams = {
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string;
/**
* Workflow run id whose failure logs to fetch.
*/
@@ -73372,6 +73418,10 @@ export namespace Schemas {
* Window end: relative or ISO8601. Defaults to now.
*/
date_to?: string;
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string;
/**
* Run scope for workflow health: 'all' (default) includes every run; 'pull_request' includes runs attributed to pull requests, excluding default-branch (master/main) runs. Fork PRs carry no PR attribution (a GitHub limitation), so 'pull_request' covers same-repo PRs only. Any other value is a 400.
*/
@@ -73391,6 +73441,10 @@ export namespace Schemas {
} as const;
export type EngineeringAnalyticsWorkflowJobsParams = {
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string;
/**
* Which re-run attempt to scope jobs to. Omit to use the run's latest attempt; pass an explicit attempt to avoid mixing jobs across a re-run's attempts.
*/
@@ -73406,6 +73460,10 @@ export namespace Schemas {
};
export type EngineeringAnalyticsWorkflowRunParams = {
+ /**
+ * 'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository.
+ */
+ repo?: string;
/**
* GitHub Actions run id to inspect.
*/
diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.ts
index 59f25cca43c8..415dfd85edfe 100644
--- a/services/mcp/src/generated/engineering_analytics/api.ts
+++ b/services/mcp/src/generated/engineering_analytics/api.ts
@@ -20,6 +20,12 @@ export const EngineeringAnalyticsBrokenTestsParams = /* @__PURE__ */ zod.object(
})
export const EngineeringAnalyticsBrokenTestsQueryParams = /* @__PURE__ */ zod.object({
+ repo: zod
+ .string()
+ .optional()
+ .describe(
+ "'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository."
+ ),
source_id: zod
.string()
.optional()
@@ -82,6 +88,12 @@ export const EngineeringAnalyticsFlakyTestsQueryParams = /* @__PURE__ */ zod.obj
.describe(
'A test qualifies once it passed on retry at least this many times in the window (OR-ed with min_failed_prs). Minimum 1. Defaults to 1.'
),
+ repo: zod
+ .string()
+ .optional()
+ .describe(
+ "'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository."
+ ),
source_id: zod
.string()
.optional()
@@ -148,6 +160,12 @@ export const EngineeringAnalyticsPullRequestsParams = /* @__PURE__ */ zod.object
export const EngineeringAnalyticsPullRequestsQueryParams = /* @__PURE__ */ zod.object({
author: zod.string().optional().describe("Optional GitHub login to scope the list to one author's pull requests."),
date_from: zod.string().optional().describe("Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d."),
+ repo: zod
+ .string()
+ .optional()
+ .describe(
+ "'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository."
+ ),
source_id: zod
.string()
.optional()
@@ -168,6 +186,12 @@ export const EngineeringAnalyticsRunFailureLogsParams = /* @__PURE__ */ zod.obje
})
export const EngineeringAnalyticsRunFailureLogsQueryParams = /* @__PURE__ */ zod.object({
+ repo: zod
+ .string()
+ .optional()
+ .describe(
+ "'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository."
+ ),
run_id: zod.number().describe('Workflow run id whose failure logs to fetch.'),
source_id: zod
.string()
@@ -178,7 +202,7 @@ export const EngineeringAnalyticsRunFailureLogsQueryParams = /* @__PURE__ */ zod
})
/**
- * The team's connected GitHub data warehouse sources, oldest first. Populate a source picker from this and pass a chosen `id` back as `source_id` to the other endpoints. A team can connect GitHub more than once (e.g. one source per repository); this lists them all, including any whose tables aren't fully synced yet.
+ * The team's selectable GitHub repositories, oldest source first — one entry per repository a source is configured to sync, so a source syncing several repositories appears once per repo. Populate a repo picker from this and pass a chosen entry's `id` back as `source_id` and its `repo` back as `repo` to the other endpoints. Includes repositories whose tables aren't fully synced yet.
*/
export const EngineeringAnalyticsSourcesParams = /* @__PURE__ */ zod.object({
project_id: zod
@@ -248,6 +272,12 @@ export const EngineeringAnalyticsWorkflowHealthQueryParams = /* @__PURE__ */ zod
),
date_from: zod.string().optional().describe("Window start: relative ('-24h', '-7d') or ISO8601. Defaults to -24h."),
date_to: zod.string().optional().describe('Window end: relative or ISO8601. Defaults to now.'),
+ repo: zod
+ .string()
+ .optional()
+ .describe(
+ "'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository."
+ ),
run_scope: zod
.enum(['all', 'pull_request'])
.optional()
@@ -274,6 +304,12 @@ export const EngineeringAnalyticsWorkflowJobsParams = /* @__PURE__ */ zod.object
})
export const EngineeringAnalyticsWorkflowJobsQueryParams = /* @__PURE__ */ zod.object({
+ repo: zod
+ .string()
+ .optional()
+ .describe(
+ "'owner/name' repository to scope to when the selected source syncs several repositories (from the `sources` list). Defaults to the source's first repository."
+ ),
run_attempt: zod
.number()
.optional()
diff --git a/services/mcp/src/tools/generated/engineering_analytics.ts b/services/mcp/src/tools/generated/engineering_analytics.ts
index 0647984767a5..adedb5d29078 100644
--- a/services/mcp/src/tools/generated/engineering_analytics.ts
+++ b/services/mcp/src/tools/generated/engineering_analytics.ts
@@ -32,6 +32,7 @@ const engineeringAnalyticsBrokenTests = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/broken_tests/`,
query: {
+ repo: params.repo,
source_id: params.source_id,
},
})
@@ -81,6 +82,7 @@ const engineeringAnalyticsFlakyTests = (): ToolBase<
limit: params.limit,
min_failed_prs: params.min_failed_prs,
min_rerun_passes: params.min_rerun_passes,
+ repo: params.repo,
source_id: params.source_id,
},
})
@@ -122,6 +124,7 @@ const engineeringAnalyticsRunFailureLogs = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/run_failure_logs/`,
query: {
+ repo: params.repo,
run_id: params.run_id,
source_id: params.source_id,
},
@@ -189,6 +192,7 @@ const engineeringAnalyticsWorkflowJobs = (): ToolBase<
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/engineering_analytics/workflow_jobs/`,
query: {
+ repo: params.repo,
run_attempt: params.run_attempt,
run_id: params.run_id,
source_id: params.source_id,
@@ -261,6 +265,7 @@ const pullRequests = (): ToolBase<typeof PullRequestsSchema, WithPostHogUrl<Sche
query: {
author: params.author,
date_from: params.date_from,
+ repo: params.repo,
source_id: params.source_id,
},
})
@@ -292,6 +297,7 @@ const workflowHealth = (): ToolBase<typeof WorkflowHealthSchema, WithPostHogUrl<
branch: params.branch,
date_from: params.date_from,
date_to: params.date_to,
+ repo: params.repo,
run_scope: params.run_scope,
source_id: params.source_id,
},