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 deepsource checks, pull request and analyzer tables (#105166)

Tom Owers6117205a8cf9
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 2cde71e6f6fd..560a144e2e5a 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
@@ -2392,15 +2392,15 @@ Note: The Management API is only ~28 GET operations; the missing pieces are almo
## Deepsource — gaps
-Today (7): `analysis_runs`, `issue_occurrences`, `issues`, `metrics`, `reports`, `repositories`, `vulnerability_occurrences`
+Today (10): `analysis_runs`, `analyzers`, `checks`, `issue_occurrences`, `issues`, `metrics`, `pull_requests`, `reports`, `repositories`, `vulnerability_occurrences`
Diffed against: <https://docs.deepsource.com/docs/developers/api>
-- [ ] `Check (AnalysisRun.checks, with CheckSummary occurrencesIntroduced/Resolved/Suppressed)` — per-analyzer results inside each analysis run — the level at which introduced vs resolved issues are counted (high)
-- [ ] `analyzers / analyzer(shortcode)` — lookup table resolving the analyzer shortcodes carried on issues, checks and occurrences (high)
-- [ ] `Repository.pullRequest / pull requests (PRSummary issuesRaised, issuesResolved, vulnerabilitiesRaised)` — PR-level quality outcomes, the main way teams measure whether DeepSource is catching things pre-merge (high)
+- [x] `Check (AnalysisRun.checks, with CheckSummary occurrencesIntroduced/Resolved/Suppressed)` — per-analyzer results inside each analysis run — the level at which introduced vs resolved issues are counted (high)
+- [x] `analyzers / analyzer(shortcode)` — lookup table resolving the analyzer shortcodes carried on issues, checks and occurrences (high)
+- [x] `Repository.pullRequest / pull requests (PRSummary issuesRaised, issuesResolved, vulnerabilitiesRaised)` — PR-level quality outcomes, the main way teams measure whether DeepSource is catching things pre-merge (high)
- [ ] `Repository.targets (RepositoryTarget: ecosystem, packageManager, manifestPath)` — SCA target inventory that scopes the vulnerability occurrences already synced (medium)
-- [ ] `Package / PackageVersion` — dependency inventory that resolves the packages referenced by vulnerability occurrences (medium)
+- [ ] `Package / PackageVersion` — dependency inventory that resolves the packages referenced by vulnerability occurrences (medium) — not a table: the schema exposes no `packages` connection, so these are only reachable as nested fields of `VulnerabilityOccurrence`, which `vulnerability_occurrences` already selects inline
- [ ] `Vulnerability (identifier, summary, severity, fixability)` — lookup definition behind vulnerability_occurrences, if occurrences only carry IDs (medium)
- [ ] `Account.suppressedIssues / IgnoreRule` — which issues are suppressed team-wide, needed to explain drops in issue counts (medium)
- [ ] `TeamMember (account team members and roles)` — resolves the users attached to runs and repositories (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/canonical_descriptions.py
index fda0bb7a8db5..ca2a0e0ae3a9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/canonical_descriptions.py
@@ -37,6 +37,44 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"repositoryName": "Name of the repository the run belongs to.",
},
},
+ "checks": {
+ "description": "A single analyzer's check within an analysis run, with the issue occurrences that analyzer introduced, resolved, and suppressed on that run.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Relay global ID of the check.",
+ "sequence": "Position of the check within its analysis run.",
+ "status": "Current status of the check (PENDING, SUCCESS, FAILURE, TIMEOUT, CANCEL, READY, ARTIFACT_TIMEOUT).",
+ "createdAt": "When the check was created.",
+ "updatedAt": "When the check was last modified.",
+ "finishedAt": "When the check finished, if it has.",
+ "analyzer": "The analyzer that ran this check: shortcode and name.",
+ "summary": "Counts of occurrences introduced, resolved, and suppressed by this check.",
+ "analysisRunId": "Relay global ID of the analysis run the check belongs to.",
+ "analysisRunUid": "UUID of the analysis run the check belongs to.",
+ "commitOid": "Commit SHA the analysis run analyzed.",
+ "branchName": "Branch the analyzed commit belongs to.",
+ "repositoryId": "Relay global ID of the repository the check ran on.",
+ "repositoryName": "Name of the repository the check ran on.",
+ },
+ },
+ "pull_requests": {
+ "description": "A pull request analyzed by DeepSource, with a summary of the issues and vulnerabilities it raised, resolved, and suppressed before merge.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Relay global ID of the pull request.",
+ "number": "Pull request number on the VCS provider.",
+ "title": "Title of the pull request.",
+ "state": "Current state of the pull request (OPEN, CLOSED, MERGED).",
+ "baseBranch": "Branch the pull request merges into.",
+ "branch": "Source branch of the pull request.",
+ "vcsUrl": "URL of the pull request on the VCS provider.",
+ "createdAt": "When the pull request was created.",
+ "summary": "Counts of issues raised, resolved, and suppressed, and vulnerabilities raised, in the pull request.",
+ "latestAnalysisRun": "The most recent analysis run for the pull request: its ID and status.",
+ "repositoryId": "Relay global ID of the repository the pull request belongs to.",
+ "repositoryName": "Name of the repository the pull request belongs to.",
+ },
+ },
"issues": {
"description": "An issue type currently raised in a repository, with its category, severity, and how many occurrences of it exist.",
"docs_url": _DOCS_URL,
@@ -78,6 +116,20 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"repositoryName": "Name of the repository the vulnerability was found in.",
},
},
+ "analyzers": {
+ "description": "The catalog of analyzers DeepSource offers. Resolves the analyzer shortcodes carried on issues, checks, and occurrences. The same for every account.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Relay global ID of the analyzer.",
+ "shortcode": "Globally unique short name of the analyzer (python, go, javascript, ...).",
+ "name": "Human-readable name of the analyzer.",
+ "version": "Version of the analyzer.",
+ "description": "Description of what the analyzer checks.",
+ "type": "Type of the analyzer (e.g. core, community, transformer).",
+ "logo": "URL of the analyzer's logo.",
+ "numIssues": "Total number of issue types this analyzer can detect.",
+ },
+ },
"metrics": {
"description": "The latest value of each code-quality metric per repository and language key, such as line coverage or duplicate code percentage.",
"docs_url": _DOCS_URL,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/deepsource.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/deepsource.py
index 208cc5152e7f..caac9ae2174e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/deepsource.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/deepsource.py
@@ -1,5 +1,5 @@
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from typing import Any
import requests
@@ -10,14 +10,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.queries import (
+ ANALYSIS_RUN_CHECKS_QUERY,
CONNECTION_QUERIES,
PER_REPOSITORY_QUERIES,
REPOSITORIES_QUERY,
REPOSITORY_NAMES_QUERY,
+ ROOT_CONNECTION_QUERIES,
VALIDATE_QUERY,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.settings import (
DEEPSOURCE_API_URL,
+ DEEPSOURCE_CHECKS_PER_RUN_PAGE_SIZE,
DEEPSOURCE_DEFAULT_PAGE_SIZE,
DEEPSOURCE_ENDPOINTS,
DEEPSOURCE_MAX_PAGES_PER_CONNECTION,
@@ -145,7 +148,7 @@ def _iter_connection(
session: requests.Session,
query: str,
variables: dict[str, Any],
- parent_field: str,
+ parent_field: str | None,
connection_field: str,
logger: FilteringBoundLogger,
start_cursor: str | None = None,
@@ -153,6 +156,8 @@ def _iter_connection(
) -> Iterator[tuple[dict[str, Any], list[dict[str, Any]], str | None, bool]]:
"""Walk one Relay connection, yielding (parent_object, nodes, end_cursor, has_next_page) pages.
+ ``parent_field`` is None for a connection that sits directly on the root query.
+
When the parent object resolves to null: raise ``missing_parent_error`` if set (a missing
account is fatal), otherwise stop silently (a repository deleted mid-sync is a benign skip).
"""
@@ -160,7 +165,7 @@ def _iter_connection(
page_count = 0
while True:
payload = _execute(session, query, {**variables, "cursor": cursor}, logger)
- parent = payload["data"].get(parent_field)
+ parent = payload["data"] if parent_field is None else payload["data"].get(parent_field)
if parent is None:
if missing_parent_error:
raise Exception(missing_parent_error)
@@ -178,6 +183,11 @@ def _iter_connection(
# fail loudly instead of silently returning partial results.
raise Exception(f"DeepSource: hasNextPage=True but endCursor is empty for {connection_field}")
+ if has_next_page and end_cursor == cursor:
+ # An endCursor that doesn't advance re-fetches this page, duplicating its rows
+ # until the page cap truncates the rest.
+ raise Exception(f"DeepSource: endCursor did not advance past '{cursor}' for {connection_field}")
+
yield parent, nodes, end_cursor, has_next_page
if not has_next_page:
@@ -268,6 +278,69 @@ def _with_repository_context(node: dict[str, Any], repository: dict[str, Any]) -
return {**node, "repositoryId": repository.get("id"), "repositoryName": repository.get("name")}
+# Turns one node of a repository connection into the rows it contributes to the table.
+# Most endpoints are one row per node; `checks` expands each analysis run into its checks.
+FanOutRowBuilder = Callable[
+ [requests.Session, FilteringBoundLogger, dict[str, Any], dict[str, Any]], list[dict[str, Any]]
+]
+
+
+def _repository_node_rows(
+ _session: requests.Session,
+ _logger: FilteringBoundLogger,
+ node: dict[str, Any],
+ repository: dict[str, Any],
+) -> list[dict[str, Any]]:
+ return [_with_repository_context(node, repository)]
+
+
+def _check_rows(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ analysis_run: dict[str, Any],
+ repository: dict[str, Any],
+) -> list[dict[str, Any]]:
+ """One row per analyzer check of an analysis run, from the checks nested in the run walk."""
+ context = {
+ "analysisRunId": analysis_run.get("id"),
+ "analysisRunUid": analysis_run.get("runUid"),
+ "commitOid": analysis_run.get("commitOid"),
+ "branchName": analysis_run.get("branchName"),
+ "repositoryId": repository.get("id"),
+ "repositoryName": repository.get("name"),
+ }
+ connection = analysis_run.get("checks") or {}
+ rows = [{**edge["node"], **context} for edge in connection.get("edges") or [] if edge and edge.get("node")]
+
+ page_info = connection.get("pageInfo") or {}
+ if not page_info.get("hasNextPage"):
+ return rows
+
+ end_cursor = page_info.get("endCursor")
+ if not end_cursor:
+ raise Exception("DeepSource: hasNextPage=True but endCursor is empty for checks")
+
+ for _parent, nodes, _end_cursor, _has_next_page in _iter_connection(
+ session,
+ ANALYSIS_RUN_CHECKS_QUERY,
+ {"id": analysis_run["id"], "checkPageSize": DEEPSOURCE_CHECKS_PER_RUN_PAGE_SIZE},
+ "node",
+ "checks",
+ logger,
+ start_cursor=end_cursor,
+ # The run was in the page we just read, so a null node here means its remaining
+ # checks are unreachable. Skipping would checkpoint a half-synced run as complete.
+ missing_parent_error=f"DeepSource: analysis run {analysis_run['id']} disappeared while paginating its checks",
+ ):
+ rows.extend({**node, **context} for node in nodes)
+ return rows
+
+
+_FAN_OUT_ROW_BUILDERS: dict[str, FanOutRowBuilder] = {
+ "checks": _check_rows,
+}
+
+
def _metric_rows(repository: dict[str, Any]) -> list[dict[str, Any]]:
"""Flatten repository.metrics into one row per metric item (metric x language key)."""
rows: list[dict[str, Any]] = []
@@ -329,10 +402,12 @@ def _fan_out_connection_rows(
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[DeepsourceResumeConfig],
) -> Iterator[list[dict[str, Any]]]:
- """Paginated per-repository fan-out (analysis runs, issues, occurrences)."""
+ """Paginated per-repository fan-out (analysis runs, pull requests, issues, occurrences)."""
query = CONNECTION_QUERIES[endpoint]
- connection_field = DEEPSOURCE_ENDPOINTS[endpoint].connection_field
+ endpoint_config = DEEPSOURCE_ENDPOINTS[endpoint]
+ connection_field = endpoint_config.connection_field
assert connection_field is not None
+ build_rows = _FAN_OUT_ROW_BUILDERS.get(endpoint, _repository_node_rows)
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
completed = set(resume.completed_repositories) if resume else set()
@@ -353,6 +428,7 @@ def _fan_out_connection_rows(
**_account_variables(account_login, vcs_provider),
"name": repository_name,
"pageSize": DEEPSOURCE_DEFAULT_PAGE_SIZE,
+ **endpoint_config.extra_variables,
}
for parent, nodes, end_cursor, has_next_page in _iter_connection(
session,
@@ -363,8 +439,9 @@ def _fan_out_connection_rows(
logger,
start_cursor=start_cursor,
):
- if nodes:
- yield [_with_repository_context(node, parent) for node in nodes]
+ rows = [row for node in nodes for row in build_rows(session, logger, node, parent)]
+ if rows:
+ yield rows
if has_next_page:
resumable_source_manager.save_state(
DeepsourceResumeConfig(
@@ -378,6 +455,34 @@ def _fan_out_connection_rows(
resumable_source_manager.save_state(DeepsourceResumeConfig(completed_repositories=sorted(completed)))
+def _root_connection_rows(
+ session: requests.Session,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DeepsourceResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk a Relay connection on the root query — no account or repository to fan out over."""
+ connection_field = DEEPSOURCE_ENDPOINTS[endpoint].root_connection_field
+ assert connection_field is not None
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_cursor = resume.cursor if resume else None
+
+ for _parent, nodes, end_cursor, has_next_page in _iter_connection(
+ session,
+ ROOT_CONNECTION_QUERIES[endpoint],
+ {"pageSize": DEEPSOURCE_DEFAULT_PAGE_SIZE},
+ None,
+ connection_field,
+ logger,
+ start_cursor=start_cursor,
+ ):
+ if nodes:
+ yield nodes
+ if has_next_page:
+ resumable_source_manager.save_state(DeepsourceResumeConfig(cursor=end_cursor))
+
+
def _per_repository_object_rows(
session: requests.Session,
account_login: str,
@@ -428,6 +533,8 @@ def deepsource_source(
try:
if endpoint == "repositories":
yield from _repositories_rows(session, account_login, vcs_provider, logger, resumable_source_manager)
+ elif endpoint_config.root_connection_field:
+ yield from _root_connection_rows(session, endpoint, logger, resumable_source_manager)
elif endpoint_config.per_repository_object:
yield from _per_repository_object_rows(
session, account_login, vcs_provider, endpoint, logger, resumable_source_manager
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/queries.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/queries.py
index afc8b631459d..697d719ae366 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/queries.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/queries.py
@@ -148,6 +148,112 @@ query VulnerabilityOccurrences($login: String!, $vcsProvider: VCSProvider!, $nam
}
}"""
+# Shared between the nested (per analysis run) and follow-up (per run, by node ID) queries.
+_CHECK_FRAGMENT = """
+fragment CheckFields on Check {
+ id
+ sequence
+ status
+ createdAt
+ updatedAt
+ finishedAt
+ analyzer { shortcode name }
+ summary {
+ occurrencesIntroduced
+ occurrencesResolved
+ occurrencesSuppressed
+ }
+}"""
+
+# Checks hang off analysis runs, so they are fetched nested inside the repository's run
+# walk rather than one request per run. `checkPageSize` is generous enough that a run's
+# checks almost always fit in this first page; ANALYSIS_RUN_CHECKS_QUERY picks up the rest.
+CHECKS_QUERY = (
+ _CHECK_FRAGMENT
+ + """
+query RepositoryChecks($login: String!, $vcsProvider: VCSProvider!, $name: String!, $pageSize: Int!, $cursor: String, $checkPageSize: Int!) {
+ repository(login: $login, vcsProvider: $vcsProvider, name: $name) {
+ id
+ name
+ analysisRuns(first: $pageSize, after: $cursor) {
+ pageInfo { hasNextPage endCursor }
+ edges { node {
+ id
+ runUid
+ commitOid
+ branchName
+ checks(first: $checkPageSize) {
+ pageInfo { hasNextPage endCursor }
+ edges { node { ...CheckFields } }
+ }
+ } }
+ }
+ }
+}"""
+)
+
+ANALYSIS_RUN_CHECKS_QUERY = (
+ _CHECK_FRAGMENT
+ + """
+query AnalysisRunChecks($id: ID!, $checkPageSize: Int!, $cursor: String) {
+ node(id: $id) {
+ ... on AnalysisRun {
+ checks(first: $checkPageSize, after: $cursor) {
+ pageInfo { hasNextPage endCursor }
+ edges { node { ...CheckFields } }
+ }
+ }
+ }
+}"""
+)
+
+PULL_REQUESTS_QUERY = """
+query RepositoryPullRequests($login: String!, $vcsProvider: VCSProvider!, $name: String!, $pageSize: Int!, $cursor: String) {
+ repository(login: $login, vcsProvider: $vcsProvider, name: $name) {
+ id
+ name
+ pullRequests(first: $pageSize, after: $cursor) {
+ pageInfo { hasNextPage endCursor }
+ edges { node {
+ id
+ number
+ title
+ state
+ baseBranch
+ branch
+ vcsUrl
+ createdAt
+ summary {
+ issuesRaised
+ issuesResolved
+ issuesSuppressed
+ vulnerabilitiesRaised
+ }
+ latestAnalysisRun { id status }
+ } }
+ }
+ }
+}"""
+
+# The analyzer catalog is the same for every DeepSource user, so this query takes no
+# account or repository argument.
+ANALYZERS_QUERY = """
+query Analyzers($pageSize: Int!, $cursor: String) {
+ analyzers(first: $pageSize, after: $cursor) {
+ pageInfo { hasNextPage endCursor }
+ edges { node {
+ id
+ shortcode
+ name
+ version
+ description
+ type
+ logo
+ numIssues
+ } }
+ }
+}"""
+
METRICS_QUERY = """
query RepositoryMetrics($login: String!, $vcsProvider: VCSProvider!, $name: String!) {
repository(login: $login, vcsProvider: $vcsProvider, name: $name) {
@@ -204,6 +310,8 @@ query Validate($login: String!, $vcsProvider: VCSProvider!) {
CONNECTION_QUERIES: dict[str, str] = {
"analysis_runs": ANALYSIS_RUNS_QUERY,
+ "checks": CHECKS_QUERY,
+ "pull_requests": PULL_REQUESTS_QUERY,
"issues": ISSUES_QUERY,
"issue_occurrences": ISSUE_OCCURRENCES_QUERY,
"vulnerability_occurrences": VULNERABILITY_OCCURRENCES_QUERY,
@@ -213,3 +321,7 @@ PER_REPOSITORY_QUERIES: dict[str, str] = {
"metrics": METRICS_QUERY,
"reports": REPORTS_QUERY,
}
+
+ROOT_CONNECTION_QUERIES: dict[str, str] = {
+ "analyzers": ANALYZERS_QUERY,
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/settings.py
index d05fff8e457b..ab052255ed69 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/settings.py
@@ -1,4 +1,5 @@
-from dataclasses import dataclass
+from dataclasses import dataclass, field
+from typing import Any
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
PartitionFormat,
@@ -14,6 +15,9 @@ DEEPSOURCE_API_URL = "https://api.deepsource.com/graphql/"
DEEPSOURCE_DEFAULT_PAGE_SIZE = 50
# Repository enumeration only pulls names, so a bigger page keeps the fan-out setup cheap.
DEEPSOURCE_REPOSITORY_LIST_PAGE_SIZE = 100
+# Checks ride along nested in the analysis-run walk, one per analyzer enabled on the run.
+# DeepSource ships far fewer analyzers than this, so a run needing a second page is rare.
+DEEPSOURCE_CHECKS_PER_RUN_PAGE_SIZE = 50
# Hard cap per Relay connection walk so a pathological cursor loop can't scan unbounded
# pages. At the default page size this still allows 100k rows per connection.
@@ -28,21 +32,26 @@ CREATED_AT = "createdAt"
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
-@dataclass
+@dataclass(frozen=True)
class DeepsourceEndpointConfig:
primary_keys: list[str]
# GraphQL connection field on Repository for paginated per-repository fan-out.
connection_field: str | None = None
+ # GraphQL connection field on the root query, walked once for the whole account.
+ root_connection_field: str | None = None
# metrics/reports: fetched as one non-paginated query per repository.
per_repository_object: bool = False
+ # Extra GraphQL variables this endpoint's query declares beyond the shared ones.
+ extra_variables: dict[str, Any] = field(default_factory=dict)
partition_mode: PartitionMode | None = None
partition_format: PartitionFormat | None = None
partition_keys: list[str] | None = None
should_sync_default: bool = True
def __post_init__(self) -> None:
- if self.connection_field and self.per_repository_object:
- raise ValueError("An endpoint is either a paginated connection or a per-repository object, not both")
+ shapes = [bool(self.connection_field), bool(self.root_connection_field), self.per_repository_object]
+ if sum(shapes) > 1:
+ raise ValueError("An endpoint has at most one of: repository connection, root connection, object query")
DEEPSOURCE_ENDPOINTS: dict[str, DeepsourceEndpointConfig] = {
@@ -56,6 +65,23 @@ DEEPSOURCE_ENDPOINTS: dict[str, DeepsourceEndpointConfig] = {
partition_format="month",
partition_keys=[CREATED_AT],
),
+ "checks": DeepsourceEndpointConfig(
+ primary_keys=["id"],
+ # Checks are fetched nested in the analysis-run walk, so this endpoint pages over
+ # analysisRuns and expands each run into one row per analyzer check.
+ connection_field="analysisRuns",
+ extra_variables={"checkPageSize": DEEPSOURCE_CHECKS_PER_RUN_PAGE_SIZE},
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[CREATED_AT],
+ ),
+ "pull_requests": DeepsourceEndpointConfig(
+ primary_keys=["id"],
+ connection_field="pullRequests",
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[CREATED_AT],
+ ),
"issues": DeepsourceEndpointConfig(
primary_keys=["id"],
connection_field="issues",
@@ -68,6 +94,10 @@ DEEPSOURCE_ENDPOINTS: dict[str, DeepsourceEndpointConfig] = {
primary_keys=["id"],
connection_field="dependencyVulnerabilityOccurrences",
),
+ "analyzers": DeepsourceEndpointConfig(
+ primary_keys=["id"],
+ root_connection_field="analyzers",
+ ),
"metrics": DeepsourceEndpointConfig(
primary_keys=["id"],
per_repository_object=True,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/source.py
index cfede2d2842e..a844c4697a26 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/source.py
@@ -34,9 +34,12 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
_ENDPOINT_DESCRIPTIONS: dict[str, str] = {
"repositories": "All repositories in the account, including ones not activated on DeepSource",
"analysis_runs": "One row per analysis run with its status and occurrence summary",
+ "checks": "One row per analyzer check inside an analysis run, with the issues it introduced and resolved",
+ "pull_requests": "Pull requests analyzed by DeepSource, with the issues and vulnerabilities each one raised",
"issues": "Currently open issue types per repository with category, severity, and occurrence count",
"issue_occurrences": "Every open occurrence of an issue with its file path and position",
"vulnerability_occurrences": "Dependency vulnerabilities (SCA) with CVSS/EPSS scores per repository",
+ "analyzers": "Every analyzer DeepSource offers, resolving the shortcodes carried on issues and checks",
"metrics": "Latest value per code-quality metric and language (coverage, duplication, and more)",
"reports": "Current value and status of each compliance and trend report (OWASP Top 10, code health, and more)",
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/tests/test_deepsource.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/tests/test_deepsource.py
index 4e38f0568c0d..e0d4384fb6ba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/tests/test_deepsource.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/tests/test_deepsource.py
@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.deepsource
_per_repository_object_rows,
_report_rows,
_repositories_rows,
+ _root_connection_rows,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.source import DeepsourceSource
@@ -49,6 +50,27 @@ def _connection_response(
return response
+def _root_connection_response(
+ connection_field: str,
+ nodes: list[dict[str, Any]],
+ has_next_page: bool,
+ end_cursor: str | None,
+) -> MagicMock:
+ """A connection that sits directly on the root query, with no parent object."""
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ response.json.return_value = {
+ "data": {
+ connection_field: {
+ "edges": [{"node": node} for node in nodes],
+ "pageInfo": {"hasNextPage": has_next_page, "endCursor": end_cursor},
+ }
+ }
+ }
+ return response
+
+
def _null_parent_response(parent_field: str) -> MagicMock:
response = MagicMock()
response.status_code = 200
@@ -144,6 +166,16 @@ class TestRepositoriesPagination:
with pytest.raises(Exception, match="endCursor is empty"):
list(_repositories_rows(session, "acme", "GITHUB", MagicMock(), _make_manager()))
+ def test_stalled_cursor_raises_instead_of_refetching_the_same_page(self) -> None:
+ session = MagicMock()
+ session.post.side_effect = [
+ _connection_response("account", "repositories", [{"id": "a"}], True, "c1"),
+ _connection_response("account", "repositories", [{"id": "a"}], True, "c1"),
+ ]
+
+ with pytest.raises(Exception, match="endCursor did not advance past 'c1'"):
+ list(_repositories_rows(session, "acme", "GITHUB", MagicMock(), _make_manager()))
+
def test_missing_account_raises_actionable_error(self) -> None:
session = MagicMock()
session.post.side_effect = [_null_parent_response("account")]
@@ -242,6 +274,152 @@ class TestFanOut:
)
+class TestChecksFanOut:
+ """Checks ride nested inside the analysis-run walk, so one run page can expand into many rows."""
+
+ @staticmethod
+ def _run_node(run_id: str, checks: list[dict[str, Any]], has_next_page: bool, end_cursor: str | None) -> dict:
+ return {
+ "id": run_id,
+ "runUid": f"uid-{run_id}",
+ "commitOid": "abc123",
+ "branchName": "main",
+ "checks": {
+ "edges": [{"node": check} for check in checks],
+ "pageInfo": {"hasNextPage": has_next_page, "endCursor": end_cursor},
+ },
+ }
+
+ def test_each_run_expands_into_one_row_per_check(self) -> None:
+ session = MagicMock()
+ _capture_post_calls(
+ session,
+ [
+ _repo_names_response([("alpha", True)]),
+ _connection_response(
+ "repository",
+ "analysisRuns",
+ [
+ self._run_node("run-1", [{"id": "chk-1"}, {"id": "chk-2"}], False, None),
+ self._run_node("run-2", [{"id": "chk-3"}], False, None),
+ ],
+ False,
+ None,
+ parent_extra={"id": "RID", "name": "alpha"},
+ ),
+ ],
+ )
+
+ pages = list(_fan_out_connection_rows(session, "acme", "GITHUB", "checks", MagicMock(), _make_manager()))
+
+ rows = [row for page in pages for row in page]
+ assert [row["id"] for row in rows] == ["chk-1", "chk-2", "chk-3"]
+ assert [row["analysisRunId"] for row in rows] == ["run-1", "run-1", "run-2"]
+ assert all(row["repositoryId"] == "RID" and row["repositoryName"] == "alpha" for row in rows)
+ assert all(row["analysisRunUid"] == f"uid-{row['analysisRunId']}" for row in rows)
+
+ def test_run_with_more_checks_than_one_page_is_followed_up(self) -> None:
+ session = MagicMock()
+ snapshots = _capture_post_calls(
+ session,
+ [
+ _repo_names_response([("alpha", True)]),
+ _connection_response(
+ "repository",
+ "analysisRuns",
+ [self._run_node("run-1", [{"id": "chk-1"}], True, "check-c1")],
+ False,
+ None,
+ parent_extra={"id": "RID", "name": "alpha"},
+ ),
+ _connection_response("node", "checks", [{"id": "chk-2"}], False, None),
+ ],
+ )
+
+ pages = list(_fan_out_connection_rows(session, "acme", "GITHUB", "checks", MagicMock(), _make_manager()))
+
+ rows = [row for page in pages for row in page]
+ assert [row["id"] for row in rows] == ["chk-1", "chk-2"]
+ # The follow-up resumes the run's own check connection, not the analysis-run walk.
+ assert snapshots[2] == {"id": "run-1", "checkPageSize": 50, "cursor": "check-c1"}
+ # The trailing check still carries the run and repository context.
+ assert rows[1]["analysisRunId"] == "run-1" and rows[1]["repositoryName"] == "alpha"
+
+ def test_run_lost_during_check_follow_up_raises(self) -> None:
+ session = MagicMock()
+ _capture_post_calls(
+ session,
+ [
+ _repo_names_response([("alpha", True)]),
+ _connection_response(
+ "repository",
+ "analysisRuns",
+ [self._run_node("run-1", [{"id": "chk-1"}], True, "check-c1")],
+ False,
+ None,
+ parent_extra={"id": "RID", "name": "alpha"},
+ ),
+ _null_parent_response("node"),
+ ],
+ )
+
+ # Skipping instead would checkpoint run-1 as complete with only its first check page.
+ with pytest.raises(Exception, match="analysis run run-1 disappeared"):
+ list(_fan_out_connection_rows(session, "acme", "GITHUB", "checks", MagicMock(), _make_manager()))
+
+ def test_truncated_check_page_raises_rather_than_dropping_checks(self) -> None:
+ session = MagicMock()
+ _capture_post_calls(
+ session,
+ [
+ _repo_names_response([("alpha", True)]),
+ _connection_response(
+ "repository",
+ "analysisRuns",
+ [self._run_node("run-1", [{"id": "chk-1"}], True, None)],
+ False,
+ None,
+ parent_extra={"id": "RID", "name": "alpha"},
+ ),
+ ],
+ )
+
+ with pytest.raises(Exception, match="endCursor is empty for checks"):
+ list(_fan_out_connection_rows(session, "acme", "GITHUB", "checks", MagicMock(), _make_manager()))
+
+
+class TestRootConnection:
+ def test_analyzers_paginate_and_checkpoint_without_an_account(self) -> None:
+ session = MagicMock()
+ responses = [
+ _root_connection_response("analyzers", [{"id": "an-1", "shortcode": "python"}], True, "c1"),
+ _root_connection_response("analyzers", [{"id": "an-2", "shortcode": "go"}], False, None),
+ ]
+ snapshots = _capture_post_calls(session, responses)
+
+ manager = _make_manager()
+ pages = list(_root_connection_rows(session, "analyzers", MagicMock(), manager))
+
+ assert [row["id"] for page in pages for row in page] == ["an-1", "an-2"]
+ # The analyzer catalog is account-independent, so the query carries no account filter.
+ assert all("login" not in snapshot for snapshot in snapshots)
+ manager.save_state.assert_called_once_with(DeepsourceResumeConfig(cursor="c1"))
+
+ def test_analyzers_resume_from_saved_cursor(self) -> None:
+ session = MagicMock()
+ snapshots = _capture_post_calls(
+ session, [_root_connection_response("analyzers", [{"id": "an-3"}], False, None)]
+ )
+
+ list(
+ _root_connection_rows(
+ session, "analyzers", MagicMock(), _make_manager(DeepsourceResumeConfig(cursor="saved"))
+ )
+ )
+
+ assert snapshots[0]["cursor"] == "saved"
+
+
class TestPerRepositoryObjects:
def test_metrics_rows_flattened_per_item(self) -> None:
metrics_response = MagicMock()