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(data-warehouse): implement deepsource import source (#71242)

Tom Owers9296974d9a52
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index ae7f973a6609..4f28d9cbfd6b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -145,6 +145,7 @@ the row lists both.
| decagon | HTTP | requests | ✅ |
| deel | HTTP | requests | ✅ |
| deepgram | HTTP | requests | ✅ |
+| deepsource | HTTP (GraphQL) | requests | ✅ |
| delighted | HTTP | requests | ✅ |
| deno_deploy | HTTP | requests | ✅ |
| devin_ai | HTTP | requests | ✅ |
@@ -597,7 +598,6 @@ doesn't conflict with concurrent PRs.
- datascope
- datorama
- db2
-- deepsource
- deno_deploy
- deputy
- display_video_360
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
new file mode 100644
index 000000000000..fda0bb7a8db5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/canonical_descriptions.py
@@ -0,0 +1,114 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://docs.deepsource.com/docs/developers/api"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "repositories": {
+ "description": "A repository in the DeepSource account, including repositories not yet activated for analysis.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Relay global ID of the repository, unique across DeepSource.",
+ "name": "Name of the repository as it appears on the VCS provider.",
+ "vcsProvider": "Version control system hosting the repository (GITHUB, GITLAB, BITBUCKET, ...).",
+ "vcsUrl": "URL of the repository on the VCS provider.",
+ "defaultBranch": "Default branch analyzed by DeepSource.",
+ "isPrivate": "Whether the repository is private on the VCS provider.",
+ "isActivated": "Whether analysis is activated for this repository on DeepSource.",
+ "latestCommitOid": "Commit SHA of the latest analyzed commit.",
+ },
+ },
+ "analysis_runs": {
+ "description": "A single DeepSource analysis run on a commit or branch, with its status and a summary of occurrences introduced and resolved.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Relay global ID of the analysis run.",
+ "runUid": "UUID of the analysis run, used to look up a run directly.",
+ "commitOid": "Commit SHA the run analyzed.",
+ "baseOid": "Base commit SHA the run compared against.",
+ "branchName": "Branch the analyzed commit belongs to.",
+ "status": "Run status (PENDING, SUCCESS, FAILURE, TIMEOUT, CANCEL, READY, SKIPPED).",
+ "createdAt": "When the run was created.",
+ "updatedAt": "When the run was last updated.",
+ "finishedAt": "When the run finished, if it has.",
+ "summary": "Counts of occurrences introduced, resolved, and suppressed by this run.",
+ "repositoryId": "Relay global ID of the repository the run belongs to.",
+ "repositoryName": "Name of the repository the run 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,
+ "columns": {
+ "id": "Relay global ID of the repository issue.",
+ "issue": "The issue definition: shortcode, title, category, severity, tags, and the analyzer that raises it.",
+ "occurrences": "Total count of open occurrences of this issue in the repository.",
+ "repositoryId": "Relay global ID of the repository the issue is raised in.",
+ "repositoryName": "Name of the repository the issue is raised in.",
+ },
+ },
+ "issue_occurrences": {
+ "description": "A single occurrence of an issue in a repository: the exact file and position where the issue is raised.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Relay global ID of the occurrence.",
+ "path": "File path where the issue occurs.",
+ "beginLine": "Line where the occurrence starts.",
+ "beginColumn": "Column where the occurrence starts.",
+ "endLine": "Line where the occurrence ends.",
+ "endColumn": "Column where the occurrence ends.",
+ "title": "Title of the occurrence.",
+ "issue": "The issue definition this occurrence belongs to: shortcode, category, severity, and analyzer.",
+ "repositoryId": "Relay global ID of the repository the occurrence is in.",
+ "repositoryName": "Name of the repository the occurrence is in.",
+ },
+ },
+ "vulnerability_occurrences": {
+ "description": "A dependency vulnerability detected by DeepSource software composition analysis, with reachability, fixability, and CVSS/EPSS scoring.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Relay global ID of the vulnerability occurrence.",
+ "reachability": "Whether the vulnerable code path is reachable from the repository's code.",
+ "fixability": "Whether and how the vulnerability can be fixed (e.g. by upgrading the dependency).",
+ "package": "The vulnerable package: name, ecosystem, and purl.",
+ "packageVersion": "The installed version of the vulnerable package.",
+ "vulnerability": "The vulnerability record: identifier (e.g. CVE), severity, CVSS and EPSS scores, affected and fixed versions.",
+ "repositoryId": "Relay global ID of the repository the vulnerability was found in.",
+ "repositoryName": "Name of the repository the vulnerability was found in.",
+ },
+ },
+ "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,
+ "columns": {
+ "id": "Relay global ID of the metric item.",
+ "key": "Language or aggregation key the value applies to (AGGREGATE, PYTHON, GO, ...).",
+ "threshold": "Configured threshold for the metric, if any.",
+ "latestValue": "Latest reported value of the metric.",
+ "latestValueDisplay": "Latest value formatted for display, including the unit.",
+ "thresholdStatus": "Whether the latest value passes or fails the configured threshold.",
+ "metricShortcode": "Shortcode of the metric (e.g. LCV for line coverage, DDP for duplicate code).",
+ "metricName": "Human-readable name of the metric.",
+ "metricDescription": "Description of what the metric measures.",
+ "metricUnit": "Unit of the metric value (e.g. %).",
+ "positiveDirection": "Whether higher or lower values are better for this metric.",
+ "isReported": "Whether the metric is currently reported for the repository.",
+ "isThresholdEnforced": "Whether the threshold is enforced on analysis runs.",
+ "repositoryId": "Relay global ID of the repository the metric belongs to.",
+ "repositoryName": "Name of the repository the metric belongs to.",
+ },
+ },
+ "reports": {
+ "description": "The current value and status of each DeepSource report per repository, such as OWASP Top 10 compliance or code health trend.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "key": "Report key (OWASP_TOP_10, SANS_TOP_25, MISRA_C, CODE_HEALTH_TREND, ISSUE_DISTRIBUTION, ISSUES_PREVENTED, ISSUES_AUTOFIXED).",
+ "title": "Human-readable title of the report.",
+ "currentValue": "Current value of the report metric.",
+ "status": "Compliance status (only on security reports: OWASP Top 10, SANS Top 25, MISRA C).",
+ "repositoryId": "Relay global ID of the repository the report belongs to.",
+ "repositoryName": "Name of the repository the report belongs to.",
+ },
+ },
+}
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
new file mode 100644
index 000000000000..c4ec613acb9a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/deepsource.py
@@ -0,0 +1,483 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.queries import (
+ CONNECTION_QUERIES,
+ PER_REPOSITORY_QUERIES,
+ REPOSITORIES_QUERY,
+ REPOSITORY_NAMES_QUERY,
+ VALIDATE_QUERY,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.settings import (
+ DEEPSOURCE_API_URL,
+ DEEPSOURCE_DEFAULT_PAGE_SIZE,
+ DEEPSOURCE_ENDPOINTS,
+ DEEPSOURCE_MAX_PAGES_PER_CONNECTION,
+ DEEPSOURCE_REPOSITORY_LIST_PAGE_SIZE,
+)
+
+DEEPSOURCE_MAX_RETRY_ATTEMPTS = 8
+# DeepSource rate-limits at 5,000 requests/hour and answers overages with HTTP 429. Cap a
+# misbehaving Retry-After so one header can't pin the activity open indefinitely; genuine
+# hour-long exhaustion falls through to Temporal rescheduling the activity, which resumes
+# from the saved cursor.
+DEEPSOURCE_MAX_RETRY_AFTER_SECONDS = 300
+_DEEPSOURCE_FALLBACK_WAIT = wait_exponential_jitter(initial=1, max=60)
+
+
+class DeepsourceRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+def _parse_retry_after(response: requests.Response) -> float | None:
+ raw = response.headers.get("Retry-After")
+ if raw is None:
+ return None
+ try:
+ seconds = float(raw)
+ except (TypeError, ValueError):
+ return None
+ return max(0.0, seconds)
+
+
+def _wait_strategy(retry_state: RetryCallState) -> float:
+ """Honor a 429's Retry-After when present, else fall back to jittered exponential backoff."""
+ exc = retry_state.outcome.exception() if retry_state.outcome is not None else None
+ if isinstance(exc, DeepsourceRetryableError) and exc.retry_after is not None:
+ return min(exc.retry_after, DEEPSOURCE_MAX_RETRY_AFTER_SECONDS)
+ return _DEEPSOURCE_FALLBACK_WAIT(retry_state)
+
+
+class DeepsourceResumeConfig:
+ # Repositories whose fan-out walk finished in this job; skipped on resume.
+ completed_repositories: list[str] = dataclasses.field(default_factory=list)
+ # Repository currently being walked, resumed at `cursor`.
+ current_repository: str | None = None
+ # Relay endCursor of the next page to fetch (the account repositories connection for
+ # the `repositories` endpoint, the per-repository connection for fan-out endpoints).
+ cursor: str | None = None
+
+
+def _make_session(api_token: str) -> requests.Session:
+ return make_tracked_session(
+ headers={
+ "Authorization": f"Bearer {api_token}",
+ "Content-Type": "application/json",
+ }
+ )
+
+
+@retry(
+ retry=retry_if_exception_type(DeepsourceRetryableError),
+ stop=stop_after_attempt(DEEPSOURCE_MAX_RETRY_ATTEMPTS),
+ wait=_wait_strategy,
+ reraise=True,
+)
+def _execute(
+ session: requests.Session,
+ query: str,
+ variables: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ try:
+ response = session.post(DEEPSOURCE_API_URL, json={"query": query, "variables": variables}, timeout=60)
+ except (requests.ConnectionError, requests.Timeout) as e:
+ # The tracked session's urllib3 retry only covers idempotent methods, so these POSTs
+ # get no transport-level retry; fold transient network failures into the backoff here.
+ raise DeepsourceRetryableError(f"DeepSource: transient network error - {e}")
+
+ if response.status_code >= 500:
+ raise DeepsourceRetryableError(f"DeepSource: server error {response.status_code}")
+
+ if response.status_code == 429:
+ raise DeepsourceRetryableError("DeepSource: rate limited (429)", retry_after=_parse_retry_after(response))
+
+ if response.status_code in (401, 403):
+ # Auth failures return a plain JSON body ({"message": "Authentication required"}),
+ # not a GraphQL payload. Raise with the stable status text so
+ # get_non_retryable_errors can match it and stop the sync.
+ detail = ""
+ try:
+ body = response.json()
+ if isinstance(body, dict) and body.get("message"):
+ detail = f" (DeepSource API: {body['message']})"
+ except Exception:
+ pass
+ raise Exception(f"{response.status_code} Client Error: {response.reason} for url: {DEEPSOURCE_API_URL}{detail}")
+
+ try:
+ payload = response.json()
+ except Exception as e:
+ if not response.ok:
+ raise Exception(
+ f"{response.status_code} Client Error: {response.reason} for url: {DEEPSOURCE_API_URL}"
+ ) from e
+ # A 2xx whose body won't parse is almost always a truncated transfer, not a stable
+ # response. Retry it; don't echo response.text — a partial body carries data.
+ raise DeepsourceRetryableError(f"DeepSource: incomplete JSON response ({e})") from e
+
+ if "errors" in payload:
+ error_messages = [e.get("message", "") for e in payload["errors"] if isinstance(e, dict)]
+ joined = "; ".join(error_messages)
+ raise Exception(f"DeepSource GraphQL error: {joined}")
+
+ if not response.ok:
+ raise Exception(f"{response.status_code} Client Error: {response.reason} for url: {DEEPSOURCE_API_URL}")
+
+ if "data" not in payload:
+ raise Exception(f"Unexpected DeepSource response format. Keys: {list(payload.keys())}")
+
+ return payload
+
+
+def _iter_connection(
+ session: requests.Session,
+ query: str,
+ variables: dict[str, Any],
+ parent_field: str,
+ connection_field: str,
+ logger: FilteringBoundLogger,
+ start_cursor: str | None = None,
+ missing_parent_error: str | None = None,
+) -> 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.
+
+ 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).
+ """
+ cursor = start_cursor
+ page_count = 0
+ while True:
+ payload = _execute(session, query, {**variables, "cursor": cursor}, logger)
+ parent = payload["data"].get(parent_field)
+ if parent is None:
+ if missing_parent_error:
+ raise Exception(missing_parent_error)
+ logger.warning(f"DeepSource: {parent_field} not found, skipping", variables=variables)
+ return
+
+ connection = parent.get(connection_field) or {}
+ nodes = [edge["node"] for edge in connection.get("edges") or [] if edge and edge.get("node")]
+ page_info = connection.get("pageInfo") or {}
+ has_next_page = bool(page_info.get("hasNextPage"))
+ end_cursor = page_info.get("endCursor")
+
+ if has_next_page and not end_cursor:
+ # hasNextPage=True with a null endCursor would loop on the same page forever;
+ # fail loudly instead of silently returning partial results.
+ raise Exception(f"DeepSource: hasNextPage=True but endCursor is empty for {connection_field}")
+
+ yield parent, nodes, end_cursor, has_next_page
+
+ if not has_next_page:
+ return
+
+ page_count += 1
+ if page_count >= DEEPSOURCE_MAX_PAGES_PER_CONNECTION:
+ logger.warning(
+ "DeepSource: per-connection page cap reached; remaining pages skipped",
+ connection_field=connection_field,
+ max_pages=DEEPSOURCE_MAX_PAGES_PER_CONNECTION,
+ variables=variables,
+ )
+ return
+
+ cursor = end_cursor
+
+
+def _account_variables(account_login: str, vcs_provider: str) -> dict[str, Any]:
+ return {"login": account_login, "vcsProvider": vcs_provider}
+
+
+def _repositories_rows(
+ session: requests.Session,
+ account_login: str,
+ vcs_provider: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DeepsourceResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_cursor = resume.cursor if resume else None
+ if start_cursor:
+ logger.debug("DeepSource: resuming repositories from saved cursor")
+
+ variables = {**_account_variables(account_login, vcs_provider), "pageSize": DEEPSOURCE_DEFAULT_PAGE_SIZE}
+ for _parent, nodes, end_cursor, has_next_page in _iter_connection(
+ session,
+ REPOSITORIES_QUERY,
+ variables,
+ "account",
+ "repositories",
+ logger,
+ start_cursor=start_cursor,
+ missing_parent_error=_account_not_found_error(account_login, vcs_provider),
+ ):
+ if nodes:
+ yield nodes
+ # Checkpoint points at the next page; on resume the walk continues from there.
+ if has_next_page:
+ resumable_source_manager.save_state(DeepsourceResumeConfig(cursor=end_cursor))
+
+
+def _account_not_found_error(account_login: str, vcs_provider: str) -> str:
+ return (
+ f"DeepSource account not found: '{account_login}' ({vcs_provider}). "
+ "Check the account login and VCS provider, and that your token has access to it."
+ )
+
+
+def _list_activated_repository_names(
+ session: requests.Session,
+ account_login: str,
+ vcs_provider: str,
+ logger: FilteringBoundLogger,
+) -> list[str]:
+ """Enumerate activated repositories to drive fan-out. Repositories that aren't activated
+ on DeepSource have no analysis data, so querying them would only burn rate limit."""
+ names: list[str] = []
+ total = 0
+ variables = {**_account_variables(account_login, vcs_provider), "pageSize": DEEPSOURCE_REPOSITORY_LIST_PAGE_SIZE}
+ for _parent, nodes, _end_cursor, _has_next_page in _iter_connection(
+ session,
+ REPOSITORY_NAMES_QUERY,
+ variables,
+ "account",
+ "repositories",
+ logger,
+ missing_parent_error=_account_not_found_error(account_login, vcs_provider),
+ ):
+ total += len(nodes)
+ names.extend(node["name"] for node in nodes if node.get("isActivated"))
+
+ logger.debug(f"DeepSource: fanning out over {len(names)} activated repositories (of {total} total)")
+ return names
+
+
+def _with_repository_context(node: dict[str, Any], repository: dict[str, Any]) -> dict[str, Any]:
+ return {**node, "repositoryId": repository.get("id"), "repositoryName": repository.get("name")}
+
+
+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]] = []
+ for metric in repository.get("metrics") or []:
+ for item in metric.get("items") or []:
+ rows.append(
+ {
+ "id": item.get("id"),
+ "key": item.get("key"),
+ "threshold": item.get("threshold"),
+ "latestValue": item.get("latestValue"),
+ "latestValueDisplay": item.get("latestValueDisplay"),
+ "thresholdStatus": item.get("thresholdStatus"),
+ "metricShortcode": metric.get("shortcode"),
+ "metricName": metric.get("name"),
+ "metricDescription": metric.get("description"),
+ "metricUnit": metric.get("unit"),
+ "positiveDirection": metric.get("positiveDirection"),
+ "isReported": metric.get("isReported"),
+ "isThresholdEnforced": metric.get("isThresholdEnforced"),
+ "repositoryId": repository.get("id"),
+ "repositoryName": repository.get("name"),
+ }
+ )
+ return rows
+
+
+def _report_rows(repository: dict[str, Any]) -> list[dict[str, Any]]:
+ """Flatten the repository.reports namespace into one row per report key."""
+ rows: list[dict[str, Any]] = []
+ for report in (repository.get("reports") or {}).values():
+ if not isinstance(report, dict):
+ continue
+ rows.append(
+ {
+ "key": report.get("key"),
+ "title": report.get("title"),
+ "currentValue": report.get("currentValue"),
+ # Only the security reports expose a status; the trend reports carry null.
+ "status": report.get("status"),
+ "repositoryId": repository.get("id"),
+ "repositoryName": repository.get("name"),
+ }
+ )
+ return rows
+
+
+_PER_REPOSITORY_ROW_BUILDERS = {
+ "metrics": _metric_rows,
+ "reports": _report_rows,
+}
+
+
+def _fan_out_connection_rows(
+ session: requests.Session,
+ account_login: str,
+ vcs_provider: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DeepsourceResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Paginated per-repository fan-out (analysis runs, issues, occurrences)."""
+ query = CONNECTION_QUERIES[endpoint]
+ connection_field = DEEPSOURCE_ENDPOINTS[endpoint].connection_field
+ assert connection_field is not None
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ completed = set(resume.completed_repositories) if resume else set()
+ if resume:
+ logger.debug(
+ f"DeepSource: resuming {endpoint} fan-out, {len(completed)} repositories already completed",
+ )
+
+ for repository_name in _list_activated_repository_names(session, account_login, vcs_provider, logger):
+ if repository_name in completed:
+ continue
+
+ # Community reports note DeepSource cursors can expire; if a stale resume cursor is
+ # rejected the sync fails and Temporal retries — the Redis state expires within 24h,
+ # bounding the worst case. Kept simple on purpose until observed in practice.
+ start_cursor = resume.cursor if resume and resume.current_repository == repository_name else None
+ variables = {
+ **_account_variables(account_login, vcs_provider),
+ "name": repository_name,
+ "pageSize": DEEPSOURCE_DEFAULT_PAGE_SIZE,
+ }
+ for parent, nodes, end_cursor, has_next_page in _iter_connection(
+ session,
+ query,
+ variables,
+ "repository",
+ connection_field,
+ logger,
+ start_cursor=start_cursor,
+ ):
+ if nodes:
+ yield [_with_repository_context(node, parent) for node in nodes]
+ if has_next_page:
+ resumable_source_manager.save_state(
+ DeepsourceResumeConfig(
+ completed_repositories=sorted(completed),
+ current_repository=repository_name,
+ cursor=end_cursor,
+ )
+ )
+
+ completed.add(repository_name)
+ resumable_source_manager.save_state(DeepsourceResumeConfig(completed_repositories=sorted(completed)))
+
+
+def _per_repository_object_rows(
+ session: requests.Session,
+ account_login: str,
+ vcs_provider: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DeepsourceResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Non-paginated per-repository fan-out (metrics, reports): one query per repository."""
+ query = PER_REPOSITORY_QUERIES[endpoint]
+ build_rows = _PER_REPOSITORY_ROW_BUILDERS[endpoint]
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ completed = set(resume.completed_repositories) if resume else set()
+
+ for repository_name in _list_activated_repository_names(session, account_login, vcs_provider, logger):
+ if repository_name in completed:
+ continue
+
+ variables = {**_account_variables(account_login, vcs_provider), "name": repository_name}
+ payload = _execute(session, query, variables, logger)
+ repository = payload["data"].get("repository")
+ if repository is None:
+ logger.warning("DeepSource: repository not found, skipping", repository=repository_name)
+ else:
+ rows = build_rows(repository)
+ if rows:
+ yield rows
+
+ completed.add(repository_name)
+ resumable_source_manager.save_state(DeepsourceResumeConfig(completed_repositories=sorted(completed)))
+
+
+def deepsource_source(
+ api_token: str,
+ account_login: str,
+ vcs_provider: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DeepsourceResumeConfig],
+) -> SourceResponse:
+ endpoint_config = DEEPSOURCE_ENDPOINTS.get(endpoint)
+ if not endpoint_config:
+ raise ValueError(f"Unknown DeepSource endpoint: {endpoint}")
+
+ def get_rows() -> Iterator[list[dict[str, Any]]]:
+ session = _make_session(api_token)
+ try:
+ if endpoint == "repositories":
+ yield from _repositories_rows(session, account_login, vcs_provider, 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
+ )
+ else:
+ yield from _fan_out_connection_rows(
+ session, account_login, vcs_provider, endpoint, logger, resumable_source_manager
+ )
+ finally:
+ session.close()
+
+ return SourceResponse(
+ items=get_rows,
+ primary_keys=endpoint_config.primary_keys,
+ name=endpoint,
+ partition_count=1 if endpoint_config.partition_mode else None,
+ partition_size=1 if endpoint_config.partition_mode else None,
+ partition_mode=endpoint_config.partition_mode,
+ partition_format=endpoint_config.partition_format,
+ partition_keys=endpoint_config.partition_keys,
+ )
+
+
+def validate_credentials(api_token: str, account_login: str, vcs_provider: str) -> tuple[bool, str | None]:
+ session = _make_session(api_token)
+ try:
+ response = session.post(
+ DEEPSOURCE_API_URL,
+ json={"query": VALIDATE_QUERY, "variables": _account_variables(account_login, vcs_provider)},
+ timeout=10,
+ )
+
+ if response.status_code in (401, 403):
+ return False, "Invalid DeepSource personal access token"
+
+ response.raise_for_status()
+ payload = response.json()
+ data = payload.get("data") or {}
+
+ # The token can be genuine while the configured account is wrong or inaccessible —
+ # DeepSource resolves `account` to null (with or without a GraphQL error) in that case.
+ if data.get("viewer") and data.get("account"):
+ return True, None
+ if data.get("viewer"):
+ return False, _account_not_found_error(account_login, vcs_provider)
+ if "errors" in payload:
+ error_messages = [e.get("message", "") for e in payload["errors"] if isinstance(e, dict)]
+ return False, f"DeepSource API error: {'; '.join(error_messages)}"
+ return False, "Could not verify DeepSource credentials"
+ except Exception as e:
+ return False, str(e)
+ finally:
+ session.close()
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
new file mode 100644
index 000000000000..afc8b631459d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/queries.py
@@ -0,0 +1,215 @@
+# GraphQL queries for the DeepSource API (https://api.deepsource.com/graphql/).
+# Field names verified against the live schema via introspection; DeepSource uses
+# Relay-style connections (first/after + pageInfo.hasNextPage/endCursor) everywhere.
+
+REPOSITORIES_QUERY = """
+query Repositories($login: String!, $vcsProvider: VCSProvider!, $pageSize: Int!, $cursor: String) {
+ account(login: $login, vcsProvider: $vcsProvider) {
+ repositories(first: $pageSize, after: $cursor) {
+ pageInfo { hasNextPage endCursor }
+ edges { node {
+ id
+ name
+ vcsProvider
+ vcsUrl
+ defaultBranch
+ isPrivate
+ isActivated
+ latestCommitOid
+ } }
+ }
+ }
+}"""
+
+# Cheap enumeration used to drive per-repository fan-out; only activated repositories
+# have analysis data worth querying.
+REPOSITORY_NAMES_QUERY = """
+query RepositoryNames($login: String!, $vcsProvider: VCSProvider!, $pageSize: Int!, $cursor: String) {
+ account(login: $login, vcsProvider: $vcsProvider) {
+ repositories(first: $pageSize, after: $cursor) {
+ pageInfo { hasNextPage endCursor }
+ edges { node { name isActivated } }
+ }
+ }
+}"""
+
+ANALYSIS_RUNS_QUERY = """
+query AnalysisRuns($login: String!, $vcsProvider: VCSProvider!, $name: String!, $pageSize: Int!, $cursor: String) {
+ repository(login: $login, vcsProvider: $vcsProvider, name: $name) {
+ id
+ name
+ analysisRuns(first: $pageSize, after: $cursor) {
+ pageInfo { hasNextPage endCursor }
+ edges { node {
+ id
+ runUid
+ commitOid
+ baseOid
+ branchName
+ status
+ createdAt
+ updatedAt
+ finishedAt
+ summary {
+ occurrencesIntroduced
+ occurrencesResolved
+ occurrencesSuppressed
+ vulnerabilitiesIntroduced
+ }
+ } }
+ }
+ }
+}"""
+
+ISSUES_QUERY = """
+query RepositoryIssues($login: String!, $vcsProvider: VCSProvider!, $name: String!, $pageSize: Int!, $cursor: String) {
+ repository(login: $login, vcsProvider: $vcsProvider, name: $name) {
+ id
+ name
+ issues(first: $pageSize, after: $cursor) {
+ pageInfo { hasNextPage endCursor }
+ edges { node {
+ id
+ issue {
+ shortcode
+ title
+ category
+ severity
+ autofixAvailable
+ isRecommended
+ tags
+ analyzer { shortcode name }
+ }
+ occurrences { totalCount }
+ } }
+ }
+ }
+}"""
+
+ISSUE_OCCURRENCES_QUERY = """
+query IssueOccurrences($login: String!, $vcsProvider: VCSProvider!, $name: String!, $pageSize: Int!, $cursor: String) {
+ repository(login: $login, vcsProvider: $vcsProvider, name: $name) {
+ id
+ name
+ issueOccurrences(first: $pageSize, after: $cursor) {
+ pageInfo { hasNextPage endCursor }
+ edges { node {
+ id
+ path
+ beginLine
+ beginColumn
+ endLine
+ endColumn
+ title
+ issue {
+ shortcode
+ category
+ severity
+ analyzer { shortcode }
+ }
+ } }
+ }
+ }
+}"""
+
+VULNERABILITY_OCCURRENCES_QUERY = """
+query VulnerabilityOccurrences($login: String!, $vcsProvider: VCSProvider!, $name: String!, $pageSize: Int!, $cursor: String) {
+ repository(login: $login, vcsProvider: $vcsProvider, name: $name) {
+ id
+ name
+ dependencyVulnerabilityOccurrences(first: $pageSize, after: $cursor) {
+ pageInfo { hasNextPage endCursor }
+ edges { node {
+ id
+ reachability
+ fixability
+ package { id name ecosystem purl }
+ packageVersion { id version versionType }
+ vulnerability {
+ id
+ identifier
+ severity
+ summary
+ publishedAt
+ updatedAt
+ withdrawnAt
+ cvssV2BaseScore
+ cvssV3BaseScore
+ cvssV4BaseScore
+ epssScore
+ epssPercentile
+ aliases
+ introducedVersions
+ fixedVersions
+ referenceUrls
+ }
+ } }
+ }
+ }
+}"""
+
+METRICS_QUERY = """
+query RepositoryMetrics($login: String!, $vcsProvider: VCSProvider!, $name: String!) {
+ repository(login: $login, vcsProvider: $vcsProvider, name: $name) {
+ id
+ name
+ metrics {
+ name
+ shortcode
+ description
+ positiveDirection
+ unit
+ minValueAllowed
+ maxValueAllowed
+ isReported
+ isThresholdEnforced
+ items {
+ id
+ key
+ threshold
+ latestValue
+ latestValueDisplay
+ thresholdStatus
+ }
+ }
+ }
+}"""
+
+# The security reports (owaspTop10, sansTop25, misraC) expose a status; the trend-style
+# reports don't, so their rows carry status = null.
+REPORTS_QUERY = """
+query RepositoryReports($login: String!, $vcsProvider: VCSProvider!, $name: String!) {
+ repository(login: $login, vcsProvider: $vcsProvider, name: $name) {
+ id
+ name
+ reports {
+ owaspTop10 { key title currentValue status }
+ sansTop25 { key title currentValue status }
+ misraC { key title currentValue status }
+ codeHealthTrend { key title currentValue }
+ issueDistribution { key title currentValue }
+ issuesPrevented { key title currentValue }
+ issuesAutofixed { key title currentValue }
+ }
+ }
+}"""
+
+# Create-time credential probe: `viewer` confirms the token is genuine, `account`
+# confirms the configured login/provider is reachable with it.
+VALIDATE_QUERY = """
+query Validate($login: String!, $vcsProvider: VCSProvider!) {
+ viewer { email }
+ account(login: $login, vcsProvider: $vcsProvider) { id }
+}"""
+
+CONNECTION_QUERIES: dict[str, str] = {
+ "analysis_runs": ANALYSIS_RUNS_QUERY,
+ "issues": ISSUES_QUERY,
+ "issue_occurrences": ISSUE_OCCURRENCES_QUERY,
+ "vulnerability_occurrences": VULNERABILITY_OCCURRENCES_QUERY,
+}
+
+PER_REPOSITORY_QUERIES: dict[str, str] = {
+ "metrics": METRICS_QUERY,
+ "reports": REPORTS_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
new file mode 100644
index 000000000000..3df30ce4fbe8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/settings.py
@@ -0,0 +1,81 @@
+from dataclasses import dataclass
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ PartitionFormat,
+ PartitionMode,
+)
+from products.warehouse_sources.backend.types import IncrementalField
+
+DEEPSOURCE_API_URL = "https://api.deepsource.com/graphql/"
+
+# DeepSource enforces a flat 5,000 requests/hour rate limit per user account, so page size
+# is a direct lever on API cost. The docs don't publish a max page size for Relay `first`
+# arguments; 50 is a conservative value verified against similar GraphQL APIs.
+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
+
+# 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.
+DEEPSOURCE_MAX_PAGES_PER_CONNECTION = 2000
+
+CREATED_AT = "createdAt"
+
+# All DeepSource connections are Relay cursor-paginated with no server-side timestamp
+# filter (verified via schema introspection: connection args are only offset/before/
+# after/first/last), so no endpoint qualifies for incremental sync — every schema is
+# full refresh only.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
+
+
+@dataclass
+class DeepsourceEndpointConfig:
+ primary_keys: list[str]
+ # GraphQL connection field on Repository for paginated per-repository fan-out.
+ connection_field: str | None = None
+ # metrics/reports: fetched as one non-paginated query per repository.
+ per_repository_object: bool = False
+ 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")
+
+
+DEEPSOURCE_ENDPOINTS: dict[str, DeepsourceEndpointConfig] = {
+ "repositories": DeepsourceEndpointConfig(
+ primary_keys=["id"],
+ ),
+ "analysis_runs": DeepsourceEndpointConfig(
+ primary_keys=["id"],
+ connection_field="analysisRuns",
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[CREATED_AT],
+ ),
+ "issues": DeepsourceEndpointConfig(
+ primary_keys=["id"],
+ connection_field="issues",
+ ),
+ "issue_occurrences": DeepsourceEndpointConfig(
+ primary_keys=["id"],
+ connection_field="issueOccurrences",
+ ),
+ "vulnerability_occurrences": DeepsourceEndpointConfig(
+ primary_keys=["id"],
+ connection_field="dependencyVulnerabilityOccurrences",
+ ),
+ "metrics": DeepsourceEndpointConfig(
+ primary_keys=["id"],
+ per_repository_object=True,
+ ),
+ "reports": DeepsourceEndpointConfig(
+ primary_keys=["repositoryId", "key"],
+ per_repository_object=True,
+ ),
+}
+
+ENDPOINTS = tuple(DEEPSOURCE_ENDPOINTS.keys())
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 e596bfb82b27..54e26b512343 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
@@ -1,30 +1,181 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.deepsource import (
+ DeepsourceResumeConfig,
+ deepsource_source,
+ validate_credentials as validate_deepsource_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.settings import (
+ DEEPSOURCE_ENDPOINTS,
+ ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DeepsourceSourceConfig
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",
+ "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",
+ "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)",
+}
+
@SourceRegistry.register
-class DeepsourceSource(SimpleSource[DeepsourceSourceConfig]):
+class DeepsourceSource(ResumableSource[DeepsourceSourceConfig, DeepsourceResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.DEEPSOURCE
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The PAT is sent to api.deepsource.com scoped to <account_login>/<vcs_provider>, so
+ # retargeting the account must force re-entry of the token — otherwise an editor who
+ # cannot read the PAT could point it at another account the owner can access.
+ return ["account_login", "vcs_provider"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.DEEPSOURCE,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="DeepSource",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Import your DeepSource static-analysis data — repositories, analysis runs, issues, code-quality metrics, and reports — into the PostHog Data warehouse.
+
+Generate a personal access token from the **Tokens** tab in your [DeepSource user settings](https://app.deepsource.com/). The token is scoped to your account, so it can read every account and repository you have access to.
+
+The account login is the organization or user name exactly as it appears in DeepSource (for a GitHub organization, this is the organization's login).
+""",
iconPath="/static/services/deepsource.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/deepsource",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="Personal access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="account_login",
+ label="Account login",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="my-organization",
+ secret=False,
+ ),
+ SourceFieldSelectConfig(
+ name="vcs_provider",
+ label="VCS provider",
+ required=True,
+ defaultValue="GITHUB",
+ options=[
+ SourceFieldSelectConfigOption(label="GitHub", value="GITHUB"),
+ SourceFieldSelectConfigOption(label="GitLab", value="GITLAB"),
+ SourceFieldSelectConfigOption(label="Bitbucket", value="BITBUCKET"),
+ SourceFieldSelectConfigOption(label="GitHub Enterprise", value="GITHUB_ENTERPRISE"),
+ SourceFieldSelectConfigOption(label="Bitbucket Data Center", value="BITBUCKET_DATACENTER"),
+ SourceFieldSelectConfigOption(label="Azure DevOps Services", value="ADS"),
+ SourceFieldSelectConfigOption(label="Google Source Repositories", value="GSR"),
+ ],
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked PAT surfaces as a 401/403 raised from the GraphQL transport.
+ # Match the stable status text plus the fixed API host, never the variable detail.
+ "401 Client Error: Unauthorized for url: https://api.deepsource.com": "Your DeepSource personal access token is invalid or has been revoked. Generate a new token in your DeepSource user settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.deepsource.com": "Your DeepSource personal access token does not have access to this data. Check the token's account access, then reconnect.",
+ # A wrong account login / VCS provider resolves the account to null — retrying can
+ # never fix the configuration.
+ "DeepSource account not found": "The configured DeepSource account could not be found. Check the account login and VCS provider, and that your token has access to it.",
+ }
+
+ def get_schemas(
+ self,
+ config: DeepsourceSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # No DeepSource connection accepts a server-side timestamp filter (Relay cursor args
+ # only), so every schema is full refresh — see settings.py.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ should_sync_default=DEEPSOURCE_ENDPOINTS[endpoint].should_sync_default,
+ description=_ENDPOINT_DESCRIPTIONS.get(endpoint),
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: DeepsourceSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_deepsource_credentials(config.api_token, config.account_login, config.vcs_provider)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DeepsourceResumeConfig]:
+ return ResumableSourceManager[DeepsourceResumeConfig](inputs, DeepsourceResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: DeepsourceSourceConfig,
+ resumable_source_manager: ResumableSourceManager[DeepsourceResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return deepsource_source(
+ api_token=config.api_token,
+ account_login=config.account_login,
+ vcs_provider=config.vcs_provider,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
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
new file mode 100644
index 000000000000..4e38f0568c0d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/tests/test_deepsource.py
@@ -0,0 +1,451 @@
+import copy
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.deepsource import (
+ DEEPSOURCE_MAX_RETRY_ATTEMPTS,
+ DeepsourceResumeConfig,
+ DeepsourceRetryableError,
+ _fan_out_connection_rows,
+ _metric_rows,
+ _per_repository_object_rows,
+ _report_rows,
+ _repositories_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.source import DeepsourceSource
+
+_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.deepsource.make_tracked_session"
+)
+
+
+def _connection_response(
+ parent_field: str,
+ connection_field: str,
+ nodes: list[dict[str, Any]],
+ has_next_page: bool,
+ end_cursor: str | None,
+ parent_extra: dict[str, Any] | None = None,
+) -> MagicMock:
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ response.json.return_value = {
+ "data": {
+ parent_field: {
+ **(parent_extra or {}),
+ 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
+ response.ok = True
+ response.json.return_value = {"data": {parent_field: None}}
+ return response
+
+
+def _error_response(status_code: int, reason: str, body: dict[str, Any] | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = False
+ response.reason = reason
+ response.headers = {}
+ if body is not None:
+ response.json.return_value = body
+ else:
+ response.json.side_effect = ValueError("no body")
+ return response
+
+
+def _repo_names_response(repos: list[tuple[str, bool]]) -> MagicMock:
+ return _connection_response(
+ "account",
+ "repositories",
+ [{"name": name, "isActivated": activated} for name, activated in repos],
+ False,
+ None,
+ )
+
+
+def _capture_post_calls(session: MagicMock, responses: list[MagicMock]) -> list[dict[str, Any]]:
+ """session.post records a deep-copied snapshot of GraphQL variables per call."""
+ snapshots: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def side_effect(*_args: object, **kwargs: object) -> MagicMock:
+ json_payload = kwargs.get("json")
+ variables = json_payload.get("variables") if isinstance(json_payload, dict) else None
+ snapshots.append(copy.deepcopy(variables) if variables is not None else {})
+ return next(response_iter)
+
+ session.post.side_effect = side_effect
+ return snapshots
+
+
+def _make_manager(saved: DeepsourceResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock()
+ manager.can_resume.return_value = saved is not None
+ manager.load_state.return_value = saved
+ return manager
+
+
+class TestRepositoriesPagination:
+ @parameterized.expand(
+ [
+ # (name, saved_cursor, page specs (has_next, end_cursor), expected checkpoint cursors, first request cursor)
+ ("fresh_multi_page", None, [(True, "c1"), (True, "c2"), (False, None)], ["c1", "c2"], None),
+ ("fresh_single_page", None, [(False, None)], [], None),
+ ("resume_then_more_pages", "saved-c", [(True, "c1"), (False, None)], ["c1"], "saved-c"),
+ ]
+ )
+ def test_pagination_and_checkpoints(
+ self,
+ _name: str,
+ saved_cursor: str | None,
+ page_specs: list[tuple[bool, str | None]],
+ expected_checkpoints: list[str],
+ first_request_cursor: str | None,
+ ) -> None:
+ session = MagicMock()
+ responses = [
+ _connection_response("account", "repositories", [{"id": f"repo-{i}", "name": f"repo-{i}"}], has_next, end)
+ for i, (has_next, end) in enumerate(page_specs)
+ ]
+ snapshots = _capture_post_calls(session, responses)
+
+ saved = DeepsourceResumeConfig(cursor=saved_cursor) if saved_cursor else None
+ manager = _make_manager(saved)
+
+ pages = list(_repositories_rows(session, "acme", "GITHUB", MagicMock(), manager))
+
+ assert [row["id"] for page in pages for row in page] == [f"repo-{i}" for i in range(len(page_specs))]
+ assert snapshots[0]["cursor"] == first_request_cursor
+ assert manager.save_state.call_args_list == [
+ ((DeepsourceResumeConfig(cursor=c),),) for c in expected_checkpoints
+ ]
+
+ def test_raises_when_has_next_page_but_cursor_missing(self) -> None:
+ session = MagicMock()
+ session.post.side_effect = [_connection_response("account", "repositories", [{"id": "a"}], True, None)]
+
+ with pytest.raises(Exception, match="endCursor is empty"):
+ 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")]
+
+ with pytest.raises(Exception, match="DeepSource account not found"):
+ list(_repositories_rows(session, "acme", "GITHUB", MagicMock(), _make_manager()))
+
+
+class TestFanOut:
+ def test_fan_out_skips_completed_and_unactivated_and_resumes_cursor(self) -> None:
+ session = MagicMock()
+ responses = [
+ # Repository enumeration: alpha already completed, beta not activated, gamma resumes.
+ _repo_names_response([("alpha", True), ("beta", False), ("gamma", True)]),
+ _connection_response(
+ "repository",
+ "analysisRuns",
+ [{"id": "run-1", "createdAt": "2026-01-01T00:00:00Z"}],
+ False,
+ None,
+ parent_extra={"id": "RID-gamma", "name": "gamma"},
+ ),
+ ]
+ snapshots = _capture_post_calls(session, responses)
+
+ saved = DeepsourceResumeConfig(
+ completed_repositories=["alpha"], current_repository="gamma", cursor="saved-inner"
+ )
+ manager = _make_manager(saved)
+
+ pages = list(_fan_out_connection_rows(session, "acme", "GITHUB", "analysis_runs", MagicMock(), manager))
+
+ # Only gamma is walked, resuming from the saved inner cursor.
+ assert session.post.call_count == 2
+ assert snapshots[1]["name"] == "gamma"
+ assert snapshots[1]["cursor"] == "saved-inner"
+ # Rows carry the repository context needed downstream.
+ assert pages == [
+ [
+ {
+ "id": "run-1",
+ "createdAt": "2026-01-01T00:00:00Z",
+ "repositoryId": "RID-gamma",
+ "repositoryName": "gamma",
+ }
+ ]
+ ]
+ # Finishing gamma checkpoints it as completed with the cursor cleared.
+ manager.save_state.assert_called_once_with(
+ DeepsourceResumeConfig(completed_repositories=["alpha", "gamma"], current_repository=None, cursor=None)
+ )
+
+ def test_fan_out_checkpoints_mid_repository(self) -> None:
+ session = MagicMock()
+ responses = [
+ _repo_names_response([("alpha", True)]),
+ _connection_response(
+ "repository", "issues", [{"id": "i-1"}], True, "inner-c1", parent_extra={"id": "RID", "name": "alpha"}
+ ),
+ _connection_response(
+ "repository", "issues", [{"id": "i-2"}], False, None, parent_extra={"id": "RID", "name": "alpha"}
+ ),
+ ]
+ _capture_post_calls(session, responses)
+
+ manager = _make_manager()
+ list(_fan_out_connection_rows(session, "acme", "GITHUB", "issues", MagicMock(), manager))
+
+ assert manager.save_state.call_args_list == [
+ ((DeepsourceResumeConfig(completed_repositories=[], current_repository="alpha", cursor="inner-c1"),),),
+ ((DeepsourceResumeConfig(completed_repositories=["alpha"], current_repository=None, cursor=None),),),
+ ]
+
+ def test_fan_out_skips_repository_deleted_mid_sync(self) -> None:
+ session = MagicMock()
+ responses = [
+ _repo_names_response([("gone", True), ("alive", True)]),
+ _null_parent_response("repository"),
+ _connection_response(
+ "repository",
+ "issueOccurrences",
+ [{"id": "occ-1"}],
+ False,
+ None,
+ parent_extra={"id": "RID", "name": "alive"},
+ ),
+ ]
+ _capture_post_calls(session, responses)
+
+ manager = _make_manager()
+ pages = list(_fan_out_connection_rows(session, "acme", "GITHUB", "issue_occurrences", MagicMock(), manager))
+
+ assert [row["id"] for page in pages for row in page] == ["occ-1"]
+ assert manager.save_state.call_args_list[-1] == (
+ (DeepsourceResumeConfig(completed_repositories=["alive", "gone"], current_repository=None, cursor=None),),
+ )
+
+
+class TestPerRepositoryObjects:
+ def test_metrics_rows_flattened_per_item(self) -> None:
+ metrics_response = MagicMock()
+ metrics_response.status_code = 200
+ metrics_response.ok = True
+ metrics_response.json.return_value = {
+ "data": {
+ "repository": {
+ "id": "RID",
+ "name": "alpha",
+ "metrics": [
+ {
+ "name": "Line Coverage",
+ "shortcode": "LCV",
+ "description": "desc",
+ "positiveDirection": "UPWARD",
+ "unit": "%",
+ "isReported": True,
+ "isThresholdEnforced": False,
+ "items": [
+ {
+ "id": "item-1",
+ "key": "AGGREGATE",
+ "threshold": 80,
+ "latestValue": 91.5,
+ "latestValueDisplay": "91.5%",
+ "thresholdStatus": "PASSING",
+ },
+ {
+ "id": "item-2",
+ "key": "PYTHON",
+ "threshold": None,
+ "latestValue": 88.0,
+ "latestValueDisplay": "88%",
+ "thresholdStatus": None,
+ },
+ ],
+ }
+ ],
+ }
+ }
+ }
+ session = MagicMock()
+ _capture_post_calls(session, [_repo_names_response([("alpha", True)]), metrics_response])
+
+ manager = _make_manager()
+ pages = list(_per_repository_object_rows(session, "acme", "GITHUB", "metrics", MagicMock(), manager))
+
+ rows = [row for page in pages for row in page]
+ assert [row["id"] for row in rows] == ["item-1", "item-2"]
+ assert all(row["metricShortcode"] == "LCV" for row in rows)
+ assert all(row["repositoryId"] == "RID" and row["repositoryName"] == "alpha" for row in rows)
+ manager.save_state.assert_called_once_with(
+ DeepsourceResumeConfig(completed_repositories=["alpha"], current_repository=None, cursor=None)
+ )
+
+ def test_report_rows_one_per_report_key(self) -> None:
+ repository = {
+ "id": "RID",
+ "name": "alpha",
+ "reports": {
+ "owaspTop10": {"key": "OWASP_TOP_10", "title": "OWASP Top 10", "currentValue": 3, "status": "FAILING"},
+ "codeHealthTrend": {"key": "CODE_HEALTH_TREND", "title": "Code health trend", "currentValue": 12},
+ },
+ }
+
+ rows = _report_rows(repository)
+
+ assert rows == [
+ {
+ "key": "OWASP_TOP_10",
+ "title": "OWASP Top 10",
+ "currentValue": 3,
+ "status": "FAILING",
+ "repositoryId": "RID",
+ "repositoryName": "alpha",
+ },
+ {
+ "key": "CODE_HEALTH_TREND",
+ "title": "Code health trend",
+ "currentValue": 12,
+ "status": None,
+ "repositoryId": "RID",
+ "repositoryName": "alpha",
+ },
+ ]
+
+ def test_metric_rows_empty_when_repository_has_no_metrics(self) -> None:
+ assert _metric_rows({"id": "RID", "name": "alpha", "metrics": None}) == []
+
+
+class TestRetriesAndErrors:
+ @patch("time.sleep", return_value=None)
+ def test_429_is_retried_then_succeeds(self, _mock_sleep: MagicMock) -> None:
+ rate_limited = _error_response(429, "Too Many Requests")
+ rate_limited.headers = {"Retry-After": "0"}
+ session = MagicMock()
+ session.post.side_effect = [
+ rate_limited,
+ _connection_response("account", "repositories", [{"id": "a"}], False, None),
+ ]
+
+ pages = list(_repositories_rows(session, "acme", "GITHUB", MagicMock(), _make_manager()))
+
+ assert pages == [[{"id": "a"}]]
+ assert session.post.call_count == 2
+
+ @patch("time.sleep", return_value=None)
+ def test_persistent_429_raises_retryable_error(self, _mock_sleep: MagicMock) -> None:
+ rate_limited = _error_response(429, "Too Many Requests")
+ rate_limited.headers = {"Retry-After": "0"}
+ session = MagicMock()
+ session.post.side_effect = [rate_limited for _ in range(DEEPSOURCE_MAX_RETRY_ATTEMPTS)]
+
+ with pytest.raises(DeepsourceRetryableError):
+ list(_repositories_rows(session, "acme", "GITHUB", MagicMock(), _make_manager()))
+
+ assert session.post.call_count == DEEPSOURCE_MAX_RETRY_ATTEMPTS
+
+ @parameterized.expand(
+ [
+ ("unauthorized", 401, "Unauthorized", {"message": "Authentication required"}),
+ ("forbidden", 403, "Forbidden", None),
+ ]
+ )
+ def test_auth_errors_raise_messages_matched_by_non_retryable_errors(
+ self,
+ _name: str,
+ status_code: int,
+ reason: str,
+ body: dict[str, Any] | None,
+ ) -> None:
+ session = MagicMock()
+ session.post.side_effect = [_error_response(status_code, reason, body)]
+
+ with pytest.raises(Exception) as exc_info:
+ list(_repositories_rows(session, "acme", "GITHUB", MagicMock(), _make_manager()))
+
+ # The raised message must stay matchable by the source's non-retryable error keys,
+ # otherwise bad credentials retry forever.
+ non_retryable = DeepsourceSource().get_non_retryable_errors()
+ assert any(key in str(exc_info.value) for key in non_retryable)
+
+ def test_graphql_errors_raise(self) -> None:
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ response.json.return_value = {"errors": [{"message": "Something went wrong"}]}
+ session = MagicMock()
+ session.post.side_effect = [response]
+
+ with pytest.raises(Exception, match="DeepSource GraphQL error: Something went wrong"):
+ list(_repositories_rows(session, "acme", "GITHUB", MagicMock(), _make_manager()))
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("valid", 200, {"data": {"viewer": {"email": "[email protected]"}, "account": {"id": "AID"}}}, True, None),
+ (
+ "token_ok_account_missing",
+ 200,
+ {"data": {"viewer": {"email": "[email protected]"}, "account": None}},
+ False,
+ "DeepSource account not found",
+ ),
+ (
+ "bad_token",
+ 401,
+ {"message": "Authentication required"},
+ False,
+ "Invalid DeepSource personal access token",
+ ),
+ (
+ "graphql_error_no_viewer",
+ 200,
+ {"data": {"viewer": None, "account": None}, "errors": [{"message": "boom"}]},
+ False,
+ "DeepSource API error",
+ ),
+ ]
+ )
+ @patch(_SESSION_PATCH)
+ def test_validation_outcomes(
+ self,
+ _name: str,
+ status_code: int,
+ body: dict[str, Any],
+ expected_valid: bool,
+ expected_error_fragment: str | None,
+ mock_session_cls: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body
+ session = MagicMock()
+ session.post.return_value = response
+ mock_session_cls.return_value = session
+
+ valid, error = validate_credentials("token", "acme", "GITHUB")
+
+ assert valid is expected_valid
+ if expected_error_fragment is None:
+ assert error is None
+ else:
+ assert error is not None and expected_error_fragment in error
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/tests/test_deepsource_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/tests/test_deepsource_source.py
new file mode 100644
index 000000000000..ee54603dfc9b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deepsource/tests/test_deepsource_source.py
@@ -0,0 +1,130 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.deepsource import (
+ DeepsourceResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.settings import (
+ DEEPSOURCE_ENDPOINTS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.source import DeepsourceSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DeepsourceSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_CONFIG = DeepsourceSourceConfig(api_token="tok", account_login="acme", vcs_provider="GITHUB")
+
+
+def _source_inputs(schema_name: str) -> MagicMock:
+ inputs = MagicMock()
+ inputs.schema_name = schema_name
+ return inputs
+
+
+class TestDeepsourceSource:
+ def test_source_type(self) -> None:
+ assert DeepsourceSource().source_type == ExternalDataSourceType.DEEPSOURCE
+
+ def test_connection_host_fields_force_secret_reentry_on_account_change(self) -> None:
+ # Changing account_login/vcs_provider retargets the stored PAT at another account, so
+ # both must be host fields — the update serializer then demands the PAT be re-entered.
+ assert DeepsourceSource().connection_host_fields == ["account_login", "vcs_provider"]
+
+ def test_source_is_released_and_categorized(self) -> None:
+ config = DeepsourceSource().get_source_config
+ assert not config.unreleasedSource
+ assert config.releaseStatus is not None
+ assert config.category is not None
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/deepsource"
+
+ def test_get_schemas_lists_every_endpoint_as_full_refresh(self) -> None:
+ schemas = DeepsourceSource().get_schemas(_CONFIG, team_id=1)
+
+ assert [s.name for s in schemas] == list(ENDPOINTS)
+ # The API has no server-side timestamp filters, so nothing may advertise incremental.
+ assert all(not s.supports_incremental and not s.supports_append for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = DeepsourceSource().get_schemas(_CONFIG, team_id=1, names=["repositories", "reports"])
+ assert {s.name for s in schemas} == {"repositories", "reports"}
+
+ def test_get_documented_tables_renders_static_catalog(self) -> None:
+ source = DeepsourceSource()
+ assert source.lists_tables_without_credentials
+
+ tables = source.get_documented_tables()
+
+ assert [t["name"] for t in tables] == list(ENDPOINTS)
+ # Canonical descriptions must cover every endpoint so the public docs aren't thin.
+ assert all(t["description"] for t in tables)
+
+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])
+ def test_source_for_pipeline_wires_endpoint_config(self, endpoint: str) -> None:
+ response = DeepsourceSource().source_for_pipeline(_CONFIG, MagicMock(), _source_inputs(endpoint))
+
+ assert response.name == endpoint
+ assert response.primary_keys == DEEPSOURCE_ENDPOINTS[endpoint].primary_keys
+ assert callable(response.items)
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = DeepsourceSource().get_resumable_source_manager(_source_inputs("repositories"))
+ assert manager._data_class is DeepsourceResumeConfig
+
+ @parameterized.expand(
+ [
+ ("valid", (True, None), True, None),
+ ("invalid", (False, "Invalid DeepSource personal access token"), False, "Invalid DeepSource"),
+ ]
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.deepsource.source.validate_deepsource_credentials"
+ )
+ def test_validate_credentials_delegates_to_transport(
+ self,
+ _name: str,
+ transport_result: tuple[bool, str | None],
+ expected_valid: bool,
+ expected_fragment: str | None,
+ mock_validate: MagicMock,
+ ) -> None:
+ mock_validate.return_value = transport_result
+
+ valid, error = DeepsourceSource().validate_credentials(_CONFIG, team_id=1)
+
+ mock_validate.assert_called_once_with("tok", "acme", "GITHUB")
+ assert valid is expected_valid
+ if expected_fragment is None:
+ assert error is None
+ else:
+ assert error is not None and expected_fragment in error
+
+
+class TestDeepsourceNonRetryableErrors:
+ @parameterized.expand(
+ [
+ (
+ "auth_401",
+ "401 Client Error: Unauthorized for url: https://api.deepsource.com/graphql/ (DeepSource API: Authentication required)",
+ ),
+ ("forbidden_403", "403 Client Error: Forbidden for url: https://api.deepsource.com/graphql/"),
+ ("account_missing", "DeepSource account not found: 'acme' (GITHUB). Check the account login..."),
+ ]
+ )
+ def test_non_retryable_errors_match(self, _name: str, observed_error: str) -> None:
+ non_retryable_errors = DeepsourceSource().get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @parameterized.expand(
+ [
+ ("transient_500", "DeepSource: server error 502"),
+ ("rate_limited", "DeepSource: rate limited (429)"),
+ ("graphql_error", "DeepSource GraphQL error: Something failed"),
+ ("network", "DeepSource: transient network error - Read timed out. (read timeout=60)"),
+ ]
+ )
+ def test_non_retryable_errors_do_not_match_transient(self, _name: str, observed_error: str) -> None:
+ non_retryable_errors = DeepsourceSource().get_non_retryable_errors()
+ # Transient/server errors must stay retryable so the pipeline backs off and retries.
+ assert not any(key in observed_error for key in non_retryable_errors)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 0ca7acbe1223..8738a2c6887f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -1163,7 +1163,11 @@ class DeepgramSourceConfig(config.Config):
@config.config
class DeepsourceSourceConfig(config.Config):
- pass
+ api_token: str
+ account_login: str
+ vcs_provider: Literal[
+ "GITHUB", "GITLAB", "BITBUCKET", "GITHUB_ENTERPRISE", "BITBUCKET_DATACENTER", "ADS", "GSR"
+ ] = config.value(default="GITHUB")
@config.config