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(warehouse-sources): add codacy security, coverage and overview tables (#103708)

Tom Owers11be1af88f2a
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 6bac60ff00db..1574ed82c1b1 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
@@ -1721,9 +1721,9 @@ Diffed against: <https://coda.io/apis/v1/openapi.json>
Note: Coda has been rebranded to Superhuman Docs, but the OpenAPI spec is still served at https://coda.io/apis/v1/openapi.json (v1.6.0). The synced rows table returns cells keyed by column ID; the columns table now resolves those ids to names, types, and formulas.
-## Codacy — **thin**
+## Codacy — gaps
-Today (11): `commit_delta_issues`, `commits`, `files`, `issues`, `metrics_timerange`, `organizations`, `people`, `pull_requests`, `repositories`, `tool_patterns`, `tools`
+Today (17): `category_overviews`, `commit_delta_issues`, `commit_statistics`, `commits`, `files`, `issues`, `issues_overview`, `metrics_timerange`, `organizations`, `people`, `pull_request_coverage`, `pull_request_file_coverage`, `pull_requests`, `repositories`, `security_items`, `tool_patterns`, `tools`
Diffed against: <https://api.codacy.com/api/api-docs/swagger.yaml>
@@ -1731,16 +1731,16 @@ Diffed against: <https://api.codacy.com/api/api-docs/swagger.yaml>
- [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)
+- [x] `/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) — `/security/items/search` synced as `security_items`; the `/security/items` twin is deprecated in the spec and caps repository filtering at 100 names
+- [x] `/analysis/organizations/{provider}/{org}/repositories/{repo}/commit-statistics` — Per-repo commit statistics over time, giving repo health a trend rather than a snapshot (medium) — synced as `commit_statistics`
+- [x] `/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) — synced as `category_overviews` and `issues_overview`
- [ ] `/organizations/{provider}/{org}/repositories/{repo}/branches` — Branch lookup that resolves the branch each analysed commit belongs to (medium)
- [ ] `/organizations/{provider}/{org}/sbom/dependencies/search` — Dependency inventory per org and repo, for supply-chain and license reporting (medium)
-- [ ] `/coverage/organizations/{provider}/{org}/repositories/{repo}/pull-requests/{pullRequestNumber} (+ /files)` — Coverage delta per pull request - coverage is completely absent from the current table set (medium)
+- [x] `/coverage/organizations/{provider}/{org}/repositories/{repo}/pull-requests/{pullRequestNumber} (+ /files)` — Coverage delta per pull request - coverage is completely absent from the current table set (medium) — synced as `pull_request_coverage` and `pull_request_file_coverage`
- [ ] `/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). 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).
+Note: Codacy API v3 swagger is served at https://api.codacy.com/api/api-docs/swagger.yaml (~250 paths). Seventeen static endpoints in codacy/settings.py, no dynamic discovery. SBOM is the remaining unrepresented product domain; coverage is covered per pull request only, not per file of the default branch. 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 3d48d80fc392..8078cc34eefd 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
@@ -215,6 +215,134 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"tags": "Tags associated with the pattern.",
},
},
+ "security_items": {
+ "description": "Security and risk management items for the organization: vulnerabilities, secrets, licence and dependency findings, each with a priority, an SLA status and its due date.",
+ "docs_url": "https://api.codacy.com/api/api-docs#searchsecurityitems",
+ "columns": {
+ "id": "Codacy identifier of the security item.",
+ "itemSource": "System that reported the item: Codacy, Jira, PenTest, ZAP, or Trivy.",
+ "itemSourceId": "Identifier of the item in the reporting system.",
+ "title": "Human-readable title of the item.",
+ "repository": "Name of the repository the item was found in.",
+ "openedAt": "Timestamp when the item was detected.",
+ "closedAt": "Timestamp when the item was closed, if it has been.",
+ "dueAt": "Timestamp the item must be fixed by, from the organization's SLA settings.",
+ "ignored": "Details of who ignored the item and why, when it has been ignored.",
+ "priority": "Priority of the item: Low, Medium, High, or Critical.",
+ "status": "SLA status of the item: Overdue, OnTrack, DueSoon, ClosedOnTime, ClosedLate, or Ignored.",
+ "htmlUrl": "Link to the underlying issue on Codacy.",
+ "projectKey": "Jira project key of the underlying issue.",
+ "securityCategory": "Security category of the item, such as Cryptography.",
+ "scanType": "Type of scan that found the item, such as SAST, SCA, Secrets, IaC, or DAST.",
+ "summary": "Brief description of the issue. Penetration testing items only.",
+ "cvssScore": "CVSS severity score of the vulnerability. Penetration testing items only.",
+ "cvssVector": "CVSS scoring vector detailing the nature and impact of the vulnerability.",
+ "cwe": "CWE software weakness identifier of the vulnerability.",
+ "cve": "CVE identifiers of the vulnerability.",
+ "affectedVersion": "Version the vulnerability was first detected in.",
+ "fixedVersion": "Versions, tags or commit SHAs where the vulnerability was fixed.",
+ "application": "URL of the affected application. DAST items only.",
+ "affectedTargets": "Targets affected by the security issue.",
+ "additionalInfo": "Additional information about the issue.",
+ "likelihood": "Likelihood of the issue being exploited. Penetration testing items only.",
+ "effortToFix": "Estimated effort to fix the issue. Penetration testing items only.",
+ "remediation": "Recommended steps to fix the issue.",
+ "dastTargetUrls": "Target URLs that were scanned.",
+ "imageName": "Name of the scanned container image.",
+ "imageTag": "Tag of the scanned container image.",
+ "dependencyChains": "Ordered package chains showing how the vulnerable package is reached. Dependency scanning items only.",
+ "advisoryInformation": "Advisory the finding is based on.",
+ },
+ },
+ "commit_statistics": {
+ "description": "Analysis totals for each analysed commit of a repository, giving repository health a trend over time instead of only the latest snapshot.",
+ "docs_url": "https://api.codacy.com/api/api-docs#listcommitanalysisstats",
+ "columns": {
+ "repository": "Name of the repository the commit belongs to.",
+ "repositoryId": "Codacy identifier of the repository.",
+ "commitId": "Codacy identifier of the commit.",
+ "commitShortUUID": "Short SHA of the commit.",
+ "commitTimestamp": "Timestamp of the commit.",
+ "commitAuthorName": "Name of the commit author.",
+ "numberIssues": "Number of issues in the repository at this commit.",
+ "numberLoc": "Lines of code in the repository at this commit.",
+ "issuesPerCategory": "Number of issues per issue category at this commit.",
+ "issuePercentage": "Percentage of lines of code with issues, truncated.",
+ "totalComplexity": "Total complexity of the repository at this commit.",
+ "numberComplexFiles": "Number of complex files at this commit.",
+ "complexFilesPercentage": "Percentage of complex files, truncated.",
+ "filesChangedToIncreaseComplexity": "Number of files the commit changed that increased complexity.",
+ "numberDuplicatedLines": "Number of duplicated lines at this commit.",
+ "duplicationPercentage": "Percentage of duplicated lines, truncated.",
+ "coveragePercentage": "Test coverage percentage, truncated. Only present when a coverage report was processed for the commit.",
+ "coveragePercentageWithDecimals": "Test coverage percentage. Only present when a coverage report was processed for the commit.",
+ "numberFilesUncovered": "Number of files with no test coverage.",
+ "techDebt": "Estimated time to fix all issues, in minutes.",
+ "totalFilesAdded": "Number of files the commit added.",
+ "totalFilesRemoved": "Number of files the commit removed.",
+ "totalFilesChanged": "Number of files the commit changed.",
+ },
+ },
+ "category_overviews": {
+ "description": "Issue counts per analysis category for the latest analysed commit of each repository, the breakdown behind the repository quality grade.",
+ "docs_url": "https://api.codacy.com/api/api-docs#listcategoryoverviews",
+ "columns": {
+ "repository": "Name of the repository the overview belongs to.",
+ "commitId": "Codacy identifier of the commit the overview was computed for.",
+ "categoryName": "Name of the analysis category, such as Security or ErrorProne.",
+ "categoryType": "Type of the analysis category.",
+ "categoryDescription": "Description of the analysis category.",
+ "percentage": "Percentage of the repository's issues in this category.",
+ "totalResults": "Number of issues in this category.",
+ },
+ },
+ "issues_overview": {
+ "description": "Issue counts for each repository broken down by category, severity level, language, code pattern, tag, commit author, and false-positive probability. One row per breakdown value.",
+ "docs_url": "https://api.codacy.com/api/api-docs#issuesoverview",
+ "columns": {
+ "repository": "Name of the repository the count belongs to.",
+ "dimension": "Breakdown the count belongs to: categories, levels, languages, tags, patterns, authors, or potentialFalsePositives.",
+ "name": "Value within the breakdown, such as the category name, severity level, or code pattern identifier.",
+ "total": "Number of issues with this value.",
+ "title": "Human-readable title of the code pattern. Only set for the patterns breakdown.",
+ },
+ },
+ "pull_request_coverage": {
+ "description": "Test coverage of each analysed pull request: how coverage moved against the common ancestor commit, and how well the lines the pull request touched are covered.",
+ "docs_url": "https://api.codacy.com/api/api-docs#getrepositorypullrequestcoverage",
+ "columns": {
+ "repository": "Name of the repository the pull request belongs to.",
+ "pullRequestNumber": "Number of the pull request on the Git provider.",
+ "id": "Codacy identifier of the pull request.",
+ "number": "Number of the pull request on the Git provider.",
+ "updated": "Timestamp when the pull request was last updated.",
+ "status": "Status of the pull request, such as open or merged.",
+ "title": "Title of the pull request.",
+ "owner": "Author of the pull request.",
+ "headCommitSha": "SHA of the pull request's head commit.",
+ "commonAncestorCommitSha": "SHA of the common ancestor commit coverage is compared against.",
+ "originBranch": "Branch the pull request comes from.",
+ "targetBranch": "Branch the pull request targets.",
+ "gitHref": "URL of the pull request on the Git provider.",
+ "deltaCoverage": "Difference between the coverage of the head commit and the common ancestor commit.",
+ "diffCoverage": "Coverage of the lines the pull request added or changed, with the covered and coverable line counts.",
+ "isUpToStandards": "True when the coverage metrics are at or above the quality gate thresholds.",
+ "resultReasons": "Per-gate results explaining the coverage verdict.",
+ },
+ },
+ "pull_request_file_coverage": {
+ "description": "Test coverage of each file changed by a pull request, so uncovered changes can be traced to the file that introduced them.",
+ "docs_url": "https://api.codacy.com/api/api-docs#getrepositorypullrequestfilescoverage",
+ "columns": {
+ "repository": "Name of the repository the pull request belongs to.",
+ "pullRequestNumber": "Number of the pull request on the Git provider.",
+ "fileName": "Path of the file in the repository.",
+ "coverage": "Coverage of the file on the pull request's head commit.",
+ "variation": "Change in the file's coverage caused by the pull request.",
+ "diff": "Coverage of the lines the pull request added or changed in this file.",
+ "diffLineHits": "Number of test hits per line added or changed in this file.",
+ },
+ },
"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",
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 60ee78f9b450..a461cac081a8 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
@@ -120,6 +120,76 @@ def _paginate(
break
+def _issues_overview_rows(data: Any) -> list[dict[str, Any]]:
+ """Unnest the overview's parallel count arrays into one row per breakdown value.
+
+ The endpoint answers with a single object holding one count array per dimension (category,
+ severity level, language, author, tag, pattern). Kept nested, the table could not be grouped
+ or filtered by dimension, which is the only thing the counts are useful for.
+ """
+ counts = (data or {}).get("counts") or {}
+ rows: list[dict[str, Any]] = []
+ for dimension, entries in counts.items():
+ if not isinstance(entries, list):
+ continue
+ for entry in entries:
+ # The `patterns` breakdown is keyed by pattern id with the title alongside; every
+ # other dimension carries a bare name.
+ name = entry.get("name") or entry.get("id")
+ if name is None:
+ continue
+ rows.append(
+ {
+ "dimension": dimension,
+ "name": name,
+ "total": entry.get("total"),
+ "title": entry.get("title"),
+ }
+ )
+ return rows
+
+
+def _expand_single_payload(endpoint: str, data: Any) -> list[dict[str, Any]]:
+ """Turn the `data` value of a one-shot response into the rows of the table."""
+ if endpoint == "issues_overview":
+ return _issues_overview_rows(data)
+ if isinstance(data, list):
+ return data
+ if isinstance(data, dict):
+ return [data]
+ return []
+
+
+def _iter_endpoint_pages(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ endpoint_config: CodacyEndpointConfig,
+ path: str,
+ max_pages: Optional[int] = None,
+ body: Optional[dict[str, Any]] = None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield raw item lists for one endpoint call, whichever response style it uses."""
+ if endpoint_config.paginated:
+ yield from _paginate(
+ session,
+ headers,
+ logger,
+ path,
+ endpoint_config.method,
+ endpoint_config.extra_params,
+ max_pages=max_pages,
+ body=body,
+ )
+ return
+
+ url = _build_url(path, dict(endpoint_config.extra_params))
+ data = _fetch_page(session, endpoint_config.method, url, headers, logger, body).get("data")
+ items = _expand_single_payload(endpoint_config.name, data)
+ if items:
+ yield items
+
+
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."""
@@ -136,6 +206,19 @@ def _normalize_item(endpoint: str, item: dict[str, Any], stamp: Optional[dict[st
if endpoint == "commit_delta_issues":
nested = item.pop("commitIssue", None) or {}
return {**stamp, **nested, **item}
+ if endpoint == "category_overviews":
+ category = item.pop("category", None) or {}
+ return {
+ **stamp,
+ "categoryName": category.get("name"),
+ "categoryType": category.get("categoryType"),
+ "categoryDescription": category.get("description"),
+ **item,
+ }
+ if endpoint == "pull_request_coverage":
+ nested = item.pop("pullRequest", None) or {}
+ coverage = item.pop("coverage", None) or {}
+ return {**stamp, **nested, **coverage, **item}
if endpoint == "metrics_timerange":
group = item.pop("group", None) or {}
return {
@@ -212,6 +295,34 @@ def _collect_commit_shas(
return shas
+def _collect_pull_request_numbers(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ provider: str,
+ organization: str,
+ repository: str,
+ limit: int,
+) -> list[int]:
+ # Analysed pull requests only: coverage is derived from the analysis, so the unanalysed ones
+ # the `pull_requests` table deliberately includes would only answer 404 here.
+ path = f"/analysis/organizations/{provider}/{organization}/repositories/{repository}/pull-requests"
+ numbers: list[int] = []
+ for page in _paginate(session, headers, logger, path):
+ for entry in page:
+ number = (entry.get("pullRequest") or {}).get("number")
+ if number is None:
+ continue
+ numbers.append(number)
+ if len(numbers) >= limit:
+ logger.warning(
+ f"Codacy: pull request cap reached for repository={repository}, max_pull_requests={limit}; "
+ "older pull requests are not expanded"
+ )
+ return numbers
+ return numbers
+
+
def _list_ready_metrics(
session: requests.Session,
headers: dict[str, str],
@@ -255,13 +366,12 @@ def _fan_out_over_repositories(
for repository in _iter_repository_names(session, headers, logger, provider, organization):
path = endpoint_config.path.format(provider=provider, organization=organization, repository=repository)
try:
- for page in _paginate(
+ for page in _iter_endpoint_pages(
session,
headers,
logger,
+ endpoint_config,
path,
- endpoint_config.method,
- endpoint_config.extra_params,
max_pages=endpoint_config.max_pages_per_parent,
):
yield [_normalize_item(endpoint, item, {"repository": repository}) for item in page]
@@ -314,6 +424,51 @@ def _fan_out_over_commits(
_skip_missing_parent(exc, logger, endpoint, f"commit {sha} of repository {repository}")
+def _fan_out_over_pull_requests(
+ 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:
+ numbers = _collect_pull_request_numbers(
+ session,
+ headers,
+ logger,
+ provider,
+ organization,
+ repository,
+ endpoint_config.max_pull_requests_per_repository,
+ )
+ except requests.HTTPError as exc:
+ _skip_missing_parent(exc, logger, endpoint, f"repository {repository}")
+ continue
+
+ for number in numbers:
+ path = endpoint_config.path.format(
+ provider=provider, organization=organization, repository=repository, pull_request=number
+ )
+ try:
+ for page in _iter_endpoint_pages(
+ session,
+ headers,
+ logger,
+ endpoint_config,
+ path,
+ max_pages=endpoint_config.max_pages_per_parent,
+ ):
+ yield [
+ _normalize_item(endpoint, item, {"repository": repository, "pullRequestNumber": number})
+ for item in page
+ ]
+ except requests.HTTPError as exc:
+ _skip_missing_parent(exc, logger, endpoint, f"pull request {number} of repository {repository}")
+
+
def _fan_out_over_tools(
session: requests.Session,
headers: dict[str, str],
@@ -379,12 +534,14 @@ def get_rows(
# 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,))
+ session = make_tracked_session(redact_values=(api_token,), capture=endpoint_config.capture_http_samples)
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 == "pull_request":
+ yield from _fan_out_over_pull_requests(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":
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 586d3662ed7d..fbf1301bd253 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
@@ -7,7 +7,7 @@ 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"]
+FanOut = Literal["repository", "tool", "commit", "metric", "pull_request"]
# 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.
@@ -15,6 +15,10 @@ METRICS_LOOKBACK_DAYS = 365
# Granularity of the metric time series; the API also accepts "week" and "month".
METRICS_PERIOD = "day"
+# Days of per-repository commit statistics requested on every sync. The endpoint returns the last
+# n days that have analysis data rather than the last n calendar days, and caps at 365.
+COMMIT_STATISTICS_DAYS = 365
+
@frozen
class CodacyEndpointConfig:
@@ -28,6 +32,12 @@ class CodacyEndpointConfig:
# 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"])
+ # False for the endpoints that answer with one complete payload and declare neither `cursor`
+ # nor `limit`; sending pagination params they don't accept makes Codacy reject the request.
+ paginated: bool = True
+ # False for endpoints whose rows carry free-text finding bodies and secret-scan detail. The
+ # HTTP sample capture scrubber is name-based and cannot recognise those fields.
+ capture_http_samples: bool = True
fan_out: Optional[FanOut] = None
# Stable datetime field to partition by (never a mutable field like `updated`).
partition_key: Optional[str] = None
@@ -40,6 +50,10 @@ class CodacyEndpointConfig:
# after this many commits per repository. Commits arrive newest-first, so the cap keeps the
# most recent ones.
max_commits_per_repository: int = 500
+ # Only read by the "pull_request" fan-out: coverage is two requests per pull request, so the
+ # walk stops after this many per repository. Pull requests arrive last-updated first, so the
+ # cap keeps the ones a coverage delta is still useful for.
+ max_pull_requests_per_repository: int = 200
CODACY_ENDPOINTS: dict[str, CodacyEndpointConfig] = {
@@ -122,6 +136,64 @@ CODACY_ENDPOINTS: dict[str, CodacyEndpointConfig] = {
# The API documents pattern ids as unique per tool, not globally.
primary_keys=["toolUuid", "id"],
),
+ "security_items": CodacyEndpointConfig(
+ name="security_items",
+ # The GET /security/items twin is deprecated in favour of this search endpoint, which also
+ # drops its 100-repository filter limit. An empty filter body returns every item.
+ path="/organizations/{provider}/{organization}/security/items/search",
+ method="POST",
+ primary_keys=["id"],
+ partition_key="openedAt",
+ capture_http_samples=False,
+ # The endpoint defaults to due date descending, which reshuffles as items are triaged;
+ # detection order is the only monotonic sort it offers.
+ extra_params={"sort": "DetectedAt", "direction": "asc"},
+ ),
+ "commit_statistics": CodacyEndpointConfig(
+ name="commit_statistics",
+ # Per-commit analysis totals over time, which turn the repository snapshot into a trend.
+ path="/analysis/organizations/{provider}/{organization}/repositories/{repository}/commit-statistics",
+ fan_out="repository",
+ primary_keys=["repository", "commitId"],
+ partition_key="commitTimestamp",
+ paginated=False,
+ extra_params={"days": str(COMMIT_STATISTICS_DAYS)},
+ ),
+ "category_overviews": CodacyEndpointConfig(
+ name="category_overviews",
+ # Issue counts per category for the repository's latest analysed commit.
+ path="/analysis/organizations/{provider}/{organization}/repositories/{repository}/category-overviews",
+ fan_out="repository",
+ primary_keys=["repository", "categoryName"],
+ paginated=False,
+ ),
+ "issues_overview": CodacyEndpointConfig(
+ name="issues_overview",
+ # The same issue totals broken down by severity, language, author, pattern and tag. The
+ # response is one object of parallel count arrays, unnested into one row per breakdown.
+ path="/analysis/organizations/{provider}/{organization}/repositories/{repository}/issues/overview",
+ method="POST",
+ fan_out="repository",
+ primary_keys=["repository", "dimension", "name"],
+ paginated=False,
+ ),
+ "pull_request_coverage": CodacyEndpointConfig(
+ name="pull_request_coverage",
+ path="/coverage/organizations/{provider}/{organization}/repositories/{repository}/pull-requests/{pull_request}",
+ fan_out="pull_request",
+ primary_keys=["repository", "pullRequestNumber"],
+ paginated=False,
+ # Pull requests are walked last-updated first, so the rows land in that order too.
+ sort_mode="desc",
+ ),
+ "pull_request_file_coverage": CodacyEndpointConfig(
+ name="pull_request_file_coverage",
+ path="/coverage/organizations/{provider}/{organization}/repositories/{repository}/pull-requests/{pull_request}/files",
+ fan_out="pull_request",
+ primary_keys=["repository", "pullRequestNumber", "fileName"],
+ paginated=False,
+ sort_mode="desc",
+ ),
"metrics_timerange": CodacyEndpointConfig(
name="metrics_timerange",
# Codacy's own dashboard numbers, precomputed per period and broken down by repository.
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 dc7e801035a3..f28a8f70a1c2 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
@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.cod
)
from products.warehouse_sources.backend.temporal.data_imports.sources.codacy.settings import (
CODACY_ENDPOINTS,
+ COMMIT_STATISTICS_DAYS,
ENDPOINTS,
METRICS_LOOKBACK_DAYS,
METRICS_PERIOD,
@@ -319,7 +320,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 in ("repository", "commit"):
+ if config.fan_out in ("repository", "commit", "pull_request"):
assert config.primary_keys[0] == "repository", endpoint
def test_commits_partition_on_stable_commit_timestamp(self) -> None:
@@ -549,3 +550,264 @@ class TestMetricsFanOut:
logger=MagicMock(),
)
)
+
+
+class TestSingleResponseEndpoints:
+ """Endpoints that answer with one complete payload and declare no `cursor` or `limit`."""
+
+ def _urls(self, monkeypatch: Any, endpoint: str, pages: dict[str, Any]) -> tuple[list[dict], list[str]]:
+ requested: list[str] = []
+
+ def fake_fetch(session: Any, method: str, url: str, headers: dict[str, str], logger_: Any, body: Any = None):
+ requested.append(url)
+ 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=endpoint, logger=MagicMock()
+ ):
+ rows.extend(batch)
+ return rows, requested
+
+ def test_commit_statistics_requests_the_day_range_without_pagination_params(self, monkeypatch: Any) -> None:
+ # The endpoint declares only `days`; sending the `limit` every paginated endpoint carries
+ # makes Codacy reject the request, so the whole table would fail to sync.
+ stats_url = (
+ f"{BASE}/analysis/organizations/gh/acme/repositories/repo-a/commit-statistics?days={COMMIT_STATISTICS_DAYS}"
+ )
+ pages = {
+ REPOS_URL: {"data": [{"name": "repo-a"}], "pagination": {}},
+ stats_url: {"data": [{"commitId": 1, "commitTimestamp": "2026-04-01T09:00:00Z", "numberIssues": 4}]},
+ }
+ rows, requested = self._urls(monkeypatch, "commit_statistics", pages)
+ assert stats_url in requested
+ assert rows == [
+ {"repository": "repo-a", "commitId": 1, "commitTimestamp": "2026-04-01T09:00:00Z", "numberIssues": 4}
+ ]
+
+ def test_category_overviews_flatten_the_nested_category(self, monkeypatch: Any) -> None:
+ # categoryName is half of the primary key, so it has to be a plain top-level column.
+ overviews_url = f"{BASE}/analysis/organizations/gh/acme/repositories/repo-a/category-overviews"
+ pages = {
+ REPOS_URL: {"data": [{"name": "repo-a"}], "pagination": {}},
+ overviews_url: {
+ "data": [
+ {
+ "commitId": 9,
+ "category": {"name": "Security", "categoryType": "Security", "description": "Security issues"},
+ "percentage": 1.6,
+ "totalResults": 3,
+ }
+ ]
+ },
+ }
+ rows, _ = self._urls(monkeypatch, "category_overviews", pages)
+ assert rows == [
+ {
+ "repository": "repo-a",
+ "categoryName": "Security",
+ "categoryType": "Security",
+ "categoryDescription": "Security issues",
+ "commitId": 9,
+ "percentage": 1.6,
+ "totalResults": 3,
+ }
+ ]
+
+ def test_issues_overview_unnests_every_count_breakdown(self, monkeypatch: Any) -> None:
+ # The response is one object of parallel count arrays; left nested the table could not be
+ # grouped by dimension, which is the only thing these counts are for.
+ overview_url = f"{BASE}/analysis/organizations/gh/acme/repositories/repo-a/issues/overview"
+ pages = {
+ REPOS_URL: {"data": [{"name": "repo-a"}], "pagination": {}},
+ overview_url: {
+ "data": {
+ "counts": {
+ "categories": [{"name": "Security", "total": 3}],
+ "levels": [{"name": "Error", "total": 2}, {"name": "Warning", "total": 1}],
+ "patterns": [{"id": "ESLint_no-unused-vars", "title": "No unused vars", "total": 5}],
+ }
+ }
+ },
+ }
+ rows, _ = self._urls(monkeypatch, "issues_overview", pages)
+ assert rows == [
+ {"repository": "repo-a", "dimension": "categories", "name": "Security", "total": 3, "title": None},
+ {"repository": "repo-a", "dimension": "levels", "name": "Error", "total": 2, "title": None},
+ {"repository": "repo-a", "dimension": "levels", "name": "Warning", "total": 1, "title": None},
+ {
+ "repository": "repo-a",
+ "dimension": "patterns",
+ # The patterns breakdown has no `name`; the pattern id is what identifies the row.
+ "name": "ESLint_no-unused-vars",
+ "total": 5,
+ "title": "No unused vars",
+ },
+ ]
+
+ def test_repository_without_issues_yields_no_overview_rows(self, monkeypatch: Any) -> None:
+ overview_url = f"{BASE}/analysis/organizations/gh/acme/repositories/repo-a/issues/overview"
+ pages = {
+ REPOS_URL: {"data": [{"name": "repo-a"}], "pagination": {}},
+ overview_url: {"data": {"counts": {"categories": [], "levels": []}}},
+ }
+ rows, _ = self._urls(monkeypatch, "issues_overview", pages)
+ assert rows == []
+
+
+class TestSecurityItems:
+ def test_paginates_in_detection_order(self, monkeypatch: Any) -> None:
+ # The endpoint defaults to due date descending, which reshuffles as items are triaged and
+ # can skip or repeat rows across page boundaries.
+ search = f"{BASE}/organizations/gh/acme/security/items/search"
+ pages = {
+ f"{search}?limit=100&sort=DetectedAt&direction=asc": {
+ "data": [{"id": "item-1", "openedAt": "2026-01-02T00:00:00Z", "priority": "Critical"}],
+ "pagination": {"cursor": "c2"},
+ },
+ f"{search}?limit=100&sort=DetectedAt&direction=asc&cursor=c2": {
+ "data": [{"id": "item-2", "openedAt": "2026-01-03T00:00:00Z", "priority": "Low"}],
+ "pagination": {},
+ },
+ }
+ rows = _collect(monkeypatch, "security_items", pages)
+ assert [row["id"] for row in rows] == ["item-1", "item-2"]
+
+ @parameterized.expand([("security_items", False), ("organizations", True)])
+ def test_sample_capture_is_off_for_security_findings(self, endpoint: str, expected: bool) -> None:
+ # Security rows carry free-text finding bodies and secret-scan detail that the capture
+ # pipeline's name-based scrubber cannot recognise, so they must stay out of the samples.
+ with patch.object(codacy, "make_tracked_session") as make_session:
+ with patch.object(codacy, "_fetch_page", return_value={"data": []}):
+ list(
+ get_rows(
+ api_token="token",
+ provider="gh",
+ organization="acme",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ )
+ )
+ assert make_session.call_args.kwargs["capture"] is expected
+
+ def test_partitions_on_the_stable_detection_timestamp(self) -> None:
+ # dueAt and closedAt both move as an item is triaged, so partitioning on either would
+ # rewrite partitions on every sync.
+ response = codacy_source(
+ api_token="token", provider="gh", organization="acme", endpoint="security_items", logger=MagicMock()
+ )
+ assert response.partition_keys == ["openedAt"]
+
+
+class TestPullRequestFanOut:
+ COVERAGE_BASE = f"{BASE}/coverage/organizations/gh/acme/repositories/repo-a/pull-requests"
+ # No includeNotAnalyzed: coverage only exists for pull requests Codacy analysed.
+ PRS_URL = f"{BASE}/analysis/organizations/gh/acme/repositories/repo-a/pull-requests?limit=100"
+
+ def _run(self, monkeypatch: Any, endpoint: str, pages: dict[str, Any], logger: Any = None) -> list[dict]:
+ def fake_fetch(session: Any, method: str, url: str, headers: dict[str, str], logger_: Any, body: Any = None):
+ 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=endpoint,
+ logger=logger or MagicMock(),
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_coverage_row_merges_the_pull_request_and_its_coverage(self, monkeypatch: Any) -> None:
+ pages = {
+ REPOS_URL: {"data": [{"name": "repo-a"}], "pagination": {}},
+ self.PRS_URL: {"data": [{"pullRequest": {"number": 7}}], "pagination": {}},
+ f"{self.COVERAGE_BASE}/7": {
+ "data": {
+ "pullRequest": {"id": 1, "number": 7, "status": "open", "targetBranch": "master"},
+ "coverage": {"deltaCoverage": -1.5, "isUpToStandards": False},
+ }
+ },
+ }
+ rows = self._run(monkeypatch, "pull_request_coverage", pages)
+ assert rows == [
+ {
+ "repository": "repo-a",
+ "pullRequestNumber": 7,
+ "id": 1,
+ "number": 7,
+ "status": "open",
+ "targetBranch": "master",
+ "deltaCoverage": -1.5,
+ "isUpToStandards": False,
+ }
+ ]
+
+ def test_file_coverage_rows_carry_both_parents(self, monkeypatch: Any) -> None:
+ # A file path repeats across pull requests and repositories, so neither parent can be
+ # dropped from the ["repository", "pullRequestNumber", "fileName"] key.
+ pages = {
+ REPOS_URL: {"data": [{"name": "repo-a"}], "pagination": {}},
+ self.PRS_URL: {"data": [{"pullRequest": {"number": 7}}], "pagination": {}},
+ f"{self.COVERAGE_BASE}/7/files": {
+ "data": [{"fileName": "src/main.py", "coverage": 82.0, "variation": -3.0}]
+ },
+ }
+ rows = self._run(monkeypatch, "pull_request_file_coverage", pages)
+ assert rows == [
+ {
+ "repository": "repo-a",
+ "pullRequestNumber": 7,
+ "fileName": "src/main.py",
+ "coverage": 82.0,
+ "variation": -3.0,
+ }
+ ]
+
+ def test_pull_request_cap_bounds_the_per_pull_request_request_fan_out(self, monkeypatch: Any) -> None:
+ # Coverage costs a request per pull request, so an uncapped walk over a busy repository
+ # would never finish inside Codacy's rate limit.
+ endpoint = CODACY_ENDPOINTS["pull_request_coverage"]
+ monkeypatch.setitem(
+ CODACY_ENDPOINTS,
+ "pull_request_coverage",
+ replace(endpoint, max_pull_requests_per_repository=2),
+ )
+
+ pages: dict[str, Any] = {
+ REPOS_URL: {"data": [{"name": "repo-a"}], "pagination": {}},
+ self.PRS_URL: {"data": [{"pullRequest": {"number": n}} for n in (7, 8, 9)], "pagination": {}},
+ }
+ for number in (7, 8, 9):
+ pages[f"{self.COVERAGE_BASE}/{number}"] = {"data": {"pullRequest": {"number": number}, "coverage": {}}}
+
+ logger = MagicMock()
+ rows = self._run(monkeypatch, "pull_request_coverage", pages, logger)
+ assert [row["pullRequestNumber"] for row in rows] == [7, 8]
+ logger.warning.assert_called_once()
+
+ def test_pull_request_without_coverage_is_skipped(self, monkeypatch: Any) -> None:
+ # A pull request analysed with no coverage report uploaded answers 404; it must not fail
+ # the whole repository sweep.
+ pages: dict[str, Any] = {
+ REPOS_URL: {"data": [{"name": "repo-a"}], "pagination": {}},
+ self.PRS_URL: {"data": [{"pullRequest": {"number": n}} for n in (7, 8)], "pagination": {}},
+ f"{self.COVERAGE_BASE}/7": requests.HTTPError(response=_response_with_status(404)),
+ f"{self.COVERAGE_BASE}/8": {"data": {"pullRequest": {"number": 8}, "coverage": {"deltaCoverage": 0.0}}},
+ }
+ rows = self._run(monkeypatch, "pull_request_coverage", pages)
+ assert [row["pullRequestNumber"] for row in rows] == [8]
+
+ def test_pull_request_without_a_number_is_not_fanned_out(self, monkeypatch: Any) -> None:
+ # A number-less entry would format into /pull-requests/None and 404 the whole sweep.
+ pages = {
+ REPOS_URL: {"data": [{"name": "repo-a"}], "pagination": {}},
+ self.PRS_URL: {"data": [{"pullRequest": {}}], "pagination": {}},
+ }
+ assert self._run(monkeypatch, "pull_request_coverage", pages) == []