: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): add 5 missing tables to the Codecov source (#117754)
Tom Owerse5cda552d9a2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 464bf01606e5..f036fdea6916 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -2898,18 +2898,18 @@ Note: Codacy API v3 swagger is served at https://api.codacy.com/api/api-docs/swa## Codecov — gaps-Today (12): `branches`, `commits`, `components`, `coverage_trend`, `flags`, `pulls`, `repo_totals`, `report_files`, `report_tree`, `repos`, `test_results`, `users`+Today (17): `branches`, `commit_uploads`, `commits`, `components`, `coverage_trend`, `flag_coverage_trend`, `flags`, `pull_component_comparisons`, `pull_flag_comparisons`, `pull_impacted_files`, `pulls`, `repo_totals`, `report_files`, `report_tree`, `repos`, `test_results`, `users`Diffed against: <https://api.codecov.io/api/v2/schema>- [x] `/{service}/{owner}/repos/{repo}/totals/` — Current coverage totals per repo (lines, hits, misses, partials) - the headline number, only available as a trend today (high)- [x] `/{service}/{owner}/repos/{repo}/test-results/ (and /test-results/{id}/)` — Test Analytics: per-test failure rate, flake rate and runtime - Codecov's flagship non-coverage product, entirely unsynced (high)- [x] `/{service}/{owner}/repos/{repo}/report/ and /report/tree` — The coverage report broken down by file and directory, which turns repo-level coverage into something actionable (high)-- [ ] `/{service}/{owner}/repos/{repo}/flags/{flag_name}/coverage/` — Coverage trend per flag - the breakdown dimension for the flags table already synced (medium)+- [x] `/{service}/{owner}/repos/{repo}/flags/{flag_name}/coverage/` — Coverage trend per flag - the breakdown dimension for the flags table already synced (medium)- [ ] `/{service}/{owner}/repos/{repo}/file_report/{path}/` — Line-level coverage for a specific file, needed to find persistently uncovered hot spots (medium)-- [ ] `/{service}/{owner}/repos/{repo}/commits/{commitid}/uploads/` — Which CI jobs uploaded coverage for each commit - the way to detect missing or failed uploads skewing coverage (medium)+- [x] `/{service}/{owner}/repos/{repo}/commits/{commitid}/uploads/` — Which CI jobs uploaded coverage for each commit - the way to detect missing or failed uploads skewing coverage (medium)- [x] `/{service}/{owner}/users/` — Org member lookup resolving the author IDs on commits and pulls already synced (medium)-- [ ] `/{service}/{owner}/repos/{repo}/compare/impacted_files (also /compare/flags, /compare/components)` — Coverage delta of a pull request by file, flag and component - the review-time metric teams actually track (medium)+- [x] `/{service}/{owner}/repos/{repo}/compare/impacted_files (also /compare/flags, /compare/components)` — Coverage delta of a pull request by file, flag and component - the review-time metric teams actually track (medium)- [ ] `/{service}/{owner}/repos/{repo}/test-analytics/` — Aggregated test-suite health summary that pairs with the raw test results (medium)- [ ] `/{service}/{owner}/` — Owner/org record giving repos an organization-level parent to roll up to (low)diff --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.pyindex 7a9202ea2b73..b932d0c47c7f 100644--- 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.py@@ -171,4 +171,91 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"avg": "Average coverage percentage observed in the interval.",},},+ "flag_coverage_trend": {+ "description": "Daily coverage time series for each flag on a repository's default branch.",+ "docs_url": "https://docs.codecov.com/reference/repos_flags_coverage_list",+ "columns": {+ "repo": "Repository the measurement belongs to (injected by the import).",+ "flag_name": "Flag 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.",+ },+ },+ "commit_uploads": {+ "description": "A coverage report uploaded to Codecov for a commit, usually by one CI job.",+ "docs_url": "https://docs.codecov.com/reference/repos_commits_uploads_list",+ "columns": {+ "repo": "Repository the commit belongs to (injected by the import).",+ "commitid": "SHA of the commit the upload belongs to (injected by the import).",+ "commit_timestamp": "Timestamp of the commit the upload belongs to (injected by the import).",+ "created_at": "When Codecov received the upload.",+ "updated_at": "When Codecov last updated the upload.",+ "storage_path": "Where Codecov stores the raw uploaded report.",+ "flags": "Flags the upload was tagged with.",+ "provider": "CI provider that sent the upload.",+ "build_code": "Build identifier on the CI provider.",+ "name": "Name given to the upload.",+ "job_code": "Job identifier on the CI provider.",+ "build_url": "Link to the CI build that sent the upload.",+ "state": "Processing state of the upload.",+ "state_id": "Numeric code of the processing state.",+ "state_name": "Name of the processing state.",+ "env": "Environment variables the uploader attached.",+ "upload_type": "Kind of upload.",+ "upload_extras": "Extra metadata the uploader attached.",+ "totals": "Coverage totals of the upload (files, lines, hits, misses, partials, branches, methods, coverage percentage).",+ },+ },+ "pull_impacted_files": {+ "description": "A file whose coverage a pull request changes, compared with the pull request's base commit.",+ "docs_url": "https://docs.codecov.com/reference/repos_compare_impacted_files_retrieve",+ "columns": {+ "repo": "Repository the pull request belongs to (injected by the import).",+ "pullid": "Pull request number (injected by the import).",+ "pull_updatestamp": "When Codecov last updated the pull request (injected by the import).",+ "base_commit": "SHA of the base commit of the comparison.",+ "head_commit": "SHA of the head commit of the comparison.",+ "state": "Whether Codecov has finished computing the comparison (processed or pending).",+ "file_name": "Path of the file in the head commit, or in the base commit for a deleted file.",+ "base_name": "Path of the file in the base commit.",+ "head_name": "Path of the file in the head commit.",+ "is_new_file": "Whether the pull request adds the file.",+ "is_renamed_file": "Whether the pull request renames the file.",+ "is_deleted_file": "Whether the pull request deletes the file.",+ "base_coverage": "Coverage totals of the file in the base commit.",+ "head_coverage": "Coverage totals of the file in the head commit.",+ "patch_coverage": "Coverage totals of the lines the pull request changes in the file.",+ "change_coverage": "Change in coverage percentage between the base and head commits.",+ "misses_count": "Number of uncovered lines in the file that the pull request affects.",+ },+ },+ "pull_flag_comparisons": {+ "description": "Coverage of one flag on a pull request, for its base commit, head commit and diff.",+ "docs_url": "https://docs.codecov.com/reference/repos_compare_flags_retrieve",+ "columns": {+ "repo": "Repository the pull request belongs to (injected by the import).",+ "pullid": "Pull request number (injected by the import).",+ "pull_updatestamp": "When Codecov last updated the pull request (injected by the import).",+ "name": "Flag name.",+ "base_report_totals": "Coverage totals of the flag in the base commit.",+ "head_report_totals": "Coverage totals of the flag in the head commit.",+ "diff_totals": "Coverage totals of the flag on the lines the pull request changes.",+ },+ },+ "pull_component_comparisons": {+ "description": "Coverage of one component on a pull request, for its base commit, head commit and diff.",+ "docs_url": "https://docs.codecov.com/reference/repos_compare_components_retrieve",+ "columns": {+ "repo": "Repository the pull request belongs to (injected by the import).",+ "pullid": "Pull request number (injected by the import).",+ "pull_updatestamp": "When Codecov last updated the pull request (injected by the import).",+ "component_id": "Component identifier from the Codecov configuration.",+ "name": "Component name.",+ "base_report_totals": "Coverage totals of the component in the base commit.",+ "head_report_totals": "Coverage totals of the component in the head commit.",+ "diff_totals": "Coverage totals of the component on the lines the pull request changes.",+ },+ },}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.pyindex ba27635127a2..9a11def19a4c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/codecov.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/codecov.py@@ -12,6 +12,7 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exfrom products.warehouse_sources.backend.temporal.data_imports.sources.codecov.settings import (CODECOV_ENDPOINTS,CodecovEndpointConfig,+ CodecovParentConfig,CodecovResponseShape,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session@@ -48,8 +49,9 @@ def _owner_base_url(service: str, owner_username: str) -> str: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+def _endpoint_url(owner_base_url: str, path: str, params: dict[str, Any], **segments: str) -> str:+ if segments:+ path = path.format(**{name: quote(value, safe="") for name, value in segments.items()})url = f"{owner_base_url}{path}"return f"{url}?{urlencode(params)}" if params else url@@ -131,6 +133,21 @@ def _tree_rows(nodes: Any, repo: str) -> Iterator[dict[str, Any]]:yield from _tree_rows(node.get("children"), repo)+def _impacted_file_rows(data: Any, repo: str) -> list[dict[str, Any]]:+ """One row per impacted file, with the commits the comparison ran between.++ `files` stays empty while Codecov is still computing the comparison (`state: "pending"`).+ """+ if not data:+ return []+ comparison = {+ "base_commit": data.get("base_commit"),+ "head_commit": data.get("head_commit"),+ "state": data.get("state"),+ }+ return [{**file, **comparison, "repo": repo} for file in data.get("files") or []]++def _unpaginated_rows(shape: CodecovResponseShape, data: Any, repo: str) -> list[dict[str, Any]]:match shape:case CodecovResponseShape.BARE_LIST:@@ -141,6 +158,8 @@ def _unpaginated_rows(shape: CodecovResponseShape, data: Any, repo: str) -> listreturn _report_file_rows(data, repo)case CodecovResponseShape.TREE:return list(_tree_rows(data, repo))+ case CodecovResponseShape.IMPACTED_FILES:+ return _impacted_file_rows(data, repo)case _:raise ValueError(f"Endpoint response shape {shape} is paginated")@@ -220,7 +239,7 @@ def _get_top_level_rows(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})+ url = _endpoint_url(owner_base_url, config.path, {"page_size": PAGE_SIZE, **config.extra_params})allowed = set(repositories)for results, next_url in _iter_pages(session, url, headers, logger):@@ -236,6 +255,26 @@ def _get_top_level_rows(resumable_source_manager.save_state(CodecovResumeConfig(next_url=next_url))+def _remaining_repos(+ repo_names: list[str],+ config: CodecovEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CodecovResumeConfig],+) -> tuple[list[str], str | None]:+ """Resolve the saved repo bookmark to the slice of repos still to process, and the URL the+ first of them resumes from.++ 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 = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is None or resume.repo is None or resume.repo not in repo_names:+ return repo_names, None+ 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}")+ return repo_names[repo_names.index(resume.repo) :], resume_url++def _get_fan_out_rows(session: requests.Session,owner_base_url: str,@@ -263,20 +302,10 @@ def _get_fan_out_rows(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}")+ remaining, resume_url = _remaining_repos(repo_names, config, logger, resumable_source_manager)for index, repo in enumerate(remaining):- url = resume_url or _endpoint_url(owner_base_url, config, repo, params)+ url = resume_url or _endpoint_url(owner_base_url, config.path, params, repo=repo)resume_url = None # only the resumed-into repo uses the saved URL; the rest start freshtry:@@ -310,6 +339,127 @@ def _get_fan_out_rows(resumable_source_manager.save_state(CodecovResumeConfig(next_url=None, repo=remaining[index + 1]))+def _iter_child_rows(+ session: requests.Session,+ owner_base_url: str,+ headers: dict[str, str],+ config: CodecovEndpointConfig,+ parent: CodecovParentConfig,+ parent_row: dict[str, Any],+ repo: str,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Fetch the child endpoint for one parent row, yielding each page with the parent columns."""+ key = parent_row.get(parent.key_field)+ if key is None:+ return+ parent_columns = {column: parent_row.get(name) for name, column in parent.include_fields.items()}+ if parent.key_query_param:+ url = _endpoint_url(owner_base_url, config.path, {parent.key_query_param: key, **params}, repo=repo)+ else:+ url = _endpoint_url(owner_base_url, config.path, params, repo=repo, key=str(key))++ try:+ if config.response_shape is CodecovResponseShape.PAGINATED_LIST:+ for results, _next_url in _iter_pages(session, url, headers, logger):+ yield [{**item, **parent_columns, "repo": repo} for item in results]+ else:+ data = _fetch_page(session, url, headers, logger)+ yield [{**row, **parent_columns} for row in _unpaginated_rows(config.response_shape, data, repo)]+ except requests.HTTPError as exc:+ # A pull missing its base or head commit has no comparison, and a flag or commit can go+ # away between listing it and this fetch. Skip that row rather than fail the sync.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Codecov: {config.name} not found for repo={repo}, {parent.key_field}={key}, skipping")+ else:+ raise+++def _iter_parent_fan_out_batches(+ session: requests.Session,+ owner_base_url: str,+ headers: dict[str, str],+ config: CodecovEndpointConfig,+ parent: CodecovParentConfig,+ repositories: list[str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CodecovResumeConfig],+ cutoff: datetime | None,+) -> Iterator[tuple[list[dict[str, Any]], CodecovResumeConfig | None]]:+ """Yield (rows, state) per child response. `state` is set, with no rows, once every row of a+ parent page has been yielded: it is the position to resume from after that page."""+ repo_names = repositories or list(_iter_repo_names(session, owner_base_url, headers, logger))++ parent_params: dict[str, Any] = {"page_size": PAGE_SIZE}+ child_params: dict[str, Any] = {**config.extra_params}+ if config.response_shape is CodecovResponseShape.PAGINATED_LIST:+ child_params = {"page_size": PAGE_SIZE, **config.extra_params}+ stop_field: str | None = None+ if cutoff is not None:+ if config.incremental_server_param:+ child_params[config.incremental_server_param] = _format_start_date(cutoff)+ if parent.incremental_server_param:+ parent_params[parent.incremental_server_param] = _format_start_date(cutoff)+ stop_field = parent.incremental_stop_field++ remaining, resume_url = _remaining_repos(repo_names, config, logger, resumable_source_manager)++ for index, repo in enumerate(remaining):+ next_repo = (+ CodecovResumeConfig(next_url=None, repo=remaining[index + 1]) if index + 1 < len(remaining) else None+ )+ url = resume_url or _endpoint_url(owner_base_url, parent.path, parent_params, repo=repo)+ resume_url = None++ try:+ for parents, next_url in _iter_pages(session, url, headers, logger):+ for parent_row in parents:+ for rows in _iter_child_rows(+ session, owner_base_url, headers, config, parent, parent_row, repo, child_params, logger+ ):+ yield rows, None+ if not next_url or _should_stop_desc(parents, stop_field, cutoff):+ break+ yield [], CodecovResumeConfig(next_url=next_url, repo=repo)+ except requests.HTTPError as exc:+ # The parent list of a repo deleted (or deactivated) since enumeration 404s.+ 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++ yield [], next_repo+++def _get_parent_fan_out_rows(+ session: requests.Session,+ owner_base_url: str,+ headers: dict[str, str],+ config: CodecovEndpointConfig,+ parent: CodecovParentConfig,+ repositories: list[str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CodecovResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over a list inside each repository (flags, commits or pulls), then fetch the+ child endpoint once per row of that list."""+ cutoff = _normalize_cutoff(db_incremental_field_last_value) if should_use_incremental_field else None+ for rows, state in _iter_parent_fan_out_batches(+ session, owner_base_url, headers, config, parent, repositories, logger, resumable_source_manager, cutoff+ ):+ if state is not None:+ resumable_source_manager.save_state(state)+ if rows:+ yield rows+ else:+ # Many parent rows have no child rows (a commit without uploads, a pull without a+ # comparison). Nothing is buffered here, so a shutdown can hand the run over.+ resumable_source_manager.safe_point()++def get_rows(api_token: str,service: str,@@ -329,7 +479,20 @@ def get_rows(# One session reused across every page (and repo) so urllib3 keeps the connection alive.session = make_tracked_session()- if config.fan_out_over_repos:+ if config.parent is not None:+ yield from _get_parent_fan_out_rows(+ session,+ owner_base_url,+ headers,+ config,+ config.parent,+ repo_filter,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ elif config.fan_out_over_repos:yield from _get_fan_out_rows(session,owner_base_url,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/settings.pyindex 75566f43f012..7a249fff0926 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codecov/settings.py@@ -19,12 +19,31 @@ class CodecovResponseShape(StrEnum):TOTALS = "totals" # coverage report object, flattened to a single totals rowREPORT_FILES = "report_files" # coverage report object, one row per entry in `files`TREE = "tree" # nested directory tree, one row per node at any depth+ IMPACTED_FILES = "impacted_files" # comparison object, one row per entry in `files`+++@frozen+class CodecovParentConfig:+ """A repository-scoped list that a child endpoint fans out over, one child request per row."""++ path: str # e.g. "/repos/{repo}/commits"+ key_field: str # Parent row field that addresses the child request+ include_fields: dict[str, str] # Parent row field -> column it fills on every child row+ # Query param that carries the key. None means the child path takes it as "{key}".+ key_query_param: Optional[str] = None+ # Server-side time filter on the parent list, sent when an incremental watermark exists.+ incremental_server_param: Optional[str] = None+ # Parent field to stop newest-first parent paging at the watermark when there is no+ # server-side filter.+ incremental_stop_field: Optional[str] = None@frozenclass CodecovEndpointConfig:name: str- path: str # Path template relative to /{service}/{owner_username}; "{repo}" is filled per repository during fan-out+ # Path template relative to /{service}/{owner_username}; "{repo}" is filled per repository+ # during fan-out, and "{key}" per parent row for endpoints with a `parent`.+ path: strincremental_fields: list[IncrementalField]primary_keys: list[str]default_incremental_field: Optional[str] = None@@ -40,6 +59,8 @@ class CodecovEndpointConfig:# allowed repositories, and owner-level endpoints are not repository-scoped at all.filtered_by_repository_allow_list: bool = Falseextra_params: dict[str, str] = field(default_factory=dict)+ # Set for endpoints keyed on a row of a repository-scoped list (a flag, a commit, a pull).+ parent: Optional[CodecovParentConfig] = None_TIMESTAMP_INCREMENTAL_FIELD: IncrementalField = {@@ -49,6 +70,30 @@ _TIMESTAMP_INCREMENTAL_FIELD: IncrementalField = {"field_type": IncrementalFieldType.DateTime,}+_COMMIT_TIMESTAMP_INCREMENTAL_FIELD: IncrementalField = {+ "label": "commit_timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "commit_timestamp",+ "field_type": IncrementalFieldType.DateTime,+}++_PULL_UPDATESTAMP_INCREMENTAL_FIELD: IncrementalField = {+ "label": "pull_updatestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "pull_updatestamp",+ "field_type": IncrementalFieldType.DateTime,+}++# The pulls list filters on `updatestamp` server-side, so a comparison is re-fetched only for a+# pull that changed since the last sync.+_PULL_PARENT = CodecovParentConfig(+ path="/repos/{repo}/pulls",+ key_field="pullid",+ include_fields={"pullid": "pullid", "updatestamp": "pull_updatestamp"},+ key_query_param="pullid",+ incremental_server_param="start_date",+)+CODECOV_ENDPOINTS: dict[str, CodecovEndpointConfig] = {"repos": CodecovEndpointConfig(@@ -151,6 +196,71 @@ CODECOV_ENDPOINTS: dict[str, CodecovEndpointConfig] = {partition_key="timestamp",fan_out_over_repos=True,),+ "flag_coverage_trend": CodecovEndpointConfig(+ name="flag_coverage_trend",+ path="/repos/{repo}/flags/{key}/coverage",+ # Same server-side `start_date` filter as coverage_trend, applied per flag.+ incremental_fields=[_TIMESTAMP_INCREMENTAL_FIELD],+ default_incremental_field="timestamp",+ incremental_server_param="start_date",+ primary_keys=["repo", "flag_name", "timestamp"],+ partition_key="timestamp",+ fan_out_over_repos=True,+ extra_params={"interval": "1d"},+ parent=CodecovParentConfig(+ path="/repos/{repo}/flags",+ key_field="flag_name",+ include_fields={"flag_name": "flag_name"},+ ),+ ),+ "commit_uploads": CodecovEndpointConfig(+ name="commit_uploads",+ path="/repos/{repo}/commits/{key}/uploads",+ # Uploads have no filter of their own. The parent commits list is newest-first, so+ # incremental sync stops paging commits once a page predates the watermark.+ incremental_fields=[_COMMIT_TIMESTAMP_INCREMENTAL_FIELD],+ default_incremental_field="commit_timestamp",+ # Uploads carry no id. Codecov gives each upload its own storage path and creation time.+ primary_keys=["repo", "commitid", "created_at", "storage_path"],+ partition_key="created_at",+ fan_out_over_repos=True,+ parent=CodecovParentConfig(+ path="/repos/{repo}/commits",+ key_field="commitid",+ include_fields={"commitid": "commitid", "timestamp": "commit_timestamp"},+ incremental_stop_field="timestamp",+ ),+ ),+ "pull_impacted_files": CodecovEndpointConfig(+ name="pull_impacted_files",+ path="/repos/{repo}/compare/impacted_files",+ incremental_fields=[_PULL_UPDATESTAMP_INCREMENTAL_FIELD],+ default_incremental_field="pull_updatestamp",+ primary_keys=["repo", "pullid", "file_name"],+ fan_out_over_repos=True,+ response_shape=CodecovResponseShape.IMPACTED_FILES,+ parent=_PULL_PARENT,+ ),+ "pull_flag_comparisons": CodecovEndpointConfig(+ name="pull_flag_comparisons",+ path="/repos/{repo}/compare/flags",+ incremental_fields=[_PULL_UPDATESTAMP_INCREMENTAL_FIELD],+ default_incremental_field="pull_updatestamp",+ primary_keys=["repo", "pullid", "name"],+ fan_out_over_repos=True,+ response_shape=CodecovResponseShape.BARE_LIST,+ parent=_PULL_PARENT,+ ),+ "pull_component_comparisons": CodecovEndpointConfig(+ name="pull_component_comparisons",+ path="/repos/{repo}/compare/components",+ incremental_fields=[_PULL_UPDATESTAMP_INCREMENTAL_FIELD],+ default_incremental_field="pull_updatestamp",+ primary_keys=["repo", "pullid", "component_id"],+ fan_out_over_repos=True,+ response_shape=CodecovResponseShape.BARE_LIST,+ parent=_PULL_PARENT,+ ),"users": CodecovEndpointConfig(name="users",path="/users",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 f3a8b7e1309a..70f1660ab2a4 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@@ -43,6 +43,11 @@ _ENDPOINT_DESCRIPTIONS: dict[str, str] = {"report_tree": "Current coverage rolled up per directory and file, following the repository's file tree","test_results": "Individual test runs from Test Analytics, with outcome, duration and failure message","users": "Members of the Codecov organization, resolving the author usernames on commits and pulls",+ "flag_coverage_trend": "Daily min/max/avg coverage time series per flag, per repository (default branch)",+ "commit_uploads": "Coverage uploads received for each commit, with the CI job, flags and processing state",+ "pull_impacted_files": "Per-file coverage change of each pull request against its base commit",+ "pull_flag_comparisons": "Per-flag coverage of each pull request's base and head commits, and of its diff",+ "pull_component_comparisons": "Per-component coverage of each pull request's base and head commits, and of its diff",}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.pyindex 805cf642a421..10acc867ad55 100644--- 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.py@@ -310,6 +310,146 @@ class TestCoverageReportEndpoints:assert result.urls == list(pages)+class TestParentFanOut:+ @parameterized.expand(+ [+ (+ # The flag name is a path segment, so it is percent-encoded.+ "flag_coverage_trend",+ f"{_BASE}/repos/r1/flags?page_size=500",+ [{"flag_name": "unit/py", "coverage": 90.0}],+ f"{_BASE}/repos/r1/flags/unit%2Fpy/coverage?page_size=500&interval=1d",+ _page([{"timestamp": "2026-07-06T00:00:00Z", "min": 90.0, "max": 91.0, "avg": 90.5}]),+ [+ {+ "timestamp": "2026-07-06T00:00:00Z",+ "min": 90.0,+ "max": 91.0,+ "avg": 90.5,+ "flag_name": "unit/py",+ "repo": "r1",+ }+ ],+ ),+ (+ "pull_impacted_files",+ f"{_BASE}/repos/r1/pulls?page_size=500",+ [{"pullid": 7, "updatestamp": "2026-07-06T00:00:00Z"}],+ f"{_BASE}/repos/r1/compare/impacted_files?pullid=7",+ {+ "base_commit": "aaa",+ "head_commit": "bbb",+ "state": "processed",+ "totals": {"base": {}, "head": {}},+ "commit_uploads": [{"commitid": "bbb"}],+ "diff": {"git_commits": []},+ "untracked": [],+ "files": [{"file_name": "app.py", "change_coverage": 5.0}],+ },+ [+ {+ "file_name": "app.py",+ "change_coverage": 5.0,+ "base_commit": "aaa",+ "head_commit": "bbb",+ "state": "processed",+ "repo": "r1",+ "pullid": 7,+ "pull_updatestamp": "2026-07-06T00:00:00Z",+ }+ ],+ ),+ (+ # Codecov is still computing the comparison, so there are no file rows yet.+ "pull_impacted_files_pending",+ f"{_BASE}/repos/r1/pulls?page_size=500",+ [{"pullid": 7, "updatestamp": "2026-07-06T00:00:00Z"}],+ f"{_BASE}/repos/r1/compare/impacted_files?pullid=7",+ {"base_commit": "aaa", "head_commit": "bbb", "state": "pending", "files": []},+ [],+ ),+ (+ "pull_component_comparisons",+ f"{_BASE}/repos/r1/pulls?page_size=500",+ [{"pullid": 7, "updatestamp": None}],+ f"{_BASE}/repos/r1/compare/components?pullid=7",+ [{"component_id": "api", "name": "api", "diff_totals": {"coverage": 80.0}}],+ [+ {+ "component_id": "api",+ "name": "api",+ "diff_totals": {"coverage": 80.0},+ "repo": "r1",+ "pullid": 7,+ "pull_updatestamp": None,+ }+ ],+ ),+ ]+ )+ def test_child_rows_carry_parent_columns(+ self,+ name: str,+ parent_url: str,+ parents: list[dict],+ child_url: str,+ child_response: Any,+ expected_rows: list[dict],+ ) -> None:+ schema_name = name.removesuffix("_pending")+ pages = {_ACTIVE_REPOS_URL: _page([{"name": "r1"}]), parent_url: _page(parents), child_url: child_response}+ result = _run(schema_name, pages)++ assert result.raised is None+ assert result.rows == expected_rows+ assert result.urls == list(pages)++ def test_walks_parent_pages_and_skips_children_that_404(self) -> None:+ commits_page_2 = f"{_BASE}/repos/r1/commits?page=2&page_size=500"+ pages = {+ _ACTIVE_REPOS_URL: _page([{"name": "r1"}, {"name": "r2"}]),+ f"{_BASE}/repos/r1/commits?page_size=500": _page(+ [{"commitid": "c1", "timestamp": "2026-07-09T00:00:00Z"}], next_url=commits_page_2+ ),+ # A commit without uploads (or deleted since the listing) is skipped, not fatal.+ f"{_BASE}/repos/r1/commits/c1/uploads?page_size=500": ScriptedResponse(status=404),+ commits_page_2: _page([{"commitid": "c2", "timestamp": "2026-07-08T00:00:00Z"}]),+ f"{_BASE}/repos/r1/commits/c2/uploads?page_size=500": _page(+ [{"created_at": "2026-07-08T00:01:00Z", "storage_path": "v4/raw/c2/u1.txt", "state": "processed"}]+ ),+ # A repo whose commit list 404s (deleted since enumeration) is skipped too.+ f"{_BASE}/repos/r2/commits?page_size=500": ScriptedResponse(status=404),+ }+ result = _run("commit_uploads", pages)++ assert result.raised is None+ assert [(r["repo"], r["commitid"], r["commit_timestamp"], r["storage_path"]) for r in result.rows] == [+ ("r1", "c2", "2026-07-08T00:00:00Z", "v4/raw/c2/u1.txt")+ ]+ assert result.urls == list(pages)+ # The cursor moves to the next parent page, then to the next repo, once every child row+ # before it has been yielded.+ assert result.saved_states == [+ CodecovResumeConfig(next_url=commits_page_2, repo="r1"),+ CodecovResumeConfig(next_url=None, repo="r2"),+ ]++ def test_resumes_from_saved_parent_page(self) -> None:+ resume_url = f"{_BASE}/repos/r2/flags?page=2&page_size=500"+ pages = {+ _ACTIVE_REPOS_URL: _page([{"name": "r1"}, {"name": "r2"}]),+ resume_url: _page([{"flag_name": "e2e"}]),+ f"{_BASE}/repos/r2/flags/e2e/coverage?page_size=500&interval=1d": _page(+ [{"timestamp": "2026-07-06T00:00:00Z", "min": 1.0, "max": 1.0, "avg": 1.0}]+ ),+ }+ result = _run("flag_coverage_trend", pages, resume_state=CodecovResumeConfig(next_url=resume_url, repo="r2"))++ assert result.raised is None+ assert [(r["repo"], r["flag_name"]) for r in result.rows] == [("r2", "e2e")]+ assert result.urls == list(pages)++class TestIncrementalSync:_WATERMARK = datetime(2026, 7, 5, tzinfo=UTC)@@ -384,6 +524,63 @@ class TestIncrementalSync:assert result.urls == list(pages)assert result.requests[-1].param("start_date") == "2026-07-05"+ @parameterized.expand(+ [+ (+ # The pulls list filters on `updatestamp` server-side.+ "pull_flag_comparisons",+ {+ f"{_BASE}/repos/r1/pulls?page_size=500&start_date=2026-07-05": _page(+ [{"pullid": 7, "updatestamp": "2026-07-06T00:00:00Z"}]+ ),+ f"{_BASE}/repos/r1/compare/flags?pullid=7": [{"name": "unit", "diff_totals": None}],+ },+ ),+ (+ # Each flag's coverage series takes the same `start_date` as coverage_trend.+ "flag_coverage_trend",+ {+ f"{_BASE}/repos/r1/flags?page_size=500": _page([{"flag_name": "unit"}]),+ f"{_BASE}/repos/r1/flags/unit/coverage?page_size=500&interval=1d&start_date=2026-07-05": _page(+ [{"timestamp": "2026-07-06T00:00:00Z", "min": 1.0, "max": 1.0, "avg": 1.0}]+ ),+ },+ ),+ (+ # Uploads have no filter, so paging the newest-first commits stops at the+ # watermark; page 2 is never requested.+ "commit_uploads",+ {+ 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/r1/commits/new/uploads?page_size=500": _page(+ [{"created_at": "2026-07-09T00:01:00Z", "storage_path": "a"}]+ ),+ f"{_BASE}/repos/r1/commits/old/uploads?page_size=500": _page(+ [{"created_at": "2026-07-01T00:01:00Z", "storage_path": "b"}]+ ),+ },+ ),+ ]+ )+ def test_parent_fan_out_incremental_request_shaping(self, schema_name: str, endpoint_pages: dict[str, Any]) -> None:+ pages = {_ACTIVE_REPOS_URL: _page([{"name": "r1"}]), **endpoint_pages}+ result = _run(+ schema_name,+ pages,+ should_use_incremental_field=True,+ db_incremental_field_last_value=self._WATERMARK,+ )++ assert result.raised is None+ assert result.rows+ assert result.urls == list(pages)+class TestValidateCredentials:@parameterized.expand(