: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement codecov import source (#71209)
Tom Owers38be4aa69e7c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 9ed851bdb0e4..d2623a3f5888 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -116,6 +116,7 @@ the row lists both.| coassemble | HTTP | requests | ✅ || coda | HTTP | requests | ✅ || codacy | HTTP | requests | ✅ |+| codecov | HTTP | requests | ✅ || codefresh | HTTP | requests | ✅ || cody | HTTP (CSV reports) | requests | ✅ || cohere | HTTP | requests | ✅ |@@ -615,6 +616,7 @@ doesn't conflict with concurrent PRs.- cloudbeds- coassemble- cockroachdb+- codacy- codecov- confluent_cloud- constant_contactdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/canonical_descriptions.pynew file mode 100644index 000000000000..f1defff4fe68--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/canonical_descriptions.py@@ -0,0 +1,92 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "repos": {+ "description": "A repository Codecov tracks for the configured owner, with its latest coverage totals.",+ "docs_url": "https://docs.codecov.com/reference/repos_list",+ "columns": {+ "name": "Repository name, unique within the owner.",+ "private": "Whether the repository is private on the git provider.",+ "updatestamp": "When Codecov last updated its state for this repository.",+ "author": "Owner of the repository (service, username, name).",+ "language": "Primary programming language of the repository.",+ "branch": "Default branch used for coverage reporting.",+ "active": "Whether the repository has received a coverage upload.",+ "activated": "Whether the repository has been manually activated in Codecov.",+ "totals": "Latest coverage totals for the default branch (files, lines, hits, misses, partials, coverage percentage).",+ },+ },+ "branches": {+ "description": "A branch of a repository that has coverage data in Codecov.",+ "docs_url": "https://docs.codecov.com/reference/repos_branches_list",+ "columns": {+ "repo": "Repository the branch belongs to (injected by the import).",+ "name": "Branch name, unique within the repository.",+ "updatestamp": "When coverage data for the branch was last updated.",+ },+ },+ "commits": {+ "description": "A commit with a coverage upload on the repository's default branch.",+ "docs_url": "https://docs.codecov.com/reference/repos_commits_list",+ "columns": {+ "repo": "Repository the commit belongs to (injected by the import).",+ "commitid": "Full git commit SHA.",+ "message": "Commit message.",+ "timestamp": "Commit timestamp.",+ "ci_passed": "Whether CI passed for this commit, if known.",+ "author": "Commit author (service, username, name).",+ "branch": "Branch the coverage upload was reported against.",+ "totals": "Coverage totals for the commit (files, lines, hits, misses, partials, coverage percentage).",+ "state": "Codecov processing state of the commit report (e.g. complete).",+ "parent": "SHA of the parent commit.",+ },+ },+ "pulls": {+ "description": "A pull request Codecov tracks for a repository, with base/head coverage totals.",+ "docs_url": "https://docs.codecov.com/reference/repos_pulls_list",+ "columns": {+ "repo": "Repository the pull request belongs to (injected by the import).",+ "pullid": "Pull request number on the git provider.",+ "title": "Pull request title.",+ "base_totals": "Coverage totals of the base commit.",+ "head_totals": "Coverage totals of the head commit.",+ "updatestamp": "When Codecov last updated its state for this pull request.",+ "state": "Pull request state (open, merged, closed).",+ "ci_passed": "Whether CI passed on the head commit, if known.",+ "author": "Pull request author (service, username, name).",+ "patch": "Patch coverage totals for the lines changed by the pull request.",+ },+ },+ "flags": {+ "description": "Current coverage per flag (a user-defined grouping of coverage uploads) in a repository.",+ "docs_url": "https://docs.codecov.com/reference/repos_flags_list",+ "columns": {+ "repo": "Repository the flag belongs to (injected by the import).",+ "flag_name": "Flag name, unique within the repository.",+ "coverage": "Latest coverage percentage for the flag.",+ },+ },+ "components": {+ "description": "Current coverage per component (a path/flag-based slice of a repository defined in codecov.yml).",+ "docs_url": "https://docs.codecov.com/reference/repos_components_list",+ "columns": {+ "repo": "Repository the component belongs to (injected by the import).",+ "component_id": "Component identifier from the repository's Codecov configuration.",+ "name": "Display name of the component.",+ "coverage": "Latest coverage percentage for the component.",+ },+ },+ "coverage_trend": {+ "description": "Daily coverage time series for a repository's default branch.",+ "docs_url": "https://docs.codecov.com/reference/repos_coverage_list",+ "columns": {+ "repo": "Repository the measurement belongs to (injected by the import).",+ "timestamp": "Start of the measured interval (one day).",+ "min": "Minimum coverage percentage observed in the interval.",+ "max": "Maximum coverage percentage observed in the interval.",+ "avg": "Average coverage percentage observed in the interval.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/codecov.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/codecov.pynew file mode 100644index 000000000000..00edbf270ce7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/codecov.py@@ -0,0 +1,365 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import quote, urlencode++import requests+from dateutil import parser as dateutil_parser+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.codecov.settings import (+ CODECOV_ENDPOINTS,+ CodecovEndpointConfig,+)+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++CODECOV_BASE_URL = "https://api.codecov.io/api/v2"+PAGE_SIZE = 500 # Codecov caps page_size at 500+++class CodecovRetryableError(Exception):+ pass+++class CodecovResumeConfig:+ # Next page URL to fetch. None means "start the bookmarked repo's endpoint at its first+ # page" — used when the bookmark advances to a repo whose first page URL isn't built yet.+ next_url: str | None = None+ # The repository currently being processed during fan-out. A stable name bookmark (not a+ # positional index) so repos added/removed between a crash and the retry can't resume us+ # into the wrong repo. None for the top-level repos endpoint.+ repo: str | None = None+++def _get_headers(api_token: str) -> dict[str, str]:+ # Codecov's documented scheme is the lowercase "bearer" keyword.+ return {"Authorization": f"bearer {api_token}", "Accept": "application/json"}+++def _owner_base_url(service: str, owner_username: str) -> str:+ # Both segments are user-supplied; percent-encode them (including "/") so they can't+ # retarget the request path.+ return f"{CODECOV_BASE_URL}/{quote(service, safe='')}/{quote(owner_username, safe='')}"+++def _endpoint_url(owner_base_url: str, config: CodecovEndpointConfig, repo: str | None, params: dict[str, Any]) -> str:+ path = config.path.format(repo=quote(repo, safe="")) if repo is not None else config.path+ url = f"{owner_base_url}{path}"+ return f"{url}?{urlencode(params)}" if params else url+++def _ensure_codecov_url(url: str) -> str:+ """Upgrade and pin a pagination/resume URL to the Codecov API origin.++ Codecov's DRF `next` links come back with an http:// scheme, so upgrade them rather than+ send the bearer token in plaintext. Beyond that, `next` is response-controlled and resume+ URLs are replayed from persisted state, so refuse any URL outside the API origin — the+ token must never be sent to a host we didn't choose.+ """+ if url.startswith("http://"):+ url = "https://" + url.removeprefix("http://")+ if not url.startswith(f"{CODECOV_BASE_URL}/"):+ raise ValueError(f"Refusing to follow non-Codecov URL: {url}")+ return url+++def _as_utc(dt: datetime) -> datetime:+ return dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+++def _normalize_cutoff(value: Any) -> datetime | None:+ if isinstance(value, datetime):+ return _as_utc(value)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ return None+++def _is_older_than_cutoff(value: Any, cutoff: datetime) -> bool:+ if value is None:+ return False+ if isinstance(value, str):+ try:+ parsed = dateutil_parser.parse(value)+ except (ValueError, TypeError):+ return False+ elif isinstance(value, datetime):+ parsed = value+ else:+ return False+ return _as_utc(parsed) <= cutoff+++def _should_stop_desc(items: list[dict[str, Any]], cutoff_field: str | None, cutoff: datetime | None) -> bool:+ """Newest-first + incremental can stop the moment a page holds a pre-watermark record."""+ if not cutoff_field or cutoff is None or not items:+ return False+ return any(_is_older_than_cutoff(item.get(cutoff_field), cutoff) for item in items if item)+++def _format_start_date(cutoff: datetime) -> str:+ # Codecov's coverage report takes calendar dates; the boundary interval is re-returned+ # and deduped by the primary-key merge.+ return cutoff.date().isoformat()+++def parse_repositories(repositories: str | None) -> list[str]:+ """Split the optional comma-separated repository allow-list into clean names."""+ if not repositories:+ return []+ return [name.strip() for name in repositories.split(",") if name.strip()]+++@retry(+ retry=retry_if_exception_type(+ (+ CodecovRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:+ response = session.get(url, headers=headers, timeout=60)++ if response.status_code == 429 or response.status_code >= 500:+ raise CodecovRetryableError(f"Codecov API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # 404 is expected and handled during fan-out (a repo deleted mid-sync).+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"Codecov API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _iter_pages(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Yield (results, next_url) per page of a DRF-paginated Codecov list, following `next`."""+ while True:+ data = _fetch_page(session, url, headers, logger)+ results = data.get("results") or []+ next_url = data.get("next")+ next_url = _ensure_codecov_url(next_url) if next_url else None+ yield results, next_url+ if not next_url:+ return+ url = next_url+++def _iter_repo_names(+ session: requests.Session, owner_base_url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> Iterator[str]:+ """Page through the owner's active repos and yield each name. Inactive repos (never+ received an upload) have no coverage data, so fanning out over them is wasted API cost."""+ url = f"{owner_base_url}/repos?{urlencode({'active': 'true', 'page_size': PAGE_SIZE})}"+ for results, _next_url in _iter_pages(session, url, headers, logger):+ for item in results:+ yield item["name"]+++def _get_top_level_rows(+ session: requests.Session,+ owner_base_url: str,+ headers: dict[str, str],+ config: CodecovEndpointConfig,+ repositories: list[str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CodecovResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ url = _ensure_codecov_url(resume.next_url)+ logger.debug(f"Codecov: resuming {config.name} from URL: {url}")+ else:+ url = _endpoint_url(owner_base_url, config, None, {"page_size": PAGE_SIZE, **config.extra_params})++ allowed = set(repositories)+ for results, next_url in _iter_pages(session, url, headers, logger):+ # The repos list has no server-side name filter, so the allow-list applies client-side.+ rows = [item for item in results if not allowed or item.get("name") in allowed]+ if rows:+ yield rows+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —+ # merge dedupes on the primary key.+ if next_url:+ resumable_source_manager.save_state(CodecovResumeConfig(next_url=next_url))+++def _get_fan_out_rows(+ session: requests.Session,+ owner_base_url: str,+ headers: dict[str, str],+ config: CodecovEndpointConfig,+ repositories: list[str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CodecovResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> Iterator[list[dict[str, Any]]]:+ """Fan out one paginated walk per repository, injecting the repo name onto every row (it+ feeds each endpoint's composite primary key)."""+ repo_names = repositories or list(_iter_repo_names(session, owner_base_url, headers, logger))++ cutoff = _normalize_cutoff(db_incremental_field_last_value) if should_use_incremental_field else None+ params: dict[str, Any] = {**config.extra_params}+ if config.paginated:+ params = {"page_size": PAGE_SIZE, **config.extra_params}+ stop_field: str | None = None+ if cutoff is not None and config.incremental_fields:+ if config.incremental_server_param:+ params[config.incremental_server_param] = _format_start_date(cutoff)+ else:+ stop_field = incremental_field or config.default_incremental_field++ # Resolve the saved repo bookmark to the slice of repos still to process. If the+ # bookmarked repo no longer exists (deleted between runs), start over from the first —+ # merge dedupes the re-pulled rows on the primary key. `resume_url` is consumed by the+ # first repo only.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = repo_names+ resume_url: str | None = None+ if resume is not None and resume.repo is not None and resume.repo in repo_names:+ remaining = repo_names[repo_names.index(resume.repo) :]+ resume_url = _ensure_codecov_url(resume.next_url) if resume.next_url else None+ logger.debug(f"Codecov: resuming {config.name} from repo={resume.repo}, url={resume_url}")++ for index, repo in enumerate(remaining):+ url = resume_url or _endpoint_url(owner_base_url, config, repo, params)+ resume_url = None # only the resumed-into repo uses the saved URL; the rest start fresh++ try:+ if not config.paginated:+ # components returns a bare JSON array with no pagination envelope.+ items = _fetch_page(session, url, headers, logger)+ rows = [{**item, "repo": repo} for item in items or []]+ if rows:+ yield rows+ else:+ for results, next_url in _iter_pages(session, url, headers, logger):+ stop_after_this_page = _should_stop_desc(results, stop_field, cutoff)+ rows = [{**item, "repo": repo} for item in results]+ if rows:+ yield rows+ # Save AFTER yielding (and only when more pages remain) so a crash+ # re-yields the last page rather than skipping it.+ if next_url and not stop_after_this_page:+ resumable_source_manager.save_state(CodecovResumeConfig(next_url=next_url, repo=repo))+ if stop_after_this_page:+ break+ except requests.HTTPError as exc:+ # A repo deleted (or deactivated) between enumeration and this fetch 404s. Skip it+ # rather than failing the whole sync. Any other HTTP error is re-raised.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Codecov: repo {repo} not found while fetching {config.name}, skipping")+ else:+ raise++ # Advance the bookmark to the next repo so a crash between repos resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(CodecovResumeConfig(next_url=None, repo=remaining[index + 1]))+++def get_rows(+ api_token: str,+ service: str,+ owner_username: str,+ repositories: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CodecovResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = CODECOV_ENDPOINTS[endpoint]+ headers = _get_headers(api_token)+ owner_base_url = _owner_base_url(service, owner_username)+ repo_filter = parse_repositories(repositories)+ # One session reused across every page (and repo) so urllib3 keeps the connection alive.+ session = make_tracked_session()++ if config.fan_out_over_repos:+ yield from _get_fan_out_rows(+ session,+ owner_base_url,+ headers,+ config,+ repo_filter,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ incremental_field,+ )+ else:+ yield from _get_top_level_rows(+ session, owner_base_url, headers, config, repo_filter, logger, resumable_source_manager+ )+++def codecov_source(+ api_token: str,+ service: str,+ owner_username: str,+ repositories: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CodecovResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = CODECOV_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ service=service,+ owner_username=owner_username,+ repositories=repositories,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Incremental endpoints fan out over repos, so rows are not globally ordered on the+ # cursor (commits are newest-first per repo; the coverage trend restarts per repo).+ # Desc mode persists the watermark only at successful job end, which is the safe+ # behavior for a partial fan-out run.+ sort_mode="desc" if endpoint_config.incremental_fields else "asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )+++def validate_credentials(api_token: str, service: str, owner_username: str) -> tuple[bool, int | None]:+ """Probe the owner's repos list to confirm the token/owner pair is genuine.++ Returns ``(ok, status_code)``; ``status_code`` is ``None`` on a transport error.+ """+ url = f"{_owner_base_url(service, owner_username)}/repos?{urlencode({'page_size': 1})}"+ try:+ response = make_tracked_session().get(url, headers=_get_headers(api_token), timeout=10)+ except Exception:+ return False, None+ return response.status_code == 200, response.status_codediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/settings.pynew file mode 100644index 000000000000..0d54674e36b3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/settings.py@@ -0,0 +1,102 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class CodecovEndpointConfig:+ name: str+ path: str # Path template relative to /{service}/{owner_username}; "{repo}" is filled per repository during fan-out+ incremental_fields: list[IncrementalField]+ primary_keys: list[str]+ default_incremental_field: Optional[str] = None+ # Query param for Codecov's server-side time filter (e.g. `start_date` on the coverage+ # report). None means no server-side filter: incremental endpoints without one scroll+ # newest-first and stop client-side at the watermark instead.+ incremental_server_param: Optional[str] = None+ partition_key: Optional[str] = None # Stable datetime field (never one that mutates)+ fan_out_over_repos: bool = False+ # Most endpoints are DRF-paginated ({count, next, previous, results}); components+ # returns a bare, unpaginated JSON array.+ paginated: bool = True+ extra_params: dict[str, str] = field(default_factory=dict)+++_TIMESTAMP_INCREMENTAL_FIELD: IncrementalField = {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+}+++CODECOV_ENDPOINTS: dict[str, CodecovEndpointConfig] = {+ "repos": CodecovEndpointConfig(+ name="repos",+ path="/repos",+ # No server-side time filter and `updatestamp` mutates, so full refresh only.+ incremental_fields=[],+ primary_keys=["name"],+ ),+ "branches": CodecovEndpointConfig(+ name="branches",+ path="/repos/{repo}/branches",+ incremental_fields=[], # Only name + a mutating updatestamp; full refresh only.+ primary_keys=["repo", "name"],+ fan_out_over_repos=True,+ ),+ "commits": CodecovEndpointConfig(+ name="commits",+ path="/repos/{repo}/commits",+ # The list is returned newest-first with no server-side time filter, so incremental+ # sync scrolls descending and stops once a page predates the watermark.+ incremental_fields=[_TIMESTAMP_INCREMENTAL_FIELD],+ default_incremental_field="timestamp",+ primary_keys=["repo", "commitid"],+ partition_key="timestamp", # Commit timestamps are immutable.+ fan_out_over_repos=True,+ ),+ "pulls": CodecovEndpointConfig(+ name="pulls",+ path="/repos/{repo}/pulls",+ # `updatestamp` is null on pulls without coverage data and the default order is by+ # pullid, so there is no reliable cursor; state also mutates (open -> merged).+ incremental_fields=[],+ primary_keys=["repo", "pullid"],+ fan_out_over_repos=True,+ ),+ "flags": CodecovEndpointConfig(+ name="flags",+ path="/repos/{repo}/flags",+ incremental_fields=[], # Point-in-time coverage per flag; no timestamps at all.+ primary_keys=["repo", "flag_name"],+ fan_out_over_repos=True,+ ),+ "components": CodecovEndpointConfig(+ name="components",+ path="/repos/{repo}/components",+ incremental_fields=[], # Point-in-time coverage per component; no timestamps at all.+ primary_keys=["repo", "component_id"],+ fan_out_over_repos=True,+ paginated=False,+ ),+ "coverage_trend": CodecovEndpointConfig(+ name="coverage_trend",+ path="/repos/{repo}/coverage",+ # Genuine server-side filter: `start_date` bounds the time series (verified: a+ # future cutoff drops all but the carried-forward latest point).+ incremental_fields=[_TIMESTAMP_INCREMENTAL_FIELD],+ default_incremental_field="timestamp",+ incremental_server_param="start_date",+ primary_keys=["repo", "timestamp"],+ fan_out_over_repos=True,+ extra_params={"interval": "1d"},+ ),+}++ENDPOINTS = tuple(CODECOV_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CODECOV_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/source.pyindex 706cfff03730..f51d7a86434d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/source.py@@ -1,30 +1,200 @@-from typing import cast+from typing import Optional, castfrom 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.codecov.codecov import (+ CodecovResumeConfig,+ codecov_source,+ validate_credentials as validate_codecov_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.codecov.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CodecovSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType+_ENDPOINT_DESCRIPTIONS: dict[str, str] = {+ "repos": "All repositories Codecov knows for the owner, with their latest coverage totals",+ "commits": "Commits with coverage uploads on each repository's default branch, newest-first",+ "coverage_trend": "Daily min/max/avg coverage time series per repository (default branch)",+ "flags": "Current coverage percentage per flag, per repository",+ "components": "Current coverage percentage per component, per repository",+}+@SourceRegistry.register-class CodecovSource(SimpleSource[CodecovSourceConfig]):+class CodecovSource(ResumableSource[CodecovSourceConfig, CodecovResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CODECOV+ @property+ def connection_host_fields(self) -> list[str]:+ # The stored token is sent to api.codecov.io scoped by git provider + owner and filtered+ # by the repository allow-list, so retargeting any of these must force re-entry of the+ # token — otherwise an editor without it could point it at another owner/repo the token+ # can read and sync that private data into the warehouse.+ return ["service", "owner_username", "repositories"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CODECOV,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Codecov (Sentry)",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Codecov API token to automatically pull your code coverage data into the PostHog Data warehouse.++You can generate a personal API token under **Settings → Access** in your [Codecov account](https://app.codecov.io/). The token mirrors your own permissions on the git provider, so it can read every repository you can.++By default all of the owner's active repositories are synced; enter a comma-separated list of repository names to limit the import.+""",iconPath="/static/services/codecov.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/codecov",+ keywords=["coverage", "code coverage", "sentry"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldSelectConfig(+ name="service",+ label="Git 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="GitLab Enterprise", value="gitlab_enterprise"),+ SourceFieldSelectConfigOption(label="Bitbucket Server", value="bitbucket_server"),+ ],+ ),+ SourceFieldInputConfig(+ name="owner_username",+ label="Owner username",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="my-org",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="repositories",+ label="Repositories (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="repo-one, repo-two",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.codecov.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # Match the stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.codecov.io": "Your Codecov API token is invalid or has been revoked. Generate a new token under Settings → Access in your Codecov account, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.codecov.io": "Your Codecov API token does not have access to this data. Check your permissions on the git provider, then reconnect.",+ "404 Client Error: Not Found for url: https://api.codecov.io": "Codecov could not find the configured owner. Check the git provider and owner username, then reconnect.",+ }++ def get_schemas(+ self,+ config: CodecovSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Incremental syncs re-pull boundary rows (a whole page for commits, the boundary+ # interval for the coverage trend); only merge dedupes those on the primary key, so+ # append mode stays off.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ 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: CodecovSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ is_valid, status_code = validate_codecov_credentials(config.api_token, config.service, config.owner_username)+ if is_valid:+ return True, None+ if status_code == 401:+ return False, "Invalid Codecov API token"+ if status_code == 404:+ return False, f"Owner '{config.owner_username}' not found on Codecov for the selected git provider"+ return False, "Could not connect to Codecov with the provided credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CodecovResumeConfig]:+ return ResumableSourceManager[CodecovResumeConfig](inputs, CodecovResumeConfig)++ def source_for_pipeline(+ self,+ config: CodecovSourceConfig,+ resumable_source_manager: ResumableSourceManager[CodecovResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return codecov_source(+ api_token=config.api_token,+ service=config.service,+ owner_username=config.owner_username,+ repositories=config.repositories,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/tests/test_codecov.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/tests/test_codecov.pynew file mode 100644index 000000000000..d792f468ba47--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/tests/test_codecov.py@@ -0,0 +1,389 @@+from datetime import UTC, datetime+from typing import Any++import pytest+from unittest import mock+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.codecov import codecov+from products.warehouse_sources.backend.temporal.data_imports.sources.codecov.codecov import (+ CodecovResumeConfig,+ _ensure_codecov_url,+ _owner_base_url,+ _should_stop_desc,+ get_rows,+ parse_repositories,+ validate_credentials,+)++_BASE = "https://api.codecov.io/api/v2/github/acme"+++class _FakeResumableManager:+ def __init__(self, state: CodecovResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[CodecovResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> CodecovResumeConfig | None:+ return self._state++ def save_state(self, data: CodecovResumeConfig) -> None:+ self.saved.append(data)+++def _http_error(status_code: int) -> requests.HTTPError:+ response = MagicMock()+ response.status_code = status_code+ return requests.HTTPError(response=response)+++def _patch_fetch(monkeypatch: Any, pages: dict[str, Any]) -> list[str]:+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> Any:+ fetched.append(url)+ result = pages[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(codecov, "_fetch_page", fake_fetch)+ return fetched+++def _collect(manager: _FakeResumableManager, **kwargs: Any) -> list[dict]:+ rows: list[dict] = []+ for batch in get_rows(+ api_token="token",+ service="github",+ owner_username="acme",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows+++def _page(results: list[dict], next_url: str | None = None) -> dict:+ return {"count": len(results), "next": next_url, "previous": None, "results": results}+++_ACTIVE_REPOS_URL = f"{_BASE}/repos?active=true&page_size=500"+++class TestParseRepositories:+ @parameterized.expand(+ [+ ("none", None, []),+ ("empty", "", []),+ ("single", "repo-one", ["repo-one"]),+ ("comma_separated_with_spaces", " repo-one , repo-two ", ["repo-one", "repo-two"]),+ ("trailing_commas", "repo-one,,", ["repo-one"]),+ ]+ )+ def test_parse(self, _name: str, value: str | None, expected: list[str]) -> None:+ assert parse_repositories(value) == expected+++class TestOwnerBaseUrl:+ @parameterized.expand(+ [+ ("plain", "acme", "https://api.codecov.io/api/v2/github/acme"),+ # Path metacharacters must be encoded so a crafted owner can't retarget the+ # request path the bearer token is sent to.+ ("slash", "acme/../evil", "https://api.codecov.io/api/v2/github/acme%2F..%2Fevil"),+ ("query", "acme?x=1", "https://api.codecov.io/api/v2/github/acme%3Fx%3D1"),+ ]+ )+ def test_owner_is_percent_encoded(self, _name: str, owner: str, expected: str) -> None:+ assert _owner_base_url("github", owner) == expected+++class TestEnsureCodecovUrl:+ @parameterized.expand(+ [+ ("http_upgraded", "http://api.codecov.io/api/v2/github/acme/repos?page=2"),+ ("https_unchanged", "https://api.codecov.io/api/v2/github/acme/repos?page=2"),+ ]+ )+ def test_valid_urls_normalize_to_https(self, _name: str, url: str) -> None:+ assert _ensure_codecov_url(url) == "https://api.codecov.io/api/v2/github/acme/repos?page=2"++ @parameterized.expand(+ [+ # A pagination link or poisoned resume state pointing anywhere but the Codecov API+ # origin would receive the bearer token — refuse it.+ ("foreign_host", "https://evil.example.com/api/v2/github/acme/repos"),+ ("userinfo_trick", "https://[email protected]/api/v2/repos"),+ ("host_suffix", "https://api.codecov.io.evil.example.com/api/v2/repos"),+ ("path_prefix_escape", "https://api.codecov.io/api/v2evil"),+ ]+ )+ def test_non_codecov_urls_are_refused(self, _name: str, url: str) -> None:+ with pytest.raises(ValueError):+ _ensure_codecov_url(url)+++class TestShouldStopDesc:+ _CUTOFF = datetime(2026, 7, 5, tzinfo=UTC)++ @parameterized.expand(+ [+ ("no_cutoff", [{"timestamp": "2026-07-01T00:00:00Z"}], "timestamp", None, False),+ ("all_newer", [{"timestamp": "2026-07-09T00:00:00Z"}], "timestamp", _CUTOFF, False),+ (+ "one_older",+ [{"timestamp": "2026-07-09T00:00:00Z"}, {"timestamp": "2026-07-01T00:00:00Z"}],+ "timestamp",+ _CUTOFF,+ True,+ ),+ ("missing_field", [{"other": "x"}], "timestamp", _CUTOFF, False),+ ("no_field", [{"timestamp": "2026-07-01T00:00:00Z"}], None, _CUTOFF, False),+ ]+ )+ def test_stop(self, _name: str, items: list[dict], field: str | None, cutoff: Any, expected: bool) -> None:+ assert _should_stop_desc(items, field, cutoff) is expected+++class TestTopLevelRows:+ def test_repos_paginates_and_upgrades_next_to_https(self, monkeypatch: Any) -> None:+ pages = {+ f"{_BASE}/repos?page_size=500": _page(+ [{"name": "r1"}], next_url="http://api.codecov.io/api/v2/github/acme/repos?page=2&page_size=500"+ ),+ # Codecov returns `next` links with an http:// scheme; we must follow them over https.+ "https://api.codecov.io/api/v2/github/acme/repos?page=2&page_size=500": _page([{"name": "r2"}]),+ }+ fetched = _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager()+ rows = _collect(manager, repositories=None, endpoint="repos")++ assert [r["name"] for r in rows] == ["r1", "r2"]+ assert fetched == list(pages)+ # State is saved only while more pages remain, and after the page was yielded.+ assert manager.saved == [+ CodecovResumeConfig(next_url="https://api.codecov.io/api/v2/github/acme/repos?page=2&page_size=500")+ ]++ def test_repos_resumes_from_saved_url(self, monkeypatch: Any) -> None:+ resume_url = f"{_BASE}/repos?page=2&page_size=500"+ pages = {resume_url: _page([{"name": "r2"}])}+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(+ _FakeResumableManager(CodecovResumeConfig(next_url=resume_url)), repositories=None, endpoint="repos"+ )++ assert [r["name"] for r in rows] == ["r2"]+ assert fetched == [resume_url]++ def test_poisoned_next_url_aborts_the_sync(self, monkeypatch: Any) -> None:+ pages = {+ f"{_BASE}/repos?page_size=500": _page(+ [{"name": "r1"}], next_url="https://evil.example.com/api/v2/github/acme/repos?page=2"+ ),+ }+ _patch_fetch(monkeypatch, pages)++ with pytest.raises(ValueError):+ _collect(_FakeResumableManager(), repositories=None, endpoint="repos")++ def test_repos_applies_repository_allow_list(self, monkeypatch: Any) -> None:+ pages = {f"{_BASE}/repos?page_size=500": _page([{"name": "r1"}, {"name": "r2"}, {"name": "r3"}])}+ _patch_fetch(monkeypatch, pages)+ rows = _collect(_FakeResumableManager(), repositories="r1, r3", endpoint="repos")++ assert [r["name"] for r in rows] == ["r1", "r3"]+++class TestFanOutRows:+ def test_fans_out_over_active_repos_and_injects_repo(self, monkeypatch: Any) -> None:+ pages = {+ _ACTIVE_REPOS_URL: _page([{"name": "r1"}, {"name": "r2"}]),+ f"{_BASE}/repos/r1/flags?page_size=500": _page([{"flag_name": "unit", "coverage": 90.0}]),+ f"{_BASE}/repos/r2/flags?page_size=500": _page([{"flag_name": "unit", "coverage": 80.0}]),+ }+ _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager()+ rows = _collect(manager, repositories=None, endpoint="flags")++ assert [(r["repo"], r["flag_name"]) for r in rows] == [("r1", "unit"), ("r2", "unit")]+ # The bookmark advances to the next repo so a crash between repos resumes correctly.+ assert manager.saved == [CodecovResumeConfig(next_url=None, repo="r2")]++ def test_repository_allow_list_skips_repo_enumeration(self, monkeypatch: Any) -> None:+ pages = {f"{_BASE}/repos/r9/flags?page_size=500": _page([{"flag_name": "unit", "coverage": 70.0}])}+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(_FakeResumableManager(), repositories="r9", endpoint="flags")++ assert [r["repo"] for r in rows] == ["r9"]+ assert _ACTIVE_REPOS_URL not in fetched++ def test_resumes_from_bookmarked_repo_and_url(self, monkeypatch: Any) -> None:+ resume_url = f"{_BASE}/repos/r2/flags?page=2&page_size=500"+ pages = {+ _ACTIVE_REPOS_URL: _page([{"name": "r1"}, {"name": "r2"}, {"name": "r3"}]),+ resume_url: _page([{"flag_name": "unit", "coverage": 80.0}]),+ f"{_BASE}/repos/r3/flags?page_size=500": _page([{"flag_name": "unit", "coverage": 60.0}]),+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(+ _FakeResumableManager(CodecovResumeConfig(next_url=resume_url, repo="r2")),+ repositories=None,+ endpoint="flags",+ )++ # r1 was already synced; r2 resumes mid-pagination, r3 starts from its first page.+ assert [r["repo"] for r in rows] == ["r2", "r3"]+ assert f"{_BASE}/repos/r1/flags?page_size=500" not in fetched++ def test_missing_bookmarked_repo_starts_over(self, monkeypatch: Any) -> None:+ pages = {+ _ACTIVE_REPOS_URL: _page([{"name": "r1"}]),+ f"{_BASE}/repos/r1/flags?page_size=500": _page([{"flag_name": "unit", "coverage": 90.0}]),+ }+ _patch_fetch(monkeypatch, pages)+ rows = _collect(+ _FakeResumableManager(CodecovResumeConfig(next_url="https://stale", repo="deleted-repo")),+ repositories=None,+ endpoint="flags",+ )++ assert [r["repo"] for r in rows] == ["r1"]++ def test_deleted_repo_404_is_skipped(self, monkeypatch: Any) -> None:+ pages = {+ _ACTIVE_REPOS_URL: _page([{"name": "r1"}, {"name": "r2"}]),+ f"{_BASE}/repos/r1/flags?page_size=500": _http_error(404),+ f"{_BASE}/repos/r2/flags?page_size=500": _page([{"flag_name": "unit", "coverage": 80.0}]),+ }+ _patch_fetch(monkeypatch, pages)+ rows = _collect(_FakeResumableManager(), repositories=None, endpoint="flags")++ assert [r["repo"] for r in rows] == ["r2"]++ def test_components_bare_list_endpoint(self, monkeypatch: Any) -> None:+ pages = {+ _ACTIVE_REPOS_URL: _page([{"name": "r1"}]),+ f"{_BASE}/repos/r1/components": [{"component_id": "api", "name": "api", "coverage": 91.2}],+ }+ _patch_fetch(monkeypatch, pages)+ rows = _collect(_FakeResumableManager(), repositories=None, endpoint="components")++ assert rows == [{"component_id": "api", "name": "api", "coverage": 91.2, "repo": "r1"}]+++class TestIncrementalSync:+ _WATERMARK = datetime(2026, 7, 5, tzinfo=UTC)++ def test_commits_stop_paging_at_watermark_but_continue_to_next_repo(self, monkeypatch: Any) -> None:+ pages = {+ _ACTIVE_REPOS_URL: _page([{"name": "r1"}, {"name": "r2"}]),+ f"{_BASE}/repos/r1/commits?page_size=500": _page(+ [+ {"commitid": "new", "timestamp": "2026-07-09T00:00:00Z"},+ {"commitid": "old", "timestamp": "2026-07-01T00:00:00Z"},+ ],+ next_url=f"{_BASE}/repos/r1/commits?page=2&page_size=500",+ ),+ f"{_BASE}/repos/r2/commits?page_size=500": _page(+ [{"commitid": "other", "timestamp": "2026-07-08T00:00:00Z"}]+ ),+ }+ fetched = _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager()+ rows = _collect(+ manager,+ repositories=None,+ endpoint="commits",+ should_use_incremental_field=True,+ db_incremental_field_last_value=self._WATERMARK,+ )++ # The boundary page is yielded in full (merge dedupes), then pagination stops for r1+ # while r2 still syncs.+ assert [r["commitid"] for r in rows] == ["new", "old", "other"]+ assert f"{_BASE}/repos/r1/commits?page=2&page_size=500" not in fetched+ # No page checkpoint is saved on a stopping page — only the repo bookmark.+ assert manager.saved == [CodecovResumeConfig(next_url=None, repo="r2")]++ def test_commits_without_watermark_page_through_everything(self, monkeypatch: Any) -> None:+ pages = {+ _ACTIVE_REPOS_URL: _page([{"name": "r1"}]),+ f"{_BASE}/repos/r1/commits?page_size=500": _page(+ [{"commitid": "a", "timestamp": "2026-07-09T00:00:00Z"}],+ next_url=f"{_BASE}/repos/r1/commits?page=2&page_size=500",+ ),+ f"{_BASE}/repos/r1/commits?page=2&page_size=500": _page(+ [{"commitid": "b", "timestamp": "2020-01-01T00:00:00Z"}]+ ),+ }+ _patch_fetch(monkeypatch, pages)+ rows = _collect(+ _FakeResumableManager(),+ repositories=None,+ endpoint="commits",+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )++ assert [r["commitid"] for r in rows] == ["a", "b"]++ def test_coverage_trend_uses_server_side_start_date(self, monkeypatch: Any) -> None:+ pages = {+ _ACTIVE_REPOS_URL: _page([{"name": "r1"}]),+ f"{_BASE}/repos/r1/coverage?page_size=500&interval=1d&start_date=2026-07-05": _page(+ [{"timestamp": "2026-07-06T00:00:00Z", "min": 90.0, "max": 91.0, "avg": 90.5}]+ ),+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(+ _FakeResumableManager(),+ repositories=None,+ endpoint="coverage_trend",+ should_use_incremental_field=True,+ db_incremental_field_last_value=self._WATERMARK,+ )++ assert [r["repo"] for r in rows] == ["r1"]+ assert fetched == list(pages)++ def test_coverage_trend_full_refresh_has_no_start_date(self, monkeypatch: Any) -> None:+ pages = {+ _ACTIVE_REPOS_URL: _page([{"name": "r1"}]),+ f"{_BASE}/repos/r1/coverage?page_size=500&interval=1d": _page(+ [{"timestamp": "2026-07-06T00:00:00Z", "min": 90.0, "max": 91.0, "avg": 90.5}]+ ),+ }+ fetched = _patch_fetch(monkeypatch, pages)+ _collect(_FakeResumableManager(), repositories=None, endpoint="coverage_trend")++ assert fetched == list(pages)+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", 200, (True, 200)),+ ("bad_token", 401, (False, 401)),+ ("unknown_owner", 404, (False, 404)),+ ]+ )+ def test_status_mapping(self, _name: str, status_code: int, expected: tuple) -> None:+ session = MagicMock()+ session.get.return_value = MagicMock(status_code=status_code)+ with mock.patch.object(codecov, "make_tracked_session", return_value=session):+ assert validate_credentials("token", "github", "acme") == expected++ def test_transport_error_maps_to_none(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with mock.patch.object(codecov, "make_tracked_session", return_value=session):+ assert validate_credentials("token", "github", "acme") == (False, None)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/tests/test_codecov_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/tests/test_codecov_source.pynew file mode 100644index 000000000000..a06dc9d8950d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/tests/test_codecov_source.py@@ -0,0 +1,170 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.codecov.settings import (+ CODECOV_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.codecov.source import CodecovSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CodecovSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++_INCREMENTAL_ENDPOINTS = {"commits", "coverage_trend"}+_FULL_REFRESH_ENDPOINTS = {"repos", "branches", "pulls", "flags", "components"}+++def _make_inputs(**overrides) -> SourceInputs:+ defaults: dict = {+ "schema_name": "commits",+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 123,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestCodecovSource:+ def setup_method(self):+ self.source = CodecovSource()+ self.team_id = 123+ self.config = CodecovSourceConfig(owner_username="acme", api_token="token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.CODECOV++ def test_get_source_config_is_released(self):+ config = self.source.get_source_config++ assert config.name.value == "Codecov"+ assert config.label == "Codecov (Sentry)"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/codecov"++ field_names = [f.name for f in config.fields]+ assert field_names == ["service", "owner_username", "api_token", "repositories"]++ def test_connection_host_fields_force_secret_reentry_on_scope_change(self):+ # Retargeting the git provider, owner, or repository allow-list reuses the stored token+ # against different Codecov resources, so the update serializer must require re-entry.+ assert self.source.connection_host_fields == ["service", "owner_username", "repositories"]++ def test_api_token_field_is_secret_password(self):+ config = self.source.get_source_config+ api_token_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token"+ )+ assert api_token_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_token_field.secret is True+ assert api_token_field.required is True++ def test_service_select_defaults_to_github(self):+ config = self.source.get_source_config+ service_field = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig))+ assert service_field.defaultValue == "github"+ assert {option.value for option in service_field.options} == {+ "github",+ "gitlab",+ "bitbucket",+ "github_enterprise",+ "gitlab_enterprise",+ "bitbucket_server",+ }++ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for name in _INCREMENTAL_ENDPOINTS:+ assert schemas[name].supports_incremental is True+ assert [f["field"] for f in schemas[name].incremental_fields] == ["timestamp"]+ for name in _FULL_REFRESH_ENDPOINTS:+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []+ # Incremental syncs re-pull boundary rows that only merge dedupes, so append stays off.+ for schema in schemas.values():+ assert schema.supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["commits"])+ assert [s.name for s in schemas] == ["commits"]++ def test_lists_tables_without_credentials_publishes_catalog(self):+ # Static endpoint catalog (no I/O) — the public docs table list should render.+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(CODECOV_ENDPOINTS)++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.codecov.io/api/v2/github/acme/repos?page_size=500",+ "403 Client Error: Forbidden for url: https://api.codecov.io/api/v2/github/acme/repos/r1/commits",+ "404 Client Error: Not Found for url: https://api.codecov.io/api/v2/github/acme/repos?page_size=500",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://api.codecov.io/api/v2/github/acme/repos",+ "500 Server Error: Internal Server Error for url: https://api.codecov.io/api/v2/github/acme/repos",+ "HTTPSConnectionPool(host='api.codecov.io', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, 200), True, None),+ ((False, 401), False, "Invalid Codecov API token"),+ ((False, 404), False, "Owner 'acme' not found on Codecov for the selected git provider"),+ ((False, None), False, "Could not connect to Codecov with the provided credentials"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.codecov.source.validate_codecov_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.codecov.source.codecov_source")+ def test_source_for_pipeline_gates_incremental_value(self, mock_codecov_source):+ # A stale watermark must not leak into a full-refresh run.+ inputs = _make_inputs(+ should_use_incremental_field=False,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ kwargs = mock_codecov_source.call_args.kwargs+ assert kwargs["endpoint"] == "commits"+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex c6fef4b4e327..898f8b347dd2 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@@ -936,7 +936,12 @@ class CodacySourceConfig(config.Config):@config.configclass CodecovSourceConfig(config.Config):- pass+ owner_username: str+ api_token: str+ service: Literal["github", "gitlab", "bitbucket", "github_enterprise", "gitlab_enterprise", "bitbucket_server"] = (+ config.value(default="github")+ )+ repositories: str | None = None@config.config