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(codacy): sync people, tools, patterns, commit deltas and metrics (#103350)

Tom Owers6bbc94fa5128
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index e950e3b5ee10..28056265ef6d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1723,14 +1723,14 @@ Note: Coda has been rebranded to Superhuman Docs, but the OpenAPI spec is still
## Codacy — **thin**
-Today (6): `commits`, `files`, `issues`, `organizations`, `pull_requests`, `repositories`
+Today (11): `commit_delta_issues`, `commits`, `files`, `issues`, `metrics_timerange`, `organizations`, `people`, `pull_requests`, `repositories`, `tool_patterns`, `tools`
Diffed against: <https://api.codacy.com/api/api-docs/swagger.yaml>
-- [ ] `/organizations/{provider}/{org}/people` — Org member lookup resolving the author identities attached to the commits and pull requests already synced (high)
-- [ ] `/tools and /tools/{toolUuid}/patterns` — Lookup that resolves the toolUuid and patternId every synced issue carries - without it issues cannot be grouped by rule or linter (high)
-- [ ] `/analysis/organizations/{provider}/{org}/repositories/{repo}/commits/{commitUuid}/deltaStatistics and /commits/{srcCommitUuid}/deltaIssues` — New vs fixed issues introduced by each commit - the change-over-time signal the flat issues table cannot produce (high)
-- [ ] `/organizations/{provider}/{org}/metrics/{metricName}/period, /period-grouped, /timerange` — Org-level quality metric time series (Codacy's dashboard numbers) precomputed per period (high)
+- [x] `/organizations/{provider}/{org}/people` — Org member lookup resolving the author identities attached to the commits and pull requests already synced (high)
+- [x] `/tools and /tools/{toolUuid}/patterns` — Lookup that resolves the toolUuid and patternId every synced issue carries - without it issues cannot be grouped by rule or linter (high)
+- [x] `/analysis/organizations/{provider}/{org}/repositories/{repo}/commits/{commitUuid}/deltaStatistics and /commits/{srcCommitUuid}/deltaIssues` — New vs fixed issues introduced by each commit - the change-over-time signal the flat issues table cannot produce (high) — `deltaIssues` synced as `commit_delta_issues`; `deltaStatistics` skipped, its counts are already on `commits` under `quality`
+- [x] `/organizations/{provider}/{org}/metrics/{metricName}/period, /period-grouped, /timerange` — Org-level quality metric time series (Codacy's dashboard numbers) precomputed per period (high) — `/timerange` synced as `metrics_timerange`; `/period` and `/period-grouped` skipped, they return a single period's value that `/timerange` already covers
- [ ] `/organizations/{provider}/{org}/security/items and /security/items/search` — Security issues (SRM) with severity and SLA state - an entire product area with no synced table (high)
- [ ] `/analysis/organizations/{provider}/{org}/repositories/{repo}/commit-statistics` — Per-repo commit statistics over time, giving repo health a trend rather than a snapshot (medium)
- [ ] `/analysis/organizations/{provider}/{org}/repositories/{repo}/category-overviews and /issues/overview` — Issue counts broken down by category and severity - the standard reporting breakdown dimensions (medium)
@@ -1740,7 +1740,7 @@ Diffed against: <https://api.codacy.com/api/api-docs/swagger.yaml>
- [ ] `/organizations/{provider}/{org}/repositories/{repo}/files/{fileId}/coverage and /files/{fileId}/duplication` — File-level coverage and duplication metrics that enrich the files table already synced (medium)
- [ ] `/organizations/{provider}/{org}/audit` — Audit log of org and repo configuration changes, useful for correlating quality shifts with settings changes (low)
-Note: Codacy API v3 swagger is served at https://api.codacy.com/api/api-docs/swagger.yaml (~250 paths). Six static endpoints in codacy/settings.py, no dynamic discovery. Whole product domains are unrepresented: security/SRM, SBOM, org metrics time series, and coverage. Excluded config surfaces (coding-standards, gate-policies, settings/\*, tokens, integrations).
+Note: Codacy API v3 swagger is served at https://api.codacy.com/api/api-docs/swagger.yaml (~250 paths). Eleven static endpoints in codacy/settings.py, no dynamic discovery. Whole product domains are still unrepresented: security/SRM, SBOM, and coverage. Excluded config surfaces (coding-standards, gate-policies, settings/\*, tokens, integrations).
## Codecov — gaps
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/canonical_descriptions.py
index 488865e4fd50..3d48d80fc392 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/canonical_descriptions.py
@@ -129,4 +129,103 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"coverage": "Coverage analysis results for the commit.",
},
},
+ "people": {
+ "description": "People in the organization on Codacy: members and the commit authors Codacy saw, resolving the author identities on the commits and pull requests already synced.",
+ "docs_url": "https://api.codacy.com/api/api-docs#listpeoplefromorganization",
+ "columns": {
+ "name": "Name of the person.",
+ "email": "Primary email address of the person.",
+ "emails": "All email addresses Codacy knows for the person.",
+ "userId": "User ID internal to Codacy. Null for commit authors who aren't Codacy users.",
+ "committerId": "Commit author ID.",
+ "lastLogin": "Timestamp when the person last logged in to Codacy.",
+ "lastAnalysis": "Timestamp when Codacy last analyzed a commit from this person.",
+ "isActive": "True if the person is an active committer on Codacy.",
+ "canBeRemoved": "True if the person can be removed from the organization.",
+ "lastCommitId": "Identifier of the last commit by the person.",
+ "providerId": "ID of the person on the Git provider.",
+ "providerLogin": "Username of the person on the Git provider.",
+ "isProviderRegistered": "True if the person is registered on the Git provider.",
+ },
+ },
+ "commit_delta_issues": {
+ "description": "Issues that each analyzed commit introduced or fixed, compared against its parent commit. Unlike the issues table, which holds the issues currently open, this records the change each commit made.",
+ "docs_url": "https://api.codacy.com/api/api-docs#listcommitdeltaissues",
+ "columns": {
+ "repository": "Name of the repository the commit belongs to.",
+ "commitSha": "SHA of the commit that introduced or fixed the issue.",
+ "deltaType": "Whether the commit added or fixed the issue.",
+ "issueId": "ID of the issue.",
+ "resultDataId": "Stable ID for the issue.",
+ "filePath": "Path of the file where the issue was found.",
+ "fileId": "Identifier of the file where the issue was found.",
+ "patternInfo": "Details of the code pattern that detected the issue, including category and severity level.",
+ "toolInfo": "Details of the tool that detected the issue.",
+ "lineNumber": "Line where the issue was found.",
+ "message": "Detailed cause of the issue.",
+ "suggestion": "The suggested fix for the issue.",
+ "language": "Language of the file where the issue was found.",
+ "lineText": "Contents of the line where the issue was found.",
+ "commitInfo": "Details of the commit that originated the issue.",
+ },
+ },
+ "tools": {
+ "description": "Codacy's catalog of static analysis tools, resolving the tool UUID carried by every issue row. The catalog is the same for every Codacy account.",
+ "docs_url": "https://api.codacy.com/api/api-docs#listtools",
+ "columns": {
+ "uuid": "Tool unique identifier.",
+ "name": "Name of the tool.",
+ "shortName": "Tool unique short name.",
+ "version": "Original tool version used by the Codacy tool wrapper.",
+ "documentationUrl": "Original tool documentation URL.",
+ "sourceCodeUrl": "Codacy tool wrapper source code URL.",
+ "prefix": "Tool prefix used to make pattern names unique.",
+ "needsCompilation": "True if the tool requires compilation to run.",
+ "configurationFilenames": "Configuration filenames the tool reads.",
+ "description": "Tool description.",
+ "dockerImage": "Docker image used to launch the tool.",
+ "languages": "Languages the tool supports.",
+ "clientSide": "True if the tool runs on the client machine and sends results to Codacy.",
+ "standalone": "True if the client-side tool runs outside of the Codacy CLI.",
+ "enabledByDefault": "True if the tool is enabled by default for new repositories.",
+ "configurable": "True if the tool is configurable on Codacy's UI.",
+ },
+ },
+ "tool_patterns": {
+ "description": "Code patterns (rules) each Codacy tool can flag, resolving the pattern ID carried by every issue row so issues can be grouped by rule, category, and severity.",
+ "docs_url": "https://api.codacy.com/api/api-docs#listpatterns",
+ "columns": {
+ "toolUuid": "Unique identifier of the tool that owns the pattern.",
+ "id": "Pattern identifier, unique per tool.",
+ "title": "Pattern title.",
+ "category": "Pattern category.",
+ "subCategory": "Pattern subcategory, when the pattern has one.",
+ "level": "Deprecated severity of the pattern. Use severityLevel instead.",
+ "severityLevel": "Severity of the issues the pattern detects: Info, Warning, High, or Error.",
+ "description": "Short description of the code pattern.",
+ "explanation": "Full description of the code pattern, in CommonMark.",
+ "enabled": "True if the pattern is on by default for new repositories.",
+ "languages": "Languages the pattern supports.",
+ "timeToFix": "Average time to fix an issue the pattern detects, in minutes.",
+ "parameters": "Configurable parameters of the pattern.",
+ "rationale": "Rationale for the pattern.",
+ "solution": "Suggested solution for issues the pattern detects.",
+ "goodExamples": "Examples of code that satisfies the pattern.",
+ "badExamples": "Examples of code that violates the pattern.",
+ "tags": "Tags associated with the pattern.",
+ },
+ },
+ "metrics_timerange": {
+ "description": "Organization quality metrics over time, broken down by repository. These are the precomputed numbers behind Codacy's own dashboards, one row per metric, period, and repository.",
+ "docs_url": "https://api.codacy.com/api/api-docs#retrievetimerangemetricvalues",
+ "columns": {
+ "metricName": "Name of the metric, such as openissues.",
+ "date": "Start date of the period the value covers.",
+ "organization": "Name of the organization the value belongs to.",
+ "repository": "Name of the repository the value belongs to. Empty when the value isn't broken down per repository.",
+ "dimensions": "Additional dimensions the value is grouped by, such as issue category or severity.",
+ "value": "Value of the metric for the period. Aggregating metrics give the average, accumulating metrics give the sum.",
+ "latestValue": "Most recent value of the metric.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/codacy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/codacy.py
index c82155cdbe39..60ee78f9b450 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/codacy.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/codacy.py
@@ -1,4 +1,5 @@
from collections.abc import Iterator
+from datetime import UTC, datetime, timedelta
from typing import Any, Optional
from urllib.parse import urlencode
@@ -6,7 +7,12 @@ import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
-from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.settings import CODACY_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.settings import (
+ CODACY_ENDPOINTS,
+ METRICS_LOOKBACK_DAYS,
+ METRICS_PERIOD,
+ CodacyEndpointConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -46,11 +52,13 @@ def _fetch_page(
url: str,
headers: dict[str, str],
logger: FilteringBoundLogger,
+ body: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
if method == "POST":
# searchRepositoryIssues takes its filters in the body; an empty filter returns every
- # current issue. Pagination params stay in the query string.
- response = session.post(url, headers=headers, json={}, timeout=REQUEST_TIMEOUT_SECONDS)
+ # current issue. The metrics time series requires a populated body. Pagination params
+ # stay in the query string either way.
+ response = session.post(url, headers=headers, json=body or {}, timeout=REQUEST_TIMEOUT_SECONDS)
else:
response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
@@ -59,8 +67,8 @@ def _fetch_page(
raise CodacyRetryableError(f"Codacy API error (retryable): status={response.status_code}, url={url}")
if not response.ok:
- # 404 during a repository fan-out is expected (repository removed from Codacy mid-sync)
- # and handled by the caller; anything else is a hard failure.
+ # 404 during a fan-out is expected (the parent was removed from Codacy mid-sync) and
+ # handled by the caller; anything else is a hard failure.
log = logger.warning if response.status_code == 404 else logger.error
log(f"Codacy API error: status={response.status_code}, body={response.text}, url={url}")
response.raise_for_status()
@@ -69,6 +77,8 @@ def _fetch_page(
def _build_url(path: str, params: dict[str, Any]) -> str:
+ if not params:
+ return f"{CODACY_BASE_URL}{path}"
return f"{CODACY_BASE_URL}{path}?{urlencode(params)}"
@@ -80,6 +90,7 @@ def _paginate(
method: str = "GET",
extra_params: Optional[dict[str, str]] = None,
max_pages: Optional[int] = None,
+ body: Optional[dict[str, Any]] = None,
) -> Iterator[list[dict[str, Any]]]:
"""Yield one list of items per page, following Codacy's cursor pagination.
@@ -94,7 +105,7 @@ def _paginate(
if cursor:
params["cursor"] = cursor
- data = _fetch_page(session, method, _build_url(path, params), headers, logger)
+ data = _fetch_page(session, method, _build_url(path, params), headers, logger, body)
items = data.get("data", [])
if items:
yield items
@@ -109,21 +120,44 @@ def _paginate(
break
-def _normalize_item(endpoint: str, item: dict[str, Any], repository: Optional[str] = None) -> dict[str, Any]:
- """Lift the envelope's entity object to the top level and stamp the repository name onto
- fan-out rows, so primary keys are plain top-level columns."""
+def _normalize_item(endpoint: str, item: dict[str, Any], stamp: Optional[dict[str, Any]] = None) -> dict[str, Any]:
+ """Lift the envelope's entity object to the top level and stamp the fan-out parent's
+ identifiers onto the row, so primary keys are plain top-level columns."""
+ stamp = stamp or {}
if endpoint == "repositories":
nested = item.pop("repository", None) or {}
return {**nested, **item}
if endpoint == "pull_requests":
nested = item.pop("pullRequest", None) or {}
- return {"repository": repository, **nested, **item}
+ return {**stamp, **nested, **item}
if endpoint == "commits":
nested = item.pop("commit", None) or {}
- return {"repository": repository, **nested, **item}
- if repository is not None:
- return {"repository": repository, **item}
- return item
+ return {**stamp, **nested, **item}
+ if endpoint == "commit_delta_issues":
+ nested = item.pop("commitIssue", None) or {}
+ return {**stamp, **nested, **item}
+ if endpoint == "metrics_timerange":
+ group = item.pop("group", None) or {}
+ return {
+ **stamp,
+ "organization": group.get("organization"),
+ # A null key column never matches on merge, so an ungrouped value would be
+ # re-inserted on every sync; key it on an empty repository name instead.
+ "repository": group.get("repository") or "",
+ "dimensions": group.get("dimensions"),
+ **item,
+ }
+ return {**stamp, **item}
+
+
+def _skip_missing_parent(
+ exc: requests.HTTPError, logger: FilteringBoundLogger, endpoint: str, description: str
+) -> None:
+ """Swallow a 404 raised while fetching a fan-out parent's children; re-raise anything else."""
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Codacy: {description} not found while fetching {endpoint}, skipping")
+ return
+ raise exc
def _iter_repository_names(
@@ -141,27 +175,83 @@ def _iter_repository_names(
yield name
-def get_rows(
- api_token: str,
+def _iter_tool_uuids(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> Iterator[str]:
+ for page in _paginate(session, headers, logger, "/tools"):
+ for tool in page:
+ uuid = tool.get("uuid")
+ if uuid:
+ yield uuid
+
+
+def _collect_commit_shas(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
provider: str,
organization: str,
- endpoint: str,
+ repository: str,
+ limit: int,
+) -> list[str]:
+ path = f"/analysis/organizations/{provider}/{organization}/repositories/{repository}/commits"
+ shas: list[str] = []
+ for page in _paginate(session, headers, logger, path):
+ for entry in page:
+ sha = (entry.get("commit") or {}).get("sha")
+ if sha:
+ shas.append(sha)
+ if len(shas) >= limit:
+ logger.warning(
+ f"Codacy: commit cap reached for repository={repository}, max_commits={limit}; "
+ "older commits are not expanded"
+ )
+ return shas
+ return shas
+
+
+def _list_ready_metrics(
+ session: requests.Session,
+ headers: dict[str, str],
logger: FilteringBoundLogger,
-) -> Iterator[list[dict[str, Any]]]:
- endpoint_config = CODACY_ENDPOINTS[endpoint]
- headers = _get_headers(api_token)
- # One session reused across every page (and repository) so urllib3 keeps the connection
- # alive instead of re-handshaking per request. The token rides the custom `api-token`
- # header, which the capture pipeline's name-based denylist doesn't know, so redact it
- # by value.
- session = make_tracked_session(redact_values=(api_token,))
+ provider: str,
+ organization: str,
+) -> list[str]:
+ path = f"/organizations/{provider}/{organization}/metrics/ready"
+ try:
+ data = _fetch_page(session, "GET", _build_url(path, {}), headers, logger)
+ except requests.HTTPError as exc:
+ # Metrics are an opt-in Codacy feature; an organization without it answers 403/404 here.
+ # Sync an empty table rather than failing the schema.
+ if exc.response is not None and exc.response.status_code in (403, 404):
+ logger.warning(f"Codacy: no metrics available for organization {organization}, skipping")
+ return []
+ raise
+ return (data.get("data") or {}).get("readyMetrics") or []
+
+
+def _metrics_request_body() -> dict[str, Any]:
+ today = datetime.now(UTC).date()
+ return {
+ "filter": {"entityFilter": {}},
+ "groupBy": {"groupBy": ["repository"]},
+ "from": (today - timedelta(days=METRICS_LOOKBACK_DAYS)).isoformat(),
+ "to": today.isoformat(),
+ "period": METRICS_PERIOD,
+ }
- if not endpoint_config.fan_out_per_repository:
- path = endpoint_config.path.format(provider=provider, organization=organization)
- for page in _paginate(session, headers, logger, path, endpoint_config.method, endpoint_config.extra_params):
- yield [_normalize_item(endpoint, item) for item in page]
- return
+def _fan_out_over_repositories(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ provider: str,
+ organization: str,
+ endpoint_config: CodacyEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ endpoint = endpoint_config.name
for repository in _iter_repository_names(session, headers, logger, provider, organization):
path = endpoint_config.path.format(provider=provider, organization=organization, repository=repository)
try:
@@ -172,16 +262,137 @@ def get_rows(
path,
endpoint_config.method,
endpoint_config.extra_params,
- max_pages=endpoint_config.max_pages_per_repository,
+ max_pages=endpoint_config.max_pages_per_parent,
):
- yield [_normalize_item(endpoint, item, repository=repository) for item in page]
+ yield [_normalize_item(endpoint, item, {"repository": repository}) for item in page]
+ except requests.HTTPError as exc:
+ _skip_missing_parent(exc, logger, endpoint, f"repository {repository}")
+
+
+def _fan_out_over_commits(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ provider: str,
+ organization: str,
+ endpoint_config: CodacyEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ endpoint = endpoint_config.name
+ for repository in _iter_repository_names(session, headers, logger, provider, organization):
+ try:
+ shas = _collect_commit_shas(
+ session,
+ headers,
+ logger,
+ provider,
+ organization,
+ repository,
+ endpoint_config.max_commits_per_repository,
+ )
except requests.HTTPError as exc:
- # A repository removed from Codacy between enumeration and this fetch 404s; skip it
- # rather than failing the whole sync. Anything else is re-raised.
- if exc.response is not None and exc.response.status_code == 404:
- logger.warning(f"Codacy: repository {repository} not found while fetching {endpoint}, skipping")
- else:
- raise
+ _skip_missing_parent(exc, logger, endpoint, f"repository {repository}")
+ continue
+
+ for sha in shas:
+ path = endpoint_config.path.format(
+ provider=provider, organization=organization, repository=repository, commit=sha
+ )
+ try:
+ for page in _paginate(
+ session,
+ headers,
+ logger,
+ path,
+ endpoint_config.method,
+ endpoint_config.extra_params,
+ max_pages=endpoint_config.max_pages_per_parent,
+ ):
+ yield [
+ _normalize_item(endpoint, item, {"repository": repository, "commitSha": sha}) for item in page
+ ]
+ except requests.HTTPError as exc:
+ _skip_missing_parent(exc, logger, endpoint, f"commit {sha} of repository {repository}")
+
+
+def _fan_out_over_tools(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ endpoint_config: CodacyEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ endpoint = endpoint_config.name
+ for tool_uuid in _iter_tool_uuids(session, headers, logger):
+ path = endpoint_config.path.format(tool_uuid=tool_uuid)
+ try:
+ for page in _paginate(
+ session,
+ headers,
+ logger,
+ path,
+ endpoint_config.method,
+ endpoint_config.extra_params,
+ max_pages=endpoint_config.max_pages_per_parent,
+ ):
+ yield [_normalize_item(endpoint, item, {"toolUuid": tool_uuid}) for item in page]
+ except requests.HTTPError as exc:
+ _skip_missing_parent(exc, logger, endpoint, f"tool {tool_uuid}")
+
+
+def _fan_out_over_metrics(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ provider: str,
+ organization: str,
+ endpoint_config: CodacyEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ endpoint = endpoint_config.name
+ body = _metrics_request_body()
+ for metric in _list_ready_metrics(session, headers, logger, provider, organization):
+ path = endpoint_config.path.format(provider=provider, organization=organization, metric=metric)
+ try:
+ for page in _paginate(
+ session,
+ headers,
+ logger,
+ path,
+ endpoint_config.method,
+ endpoint_config.extra_params,
+ max_pages=endpoint_config.max_pages_per_parent,
+ body=body,
+ ):
+ yield [_normalize_item(endpoint, item, {"metricName": metric}) for item in page]
+ except requests.HTTPError as exc:
+ _skip_missing_parent(exc, logger, endpoint, f"metric {metric}")
+
+
+def get_rows(
+ api_token: str,
+ provider: str,
+ organization: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ endpoint_config = CODACY_ENDPOINTS[endpoint]
+ headers = _get_headers(api_token)
+ # One session reused across every page (and fan-out parent) so urllib3 keeps the connection
+ # alive instead of re-handshaking per request. The token rides the custom `api-token`
+ # header, which the capture pipeline's name-based denylist doesn't know, so redact it
+ # by value.
+ session = make_tracked_session(redact_values=(api_token,))
+
+ if endpoint_config.fan_out == "repository":
+ yield from _fan_out_over_repositories(session, headers, logger, provider, organization, endpoint_config)
+ elif endpoint_config.fan_out == "commit":
+ yield from _fan_out_over_commits(session, headers, logger, provider, organization, endpoint_config)
+ elif endpoint_config.fan_out == "tool":
+ yield from _fan_out_over_tools(session, headers, logger, endpoint_config)
+ elif endpoint_config.fan_out == "metric":
+ yield from _fan_out_over_metrics(session, headers, logger, provider, organization, endpoint_config)
+ else:
+ path = endpoint_config.path.format(provider=provider, organization=organization)
+ for page in _paginate(session, headers, logger, path, endpoint_config.method, endpoint_config.extra_params):
+ yield [_normalize_item(endpoint, item) for item in page]
def codacy_source(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/settings.py
index 97d22a60d4fc..586d3662ed7d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/settings.py
@@ -1,28 +1,45 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField
+# Parent resource a fan-out endpoint is requested once per. "commit" walks the organization's
+# repositories and then each repository's commits, so it is the only two-level fan-out.
+FanOut = Literal["repository", "tool", "commit", "metric"]
+
+# How far back the org-level metric time series is pulled on every sync. The endpoint requires an
+# explicit range and the table is full refresh, so this bounds what a sync re-reads.
+METRICS_LOOKBACK_DAYS = 365
+# Granularity of the metric time series; the API also accepts "week" and "month".
+METRICS_PERIOD = "day"
+
-@dataclass
+@frozen
class CodacyEndpointConfig:
name: str
- # Path template with {provider}, {organization}, and (for fan-out endpoints) {repository}
+ # Path template with {provider}, {organization}, and the fan-out parent's placeholder
+ # ({repository}, {tool_uuid}, {commit}, {metric}).
path: str
- # searchRepositoryIssues is the one POST list endpoint; pagination still rides the query string.
+ # searchRepositoryIssues and the metrics time series are the POST list endpoints; pagination
+ # still rides the query string.
method: Literal["GET", "POST"] = "GET"
- # Composite keys include the repository name for fan-out children, whose ids are only
- # unique within a repository.
+ # Composite keys include the fan-out parent's identifier, since child ids are only unique
+ # within a parent.
primary_keys: list[str] = field(default_factory=lambda: ["id"])
- # Fan-out: fetched once per repository in the configured organization.
- fan_out_per_repository: bool = False
+ fan_out: Optional[FanOut] = None
# Stable datetime field to partition by (never a mutable field like `updated`).
partition_key: Optional[str] = None
sort_mode: Literal["asc", "desc"] = "asc"
extra_params: dict[str, str] = field(default_factory=dict)
- # Hard cap on pages fetched per repository in a fan-out, to bound runaway pagination.
+ # Hard cap on pages fetched per fan-out parent, to bound runaway pagination.
# A structured warning is logged if the cap is reached.
- max_pages_per_repository: int = 1000
+ max_pages_per_parent: int = 1000
+ # Only read by the "commit" fan-out: deltaIssues is one request per commit, so the walk stops
+ # after this many commits per repository. Commits arrive newest-first, so the cap keeps the
+ # most recent ones.
+ max_commits_per_repository: int = 500
CODACY_ENDPOINTS: dict[str, CodacyEndpointConfig] = {
@@ -39,10 +56,18 @@ CODACY_ENDPOINTS: dict[str, CodacyEndpointConfig] = {
path="/analysis/organizations/{provider}/{organization}/repositories",
primary_keys=["provider", "owner", "name"],
),
+ "people": CodacyEndpointConfig(
+ name="people",
+ # Resolves the author identities stamped on commits and pull requests.
+ path="/organizations/{provider}/{organization}/people",
+ # `userId` and `committerId` are both optional — they are null for commit authors who
+ # never registered with Codacy — so the email is the only always-present identifier.
+ primary_keys=["email"],
+ ),
"files": CodacyEndpointConfig(
name="files",
path="/organizations/{provider}/{organization}/repositories/{repository}/files",
- fan_out_per_repository=True,
+ fan_out="repository",
# `fileId` identifies a file in a specific branch and commit, so it changes across
# analyses; the repository-relative path is the stable identity of a file row.
primary_keys=["repository", "path"],
@@ -51,13 +76,13 @@ CODACY_ENDPOINTS: dict[str, CodacyEndpointConfig] = {
name="issues",
path="/analysis/organizations/{provider}/{organization}/repositories/{repository}/issues/search",
method="POST",
- fan_out_per_repository=True,
+ fan_out="repository",
primary_keys=["repository", "resultDataId"],
),
"pull_requests": CodacyEndpointConfig(
name="pull_requests",
path="/analysis/organizations/{provider}/{organization}/repositories/{repository}/pull-requests",
- fan_out_per_repository=True,
+ fan_out="repository",
primary_keys=["repository", "number"],
# The API returns pull requests last-updated first (verified against the live API).
sort_mode="desc",
@@ -67,16 +92,51 @@ CODACY_ENDPOINTS: dict[str, CodacyEndpointConfig] = {
name="commits",
# Analysis results for the commits in the repository's main branch on Codacy.
path="/analysis/organizations/{provider}/{organization}/repositories/{repository}/commits",
- fan_out_per_repository=True,
+ fan_out="repository",
primary_keys=["repository", "sha"],
partition_key="commitTimestamp",
# The API returns commits newest-first (verified against the live API).
sort_mode="desc",
),
+ "commit_delta_issues": CodacyEndpointConfig(
+ name="commit_delta_issues",
+ # The individual issues a commit introduced or fixed, which the flat issues table cannot
+ # express — it only holds the issues currently open.
+ path="/analysis/organizations/{provider}/{organization}/repositories/{repository}/commits/{commit}/deltaIssues",
+ fan_out="commit",
+ primary_keys=["repository", "commitSha", "resultDataId"],
+ # Commits are walked newest-first, so the rows land newest-first too.
+ sort_mode="desc",
+ ),
+ "tools": CodacyEndpointConfig(
+ name="tools",
+ # Lookup resolving the toolUuid every issue row carries. Not organization-scoped: the
+ # tool catalog is the same for every Codacy account.
+ path="/tools",
+ primary_keys=["uuid"],
+ ),
+ "tool_patterns": CodacyEndpointConfig(
+ name="tool_patterns",
+ path="/tools/{tool_uuid}/patterns",
+ fan_out="tool",
+ # The API documents pattern ids as unique per tool, not globally.
+ primary_keys=["toolUuid", "id"],
+ ),
+ "metrics_timerange": CodacyEndpointConfig(
+ name="metrics_timerange",
+ # Codacy's own dashboard numbers, precomputed per period and broken down by repository.
+ path="/organizations/{provider}/{organization}/metrics/{metric}/timerange",
+ method="POST",
+ fan_out="metric",
+ primary_keys=["metricName", "date", "repository"],
+ partition_key="date",
+ ),
}
ENDPOINTS = tuple(CODACY_ENDPOINTS.keys())
# Codacy's v3 list endpoints expose no server-side updated-since/created-since filters
-# (pagination is cursor+limit only), so every endpoint is full refresh.
+# (pagination is cursor+limit only), so every endpoint is full refresh. The metrics time series
+# does take a date range, but the fan-out interleaves one ascending series per metric into a
+# single table, so the pipeline's watermark could not advance monotonically.
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in CODACY_ENDPOINTS}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/tests/test_codacy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/tests/test_codacy.py
index 451df86837f5..dc7e801035a3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/tests/test_codacy.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codacy/tests/test_codacy.py
@@ -1,3 +1,5 @@
+from dataclasses import replace
+from datetime import UTC, datetime, timedelta
from typing import Any
import pytest
@@ -14,7 +16,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.cod
get_rows,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.settings import CODACY_ENDPOINTS, ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.settings import (
+ CODACY_ENDPOINTS,
+ ENDPOINTS,
+ METRICS_LOOKBACK_DAYS,
+ METRICS_PERIOD,
+)
BASE = "https://api.codacy.com/api/v3"
REPOS_URL = f"{BASE}/organizations/gh/acme/repositories?limit=100"
@@ -29,7 +36,7 @@ def _response_with_status(status_code: int) -> requests.Response:
def _collect(monkeypatch: Any, endpoint: str, pages: dict[str, Any]) -> list[dict]:
"""Run get_rows against URL-keyed fixtures; a request for an unexpected URL fails loudly."""
- def fake_fetch(session: Any, method: str, url: str, headers: dict[str, str], logger: Any) -> dict:
+ def fake_fetch(session: Any, method: str, url: str, headers: dict[str, str], logger: Any, body: Any = None) -> dict:
result = pages[url]
if isinstance(result, Exception):
raise result
@@ -68,7 +75,7 @@ class TestPagination:
def test_page_cap_truncates_fan_out_pagination(self, monkeypatch: Any) -> None:
files_endpoint = CODACY_ENDPOINTS["files"]
- monkeypatch.setattr(files_endpoint, "max_pages_per_repository", 2)
+ monkeypatch.setitem(CODACY_ENDPOINTS, "files", replace(files_endpoint, max_pages_per_parent=2))
files_base = f"{BASE}/organizations/gh/acme/repositories/repo-a/files"
# Every page advertises another cursor; without the cap this would page forever.
@@ -80,7 +87,9 @@ class TestPagination:
}
logger = MagicMock()
- def fake_fetch(session: Any, method: str, url: str, headers: dict[str, str], logger_: Any) -> dict:
+ def fake_fetch(
+ session: Any, method: str, url: str, headers: dict[str, str], logger_: Any, body: Any = None
+ ) -> dict:
return pages[url]
monkeypatch.setattr(codacy, "_fetch_page", fake_fetch)
@@ -273,6 +282,14 @@ class TestFetchPage:
assert session.post.call_args.kwargs["json"] == {}
session.get.assert_not_called()
+ def test_post_body_is_forwarded(self) -> None:
+ # The metrics time series rejects an empty body; it carries the required date range.
+ session = MagicMock()
+ session.post.return_value = self._json_response(200, {"data": []})
+ body = {"from": "2026-01-01", "to": "2026-12-31"}
+ _fetch_page(session, "POST", f"{BASE}/organizations/gh/acme/metrics/x/timerange", {}, MagicMock(), body)
+ assert session.post.call_args.kwargs["json"] == body
+
class TestValidateCredentials:
@parameterized.expand([("valid_token", 200, True), ("invalid_token", 401, False), ("forbidden", 403, False)])
@@ -302,7 +319,7 @@ class TestSourceResponse:
# A fan-out child keyed without the repository would multi-match on merge once two
# repositories share an id (e.g. the same file path), degrading every subsequent sync.
for endpoint, config in CODACY_ENDPOINTS.items():
- if config.fan_out_per_repository:
+ if config.fan_out in ("repository", "commit"):
assert config.primary_keys[0] == "repository", endpoint
def test_commits_partition_on_stable_commit_timestamp(self) -> None:
@@ -311,3 +328,224 @@ class TestSourceResponse:
)
assert response.partition_mode == "datetime"
assert response.partition_keys == ["commitTimestamp"]
+
+
+class TestToolFanOut:
+ def test_patterns_are_stamped_with_their_tool_uuid(self, monkeypatch: Any) -> None:
+ # Codacy documents pattern ids as unique per tool only, so without the tool uuid the
+ # ["toolUuid", "id"] key collapses and two tools sharing an id multi-match on merge.
+ pages = {
+ f"{BASE}/tools?limit=100": {
+ "data": [{"uuid": "uuid-1", "name": "ESLint"}, {"uuid": "uuid-2", "name": "PMD"}],
+ "pagination": {},
+ },
+ f"{BASE}/tools/uuid-1/patterns?limit=100": {
+ "data": [{"id": "unused", "category": "ErrorProne"}],
+ "pagination": {},
+ },
+ f"{BASE}/tools/uuid-2/patterns?limit=100": {
+ "data": [{"id": "unused", "category": "CodeStyle"}],
+ "pagination": {},
+ },
+ }
+ rows = _collect(monkeypatch, "tool_patterns", pages)
+ assert rows == [
+ {"toolUuid": "uuid-1", "id": "unused", "category": "ErrorProne"},
+ {"toolUuid": "uuid-2", "id": "unused", "category": "CodeStyle"},
+ ]
+
+ def test_tools_without_a_uuid_are_not_fanned_out(self, monkeypatch: Any) -> None:
+ # A uuid-less entry would format into /tools/None/patterns and 404 the whole sweep.
+ pages = {
+ f"{BASE}/tools?limit=100": {"data": [{"name": "Broken"}], "pagination": {}},
+ }
+ assert _collect(monkeypatch, "tool_patterns", pages) == []
+
+
+class TestCommitFanOut:
+ def _commit_pages(self, shas: list[str]) -> dict[str, Any]:
+ return {
+ REPOS_URL: {"data": [{"name": "repo-a"}], "pagination": {}},
+ f"{BASE}/analysis/organizations/gh/acme/repositories/repo-a/commits?limit=100": {
+ "data": [{"commit": {"sha": sha}} for sha in shas],
+ "pagination": {},
+ },
+ }
+
+ def _delta_url(self, sha: str) -> str:
+ return f"{BASE}/analysis/organizations/gh/acme/repositories/repo-a/commits/{sha}/deltaIssues?limit=100"
+
+ def test_lifts_commit_issue_and_stamps_repository_and_commit(self, monkeypatch: Any) -> None:
+ pages = self._commit_pages(["sha1"])
+ pages[self._delta_url("sha1")] = {
+ "data": [{"commitIssue": {"resultDataId": 7, "message": "unused import"}, "deltaType": "Added"}],
+ "pagination": {},
+ }
+ rows = _collect(monkeypatch, "commit_delta_issues", pages)
+ # resultDataId is only stable within a repository, and the same issue can be added by one
+ # commit and fixed by another, so both parents have to reach the row as columns.
+ assert rows == [
+ {
+ "repository": "repo-a",
+ "commitSha": "sha1",
+ "resultDataId": 7,
+ "message": "unused import",
+ "deltaType": "Added",
+ }
+ ]
+
+ def test_commit_cap_bounds_the_per_commit_request_fan_out(self, monkeypatch: Any) -> None:
+ # deltaIssues costs one request per commit, so an uncapped walk over a busy repository
+ # would never finish inside Codacy's rate limit.
+ endpoint = CODACY_ENDPOINTS["commit_delta_issues"]
+ monkeypatch.setitem(
+ CODACY_ENDPOINTS,
+ "commit_delta_issues",
+ replace(endpoint, max_commits_per_repository=2),
+ )
+
+ pages = self._commit_pages(["sha1", "sha2", "sha3"])
+ for sha in ("sha1", "sha2", "sha3"):
+ pages[self._delta_url(sha)] = {"data": [{"commitIssue": {"resultDataId": 1}}], "pagination": {}}
+
+ logger = MagicMock()
+
+ def fake_fetch(session: Any, method: str, url: str, headers: dict[str, str], logger_: Any, body: Any = None):
+ return pages[url]
+
+ monkeypatch.setattr(codacy, "_fetch_page", fake_fetch)
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_token="token", provider="gh", organization="acme", endpoint="commit_delta_issues", logger=logger
+ ):
+ rows.extend(batch)
+
+ assert [row["commitSha"] for row in rows] == ["sha1", "sha2"]
+ logger.warning.assert_called_once()
+
+ def test_commit_removed_mid_sync_is_skipped_without_losing_the_repository(self, monkeypatch: Any) -> None:
+ pages = self._commit_pages(["sha1", "gone", "sha2"])
+ pages[self._delta_url("sha1")] = {"data": [{"commitIssue": {"resultDataId": 1}}], "pagination": {}}
+ pages[self._delta_url("gone")] = requests.HTTPError(response=_response_with_status(404))
+ pages[self._delta_url("sha2")] = {"data": [{"commitIssue": {"resultDataId": 2}}], "pagination": {}}
+
+ rows = _collect(monkeypatch, "commit_delta_issues", pages)
+ assert [row["commitSha"] for row in rows] == ["sha1", "sha2"]
+
+
+class TestMetricsFanOut:
+ READY_URL = f"{BASE}/organizations/gh/acme/metrics/ready"
+
+ def _timerange_url(self, metric: str) -> str:
+ return f"{BASE}/organizations/gh/acme/metrics/{metric}/timerange?limit=100"
+
+ def _run(self, monkeypatch: Any, pages: dict[str, Any]) -> tuple[list[dict], list[dict]]:
+ bodies: list[dict] = []
+
+ def fake_fetch(session: Any, method: str, url: str, headers: dict[str, str], logger_: Any, body: Any = None):
+ if body is not None:
+ bodies.append(body)
+ result = pages[url]
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ monkeypatch.setattr(codacy, "_fetch_page", fake_fetch)
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_token="token", provider="gh", organization="acme", endpoint="metrics_timerange", logger=MagicMock()
+ ):
+ rows.extend(batch)
+ return rows, bodies
+
+ def test_flattens_group_and_stamps_metric_name(self, monkeypatch: Any) -> None:
+ pages = {
+ self.READY_URL: {"data": {"readyMetrics": ["openissues"]}},
+ self._timerange_url("openissues"): {
+ "data": [
+ {
+ "date": "2026-09-01",
+ "group": {"organization": "acme", "repository": "repo-a", "dimensions": ["Security"]},
+ "value": 12.0,
+ "latestValue": 11.0,
+ }
+ ]
+ },
+ }
+ rows, _ = self._run(monkeypatch, pages)
+ assert rows == [
+ {
+ "metricName": "openissues",
+ "organization": "acme",
+ "repository": "repo-a",
+ "dimensions": ["Security"],
+ "date": "2026-09-01",
+ "value": 12.0,
+ "latestValue": 11.0,
+ }
+ ]
+
+ def test_ungrouped_value_keys_on_an_empty_repository(self, monkeypatch: Any) -> None:
+ # repository is part of the primary key; a null there never matches on merge, so the
+ # row would be re-inserted on every sync.
+ pages = {
+ self.READY_URL: {"data": {"readyMetrics": ["openissues"]}},
+ self._timerange_url("openissues"): {"data": [{"date": "2026-09-01", "value": 3.0}]},
+ }
+ rows, _ = self._run(monkeypatch, pages)
+ assert rows[0]["repository"] == ""
+
+ def test_request_body_carries_the_required_range_and_grouping(self, monkeypatch: Any) -> None:
+ # The endpoint rejects a body without from/to/groupBy, and the same window has to be
+ # reused for every metric so one table holds a consistent range.
+ pages = {
+ self.READY_URL: {"data": {"readyMetrics": ["openissues", "newissues"]}},
+ self._timerange_url("openissues"): {"data": []},
+ self._timerange_url("newissues"): {"data": []},
+ }
+ _, bodies = self._run(monkeypatch, pages)
+ assert len(bodies) == 2
+ assert bodies[0] == bodies[1]
+ today = datetime.now(UTC).date()
+ assert bodies[0] == {
+ "filter": {"entityFilter": {}},
+ "groupBy": {"groupBy": ["repository"]},
+ "from": (today - timedelta(days=METRICS_LOOKBACK_DAYS)).isoformat(),
+ "to": today.isoformat(),
+ "period": METRICS_PERIOD,
+ }
+
+ @parameterized.expand([("not_entitled", 403), ("not_found", 404)])
+ def test_organization_without_metrics_syncs_empty(self, _name: str, status_code: int) -> None:
+ # Metrics are opt-in on Codacy; the table has to come back empty rather than failing
+ # the schema for every account that hasn't enabled them.
+ def fake_fetch(session: Any, method: str, url: str, headers: dict[str, str], logger_: Any, body: Any = None):
+ raise requests.HTTPError(response=_response_with_status(status_code))
+
+ with patch.object(codacy, "_fetch_page", fake_fetch):
+ rows = list(
+ get_rows(
+ api_token="token",
+ provider="gh",
+ organization="acme",
+ endpoint="metrics_timerange",
+ logger=MagicMock(),
+ )
+ )
+ assert rows == []
+
+ def test_unexpected_error_on_ready_metrics_propagates(self) -> None:
+ def fake_fetch(session: Any, method: str, url: str, headers: dict[str, str], logger_: Any, body: Any = None):
+ raise requests.HTTPError(response=_response_with_status(400))
+
+ with patch.object(codacy, "_fetch_page", fake_fetch):
+ with pytest.raises(requests.HTTPError):
+ list(
+ get_rows(
+ api_token="token",
+ provider="gh",
+ organization="acme",
+ endpoint="metrics_timerange",
+ logger=MagicMock(),
+ )
+ )