: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(warehouse-sources): add Bitbucket pipeline steps, commit statuses and branches (#100957)
Tom Owersaee556a1a7fd
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 d712d75b2b93..e60c5fa0274d 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@@ -818,7 +818,7 @@ Note: BigMailer's public API exposes no per-recipient engagement or event endpoi## Bitbucket — gaps-Today (10): `commits`, `deployments`, `environments`, `pipelines`, `projects`, `pull_request_activity`, `pull_request_comments`, `pull_requests`, `repositories`, `workspace_members`+Today (13): `branches`, `commit_statuses`, `commits`, `deployments`, `environments`, `pipeline_steps`, `pipelines`, `projects`, `pull_request_activity`, `pull_request_comments`, `pull_requests`, `repositories`, `workspace_members`Diffed against: <https://api.bitbucket.org/swagger.json>@@ -826,14 +826,18 @@ Diffed against: <https://api.bitbucket.org/swagger.json>- [x] `repositories/{workspace}/{repo}/pullrequests/{id}/comments` — code review comment volume and latency (high)- [x] `repositories/{workspace}/{repo}/environments` — lookup resolving the environment referenced by the deployments we already sync (high)- [x] `workspaces/{workspace}/projects` — lookup grouping the repositories we already sync under a project key (high)-- [ ] `repositories/{workspace}/{repo}/pipelines/{uuid}/steps` — per-step CI durations and outcomes; the pipelines row alone gives no breakdown (high)-- [ ] `repositories/{workspace}/{repo}/issues` — repo issue tracker records (medium)-- [ ] `repositories/{workspace}/{repo}/commit/{commit}/statuses` — external build/check status per commit we already sync (medium)-- [ ] `repositories/{workspace}/{repo}/refs/branches` — branch lookup resolving branch names on PRs, pipelines and deployments (medium)+- [x] `repositories/{workspace}/{repo}/pipelines/{uuid}/steps` — per-step CI durations and outcomes; the pipelines row alone gives no breakdown (high)+- [ ] `repositories/{workspace}/{repo}/issues` — repo issue tracker records (medium). Removed by Atlassian: the endpoint returns 410 Gone (changelog CHANGE-3071), so there is nothing to sync.+- [x] `repositories/{workspace}/{repo}/commit/{commit}/statuses` — external build/check status per commit we already sync (medium)+- [x] `repositories/{workspace}/{repo}/refs/branches` — branch lookup resolving branch names on PRs, pipelines and deployments (medium)- [ ] `repositories/{workspace}/{repo}/pullrequests/{id}/commits` — PR-to-commit join enabling change-size metrics (medium)- [ ] `repositories/{workspace}/{repo}/pipelines/{uuid}/steps/{uuid}/test_reports/test_cases` — per-test-case CI results for flakiness analysis (medium)-- [ ] `repositories/{workspace}/{repo}/issues/{id}/comments` — issue discussion volume (medium)-- [ ] `repositories/{workspace}/{repo}/issues/{id}/changes` — issue state transition history (low)+- [ ] `repositories/{workspace}/{repo}/issues/{id}/comments` — issue discussion volume (medium). Removed with the rest of the issue tracker API (CHANGE-3071).+- [ ] `repositories/{workspace}/{repo}/issues/{id}/changes` — issue state transition history (low). Removed with the rest of the issue tracker API (CHANGE-3071).++Note: `pipeline_steps` and `commit_statuses` cost one request per parent row, so their parent walk+is bounded — by the incremental watermark once a table has synced, and by a per-repository cap on the+first sync. `commit_statuses` is not selected by default for that reason.Note: `pull_request_activity` syncs the repo-level `pullrequests/activity` feed rather than theper-pull-request path listed above. Both return the same entries; the repo-level feed covers everydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/bitbucket.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/bitbucket.pyindex 8dcb2481347d..4a3b2fbee431 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/bitbucket.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/bitbucket.py@@ -2,7 +2,7 @@ import dataclassesfrom collections.abc import Callable, Iteratorfrom datetime import UTC, date, datetimefrom typing import Any, Optional-from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit+from urllib.parse import parse_qsl, quote, urlencode, urlsplit, urlunsplitimport requestsfrom dateutil import parser as dateutil_parser@@ -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.bitbucket.settings import (BITBUCKET_ENDPOINTS,BitbucketEndpointConfig,+ SecondLevelFanOut,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -36,10 +37,12 @@ class BitbucketResumeConfig:# (not a positional index) so repos added/removed between a crash and the retry# can't resume us into the wrong repo. None for top-level endpoints.repo_slug: str | None = None- # Second-level bookmark for endpoints that fan out over pull requests. Ids are- # assigned in creation order within a repo, so the walk resumes by skipping every- # pull request below it, so a deleted bookmark lands on the next one up.- pull_request_id: int | None = None+ # Second-level bookmarks for endpoints that fan out over a parent endpoint. The+ # cursor is the parent's ordering value, which resolves where the walk had reached+ # even if the bookmarked parent itself has since been deleted; the id identifies the+ # exact parent `next_url` belongs to. Both None for single-level endpoints.+ parent_id: str | None = None+ parent_cursor: str | None = None@dataclasses.dataclass(frozen=True)@@ -260,8 +263,19 @@ def _normalize_comment_row(row: dict[str, Any]) -> dict[str, Any]:return {**row, "pull_request_id": pull_request.get("id"), "user_uuid": user.get("uuid")}+def _normalize_pipeline_step_row(row: dict[str, Any]) -> dict[str, Any]:+ # A step that pulls its build container from a private registry carries the registry+ # password in `image`. Persisting it would hand the credential to everyone with+ # warehouse query access, including people with no access to the repository.+ image = row.get("image")+ if not isinstance(image, dict) or "password" not in image:+ return row+ return {**row, "image": {key: value for key, value in image.items() if key != "password"}}++_ROW_MAPPERS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {"workspace_members": _normalize_member_row,+ "pipeline_steps": _normalize_pipeline_step_row,"pull_request_activity": _normalize_activity_row,"pull_request_comments": _normalize_comment_row,}@@ -408,120 +422,167 @@ def _get_fan_out_rows()-def _iter_pull_requests(+def _parent_precedes_bookmark(order: str, value: Any, bookmark: str) -> bool:+ """True when a parent sits before the resume bookmark in the walk's own order, so the+ previous attempt already processed it. A value we cannot compare is never skipped —+ re-fetching a parent costs requests, skipping one loses its rows."""+ if order == "id_asc":+ try:+ return int(value) < int(bookmark)+ except (TypeError, ValueError):+ return False++ parsed = _as_utc_datetime(value)+ marked = _as_utc_datetime(bookmark)+ if parsed is None or marked is None:+ return False+ return parsed > marked+++def _iter_fan_out_parents(session: requests.Session,+ fan_out: SecondLevelFanOut,workspace: str,repo_slug: str,logger: FilteringBoundLogger,- since: datetime | None,+ since: Any,) -> Iterator[dict[str, Any]]:- """Page a repository's pull requests to seed a two-level fan-out. Reuses the- pull_requests endpoint's own state params and page size so the list stays defined in- one place, and sorts on the immutable created_on so ids arrive ascending, which is- what lets the resume bookmark skip by id."""- parent = BITBUCKET_ENDPOINTS["pull_requests"]- params = [("pagelen", str(parent.page_size)), *parent.extra_params, ("sort", "created_on")]- if since is not None:- params.append(("q", f'updated_on > "{_format_bbql_datetime(since)}"'))+ """Walk one repository's parent rows for a two-level fan-out, reusing the parent+ endpoint's own page size and params so the list stays defined in one place."""+ parent = BITBUCKET_ENDPOINTS[fan_out.parent]+ params: list[tuple[str, str]] = [("pagelen", str(parent.page_size)), *parent.extra_params]+ if fan_out.parent_sort:+ params.append(("sort", fan_out.parent_sort))+ if fan_out.parent_filter_field and since is not None:+ params.append(("q", f'{fan_out.parent_filter_field} > "{_format_bbql_datetime(since)}"'))++ # Parents the server can't filter are bounded here instead: they arrive newest-first,+ # so the walk stops once a whole page predates the watermark.+ cutoff = None if fan_out.parent_filter_field else _as_utc_datetime(since)url = _build_url(parent.path.format(workspace=workspace, repo_slug=repo_slug), params)+ walked = 0while True:data = _fetch_page(session, url, logger)- yield from data.get("values", [])+ items = data.get("values", [])next_url = data.get("next")+ if next_url and parent.rebuild_page_urls:+ next_url = _increment_page_url(url, int(data.get("page") or 1))++ if cutoff is not None and _page_predates_cutoff(items, fan_out.order_field, cutoff):+ return++ for item in items:+ yield item+ walked += 1+ if fan_out.max_parents_per_repo is not None and walked >= fan_out.max_parents_per_repo:+ logger.warning(+ f"Bitbucket: reached the {fan_out.max_parents_per_repo} {fan_out.parent} cap for "+ f"repo {repo_slug}; older {fan_out.parent} are not walked this sync"+ )+ return+if not next_url:- break+ returnurl = next_url-def _get_pull_request_fan_out_rows(+def _get_second_level_fan_out_rows(session: requests.Session,config: BitbucketEndpointConfig,+ fan_out: SecondLevelFanOut,workspace: str,resumable_source_manager: ResumableSourceManager[BitbucketResumeConfig],logger: FilteringBoundLogger,params: list[tuple[str, str]],parent_since: Any,) -> Iterator[list[dict[str, Any]]]:- """Two-level fan-out: every repository in the workspace, then every pull request in it.+ """Two-level fan-out: every repository in the workspace, then every row of a parent+ endpoint within it, then this endpoint once per parent row.- An incremental sync narrows the pull request walk to those updated since the watermark,- which is sound because posting, editing or deleting a comment bumps the pull request's- own updated_on. Without that bound every sync would issue one request per pull request- that ever existed, which no workspace's rate budget survives."""+ An incremental sync narrows the parent walk to what changed since the watermark. Without+ that bound every sync would issue one request per parent that ever existed, which no+ workspace's rate budget survives."""repos = [repo for repo in _iter_repositories(session, workspace, logger) if repo.get("slug")]resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Noneremaining = repos- resume_pull_request: int | None = None+ resume_parent_id: str | None = None+ resume_parent_cursor: str | None = Noneresume_url: str | None = Noneif resume is not None and resume.repo_slug is not None:slugs = [repo["slug"] for repo in repos]if resume.repo_slug in slugs:remaining = repos[slugs.index(resume.repo_slug) :]- resume_pull_request = resume.pull_request_id+ resume_parent_id = resume.parent_id+ resume_parent_cursor = resume.parent_cursorresume_url = resume.next_urllogger.debug(f"Bitbucket: resuming {config.name} from repo={resume.repo_slug}, "- f"pull_request={resume_pull_request}, url={resume_url}"+ f"parent={resume_parent_id}, url={resume_url}")for index, repo in enumerate(remaining):# The bookmark only describes the repo it was taken in; later repos start fresh.- bookmark_pull_request = resume_pull_request if index == 0 else None+ bookmark_cursor = resume_parent_cursor if index == 0 else None+ bookmark_id = resume_parent_id if index == 0 else Nonebookmark_url = resume_url if index == 0 else Nonetry:- for pull_request in _iter_pull_requests(session, workspace, repo["slug"], logger, parent_since):- pull_request_id = pull_request.get("id")- if (- bookmark_pull_request is not None- and isinstance(pull_request_id, int)- and pull_request_id < bookmark_pull_request- ):+ for parent in _iter_fan_out_parents(session, fan_out, workspace, repo["slug"], logger, parent_since):+ cursor = parent.get(fan_out.order_field)+ if bookmark_cursor is not None and _parent_precedes_bookmark(fan_out.order, cursor, bookmark_cursor):continue- if bookmark_url and pull_request_id == bookmark_pull_request:+ parent_id = parent.get(fan_out.id_field)+ if bookmark_url and str(parent_id) == bookmark_id:url = bookmark_urlelse:url = _build_url(config.path.format(- workspace=workspace, repo_slug=repo["slug"], pull_request_id=pull_request_id+ workspace=workspace,+ repo_slug=repo["slug"],+ # Pipeline uuids are braced, which is not path-safe.+ **{fan_out.path_param: quote(str(parent_id), safe="")},),params,)bookmark_url = None+ injected = {column: parent.get(field) for column, field in fan_out.inject.items()}+ bookmark = BitbucketResumeConfig(+ repo_slug=repo["slug"],+ parent_id=str(parent_id),+ parent_cursor=str(cursor) if cursor is not None else None,+ )+try:while True:data = _fetch_page(session, url, logger)items = data.get("values", [])next_url = data.get("next")- rows = _map_rows(config.name, items, repo)+ rows = [{**row, **injected} for row in _map_rows(config.name, items, repo)]if rows:yield rows- resumable_source_manager.save_state(- BitbucketResumeConfig(- next_url=next_url, repo_slug=repo["slug"], pull_request_id=pull_request_id- )- )+ resumable_source_manager.save_state(dataclasses.replace(bookmark, next_url=next_url))if not next_url:breakurl = next_urlexcept requests.HTTPError as exc:- # The pull request was deleted between the listing and this fetch. Skip- # it and keep going through the repo's remaining pull requests.+ # The parent was deleted between the listing and this fetch. Skip it and+ # keep going through the repo's remaining parents.if exc.response is not None and exc.response.status_code == 404:logger.warning(f"Bitbucket: {config.name} not available for "- f"{repo['slug']} pull request {pull_request_id}, skipping"+ f"{repo['slug']} {fan_out.parent} {parent_id}, skipping")continueraiseexcept requests.HTTPError as exc:- # The repository was deleted between enumeration and the pull request walk.+ # The repository was deleted between enumeration and the parent walk, or the+ # parent endpoint is not enabled on it (a repo with Pipelines turned off).if exc.response is not None and exc.response.status_code == 404:logger.warning(f"Bitbucket: {config.name} not available for repo {repo['slug']}, skipping")else:@@ -551,10 +612,11 @@ def get_rows(config, should_use_incremental_field, db_incremental_field_last_value, incremental_field)- if config.fan_out_over_pull_requests:- yield from _get_pull_request_fan_out_rows(+ if config.fan_out is not None:+ yield from _get_second_level_fan_out_rows(session,config,+ config.fan_out,workspace,resumable_source_manager,logger,@@ -600,9 +662,7 @@ def bitbucket_source(# ascending — desc defers the incremental watermark to successful job end (max# seen), instead of checkpointing per batch as asc would. Top-level endpoints# request an ascending server sort, so asc checkpointing is safe there.- sort_mode="desc"- if (endpoint_config.fan_out_over_repos or endpoint_config.fan_out_over_pull_requests)- else "asc",+ sort_mode="desc" if (endpoint_config.fan_out_over_repos or endpoint_config.fan_out is not None) else "asc",partition_count=1,partition_size=1,partition_mode="datetime" if endpoint_config.partition_key else None,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/canonical_descriptions.pyindex 11a34027a5f1..28f754cab1a4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/canonical_descriptions.py@@ -142,6 +142,64 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"pullrequest": "The pull request the comment was made on.",},},+ "pipeline_steps": {+ "description": "A single step of a Bitbucket Pipelines run, with its own state and timings. Pipelines record only the run as a whole, so this is where per-step CI duration and outcome live.",+ "docs_url": "https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pipelines/#api-repositories-workspace-repo-slug-pipelines-pipeline-uuid-steps-get",+ "columns": {+ "uuid": "The step's identifier (a braced UUID), unique within its pipeline.",+ "pipeline_uuid": "UUID of the pipeline run the step belongs to (injected by PostHog; part of the primary key).",+ "pipeline_created_on": "When the parent pipeline run was created (injected by PostHog; the incremental cursor and partition key).",+ "repository_uuid": "UUID of the repository the step ran in (injected by PostHog; part of the primary key).",+ "repository_slug": "Slug of the repository the step ran in (injected by PostHog).",+ "repository_full_name": "workspace/repo of the repository the step ran in (injected by PostHog).",+ "name": "The step name from bitbucket-pipelines.yml, when one is set.",+ "state": "The step state object, including its name (e.g. PENDING, IN_PROGRESS, COMPLETED) and result.",+ "started_on": "When the step started running. Not set while the step is still queued.",+ "completed_on": "When the step finished. Not set while the step is still running.",+ "duration_in_seconds": "Wall-clock duration of the step in seconds.",+ "build_seconds_used": "Build time consumed by the step, in seconds.",+ "image": "The Docker image used as the build container for the step. PostHog removes the private registry password before syncing.",+ "setup_commands": "The commands run during the step's setup phase, outside the build container.",+ "script_commands": "The build commands run inside the build container.",+ "trigger": "What started the step (automatic or manual).",+ "max_time": "The step's configured timeout in minutes.",+ "run_number": "The step's run number, which increments when a step is re-run.",+ },+ },+ "commit_statuses": {+ "description": "An external build or check result reported against a commit, such as a CI job posting success or failure. Each status is addressed by its commit and key.",+ "docs_url": "https://developer.atlassian.com/cloud/bitbucket/rest/api-group-commit-statuses/#api-repositories-workspace-repo-slug-commit-commit-statuses-get",+ "columns": {+ "key": "The status key, unique per commit and vendor (e.g. BB-DEPLOY). Part of the primary key.",+ "commit_hash": "Hash of the commit the status was reported against (injected by PostHog; part of the primary key).",+ "commit_date": "Date of the commit the status was reported against (injected by PostHog; the incremental cursor and partition key).",+ "repository_uuid": "UUID of the repository the commit belongs to (injected by PostHog; part of the primary key).",+ "repository_slug": "Slug of the repository the commit belongs to (injected by PostHog).",+ "repository_full_name": "workspace/repo of the repository the commit belongs to (injected by PostHog).",+ "state": "The reported state: SUCCESSFUL, FAILED, INPROGRESS, or STOPPED.",+ "name": "An identifier for the build itself, e.g. BB-DEPLOY-1.",+ "description": "A description of the build, e.g. 'Unit tests in Bamboo'.",+ "refname": "The ref that pointed at the commit when the status was created. May be unset, and the ref may since have moved.",+ "url": "A link back to the build system that produced the status.",+ "type": "The status type. Build is the only supported type today.",+ "created_on": "When the status was first reported.",+ "updated_on": "When the status was last updated.",+ },+ },+ "branches": {+ "description": "A branch in a repository. Pull requests, pipelines and deployments refer to branches by name.",+ "docs_url": "https://developer.atlassian.com/cloud/bitbucket/rest/api-group-refs/#api-repositories-workspace-repo-slug-refs-branches-get",+ "columns": {+ "name": "The branch name, unique within its repository. Part of the primary key.",+ "repository_uuid": "UUID of the repository the branch belongs to (injected by PostHog; part of the primary key).",+ "repository_slug": "Slug of the repository the branch belongs to (injected by PostHog).",+ "repository_full_name": "workspace/repo of the repository the branch belongs to (injected by PostHog).",+ "target": "The commit the branch currently points at, including its hash, date, author and message.",+ "merge_strategies": "The merge strategies available for pull requests targeting this branch.",+ "default_merge_strategy": "The default merge strategy for pull requests targeting this branch.",+ "type": "The ref type, always 'branch' for this table.",+ },+ },"environments": {"description": "A deployment environment configured on a repository. Deployments refer to these environments.","docs_url": "https://developer.atlassian.com/cloud/bitbucket/rest/api-group-deployments/#api-repositories-workspace-repo-slug-environments-get",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/settings.pyindex 29c7269918a5..1fc9dfdc9fd4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/settings.py@@ -19,6 +19,33 @@ _UPDATED_ON_CREATED_ON: list[IncrementalField] = []+@dataclass(frozen=True)+class SecondLevelFanOut:+ """Describes a child endpoint that is fetched once per row of a parent endpoint, which is+ itself walked once per repository in the workspace."""++ # Key in BITBUCKET_ENDPOINTS whose path is walked per repository to produce the parents.+ parent: str+ # Placeholder in the child's path, and the parent field whose value fills it.+ path_param: str+ id_field: str+ # How the parent list is ordered, and the parent field carrying that ordering value.+ # Resuming skips parents the previous attempt already walked past, and an incremental+ # sync stops the walk once the ordering value crosses the watermark.+ order: str # "id_asc" or "datetime_desc"+ order_field: str+ # Parent walk request shaping: the `sort` value, and the BBQL field for a server-side+ # bound (None when the parent endpoint ignores `q` and the bound is applied client-side).+ parent_sort: Optional[str] = None+ parent_filter_field: Optional[str] = None+ # Parent fields copied onto every child row, as {child column: parent field}. Child rows+ # usually carry no reference back to their parent, and the primary key needs one.+ inject: dict[str, str] = field(default_factory=dict)+ # One request per parent, so an unbounded first sync of a long-lived repository would+ # outlast any rate budget. Later syncs are bounded by the watermark instead.+ max_parents_per_repo: Optional[int] = None++@dataclass(frozen=True)class BitbucketEndpointConfig:name: str@@ -33,9 +60,9 @@ class BitbucketEndpointConfig:# Fan-out: fetched once per repository in the workspace, with {repo_slug}# substituted into the path and repository context injected into each row.fan_out_over_repos: bool = False- # Two-level fan-out: for every repository, walk its pull requests and fetch this- # path once per pull request, with {pull_request_id} substituted into the path.- fan_out_over_pull_requests: bool = False+ # Two-level fan-out: for every repository, walk a parent endpoint and fetch this path+ # once per parent row. None for top-level and single-level fan-out endpoints.+ fan_out: Optional[SecondLevelFanOut] = None# BBQL field for a server-side incremental filter (`q=<field> > "<ts>"`), verified# to actually filter (a future-date probe returns 0 rows). None = the endpoint# silently ignores `q` (commits, pipelines); incremental sync instead scrolls@@ -175,11 +202,100 @@ BITBUCKET_ENDPOINTS: dict[str, BitbucketEndpointConfig] = {default_incremental_field="updated_on",server_filter_field="updated_on",sort_param="updated_on",- fan_out_over_pull_requests=True,+ fan_out=SecondLevelFanOut(+ parent="pull_requests",+ path_param="pull_request_id",+ id_field="id",+ # Sorted on the immutable created_on so ids arrive ascending, which is what lets+ # the resume bookmark skip every pull request below it.+ order="id_asc",+ order_field="id",+ parent_sort="created_on",+ # Posting, editing or deleting a comment bumps its pull request's updated_on, so+ # the server-side bound narrows the walk without missing a changed comment.+ parent_filter_field="updated_on",+ ),# Comment ids look globally sequential, but the docs only scope them to their# pull request, so the parents complete the key.primary_keys=["repository_uuid", "pull_request_id", "id"],),+ "pipeline_steps": BitbucketEndpointConfig(+ name="pipeline_steps",+ path="/repositories/{workspace}/{repo_slug}/pipelines/{pipeline_uuid}/steps/",+ # A step carries started_on and completed_on, but both are unset until the step runs,+ # so neither can act as a cursor. The parent pipeline's immutable created_on is+ # injected instead, which is also what bounds the pipeline walk.+ partition_key="pipeline_created_on",+ incremental_fields=[+ {+ "label": "pipeline_created_on",+ "type": IncrementalFieldType.DateTime,+ "field": "pipeline_created_on",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ default_incremental_field="pipeline_created_on",+ fan_out=SecondLevelFanOut(+ parent="pipelines",+ path_param="pipeline_uuid",+ id_field="uuid",+ order="datetime_desc",+ order_field="created_on",+ parent_sort="-created_on",+ inject={"pipeline_uuid": "uuid", "pipeline_created_on": "created_on"},+ max_parents_per_repo=2000,+ ),+ # Step uuids are real UUIDs, but the docs only scope them to their pipeline.+ primary_keys=["repository_uuid", "pipeline_uuid", "uuid"],+ ),+ "commit_statuses": BitbucketEndpointConfig(+ name="commit_statuses",+ path="/repositories/{workspace}/{repo_slug}/commit/{commit}/statuses",+ # A status has its own created_on, but nothing on the commit changes when one is+ # posted, so the only bound available for the commit walk is the commit's own date.+ # A status attached to a commit older than the watermark is therefore missed — the+ # same trade-off the commits endpoint already makes.+ partition_key="commit_date",+ incremental_fields=[+ {+ "label": "commit_date",+ "type": IncrementalFieldType.DateTime,+ "field": "commit_date",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ default_incremental_field="commit_date",+ fan_out=SecondLevelFanOut(+ parent="commits",+ path_param="commit",+ id_field="hash",+ order="datetime_desc",+ order_field="date",+ inject={"commit_hash": "hash", "commit_date": "date"},+ max_parents_per_repo=2000,+ ),+ # One request per commit is far more than the other tables cost, so this one is+ # opt-in rather than selected by default.+ should_sync_default=False,+ # Statuses carry no id. Bitbucket addresses one by commit and key+ # (PUT .../commit/{hash}/statuses/build/{key}), so that pair identifies a status.+ primary_keys=["repository_uuid", "commit_hash", "key"],+ ),+ "branches": BitbucketEndpointConfig(+ name="branches",+ path="/repositories/{workspace}/{repo_slug}/refs/branches",+ # A branch has no timestamps of its own; target.date is the tip commit's date and+ # moves on every push, so it is neither a cursor nor a partition key. Full refresh,+ # over a list bounded by the branch count per repository.+ incremental_fields=[],+ # An explicit sort keeps pages from shifting under the paginator when a branch is+ # created or deleted mid-walk.+ sort_param="name",+ fan_out_over_repos=True,+ # Branch names are unique within a repository, and are what pull requests,+ # pipelines and deployments reference.+ primary_keys=["repository_uuid", "name"],+ ),"environments": BitbucketEndpointConfig(name="environments",path="/repositories/{workspace}/{repo_slug}/environments",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/tests/test_bitbucket.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/tests/test_bitbucket.pyindex 3627a86cb3d5..29d10d2382bc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/tests/test_bitbucket.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/tests/test_bitbucket.py@@ -1,3 +1,4 @@+import dataclassesfrom datetime import UTC, datetimefrom typing import Anyfrom urllib.parse import parse_qsl, urlsplit@@ -14,8 +15,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket._as_utc_datetime,_build_initial_params,_increment_page_url,+ _iter_fan_out_parents,_normalize_activity_row,_page_predates_cutoff,+ _parent_precedes_bookmark,bitbucket_source,get_rows,validate_credentials,@@ -80,6 +83,12 @@ def _requested_urls(session: mock.Mock) -> list[str]:("projects", True, CUTOFF, "updated_on", 'updated_on > "2024-06-01T00:00:00+00:00"', "updated_on"),# PR comments filter server-side on the child request("pull_request_comments", True, CUTOFF, "updated_on", 'updated_on > "2024-06-01T00:00:00+00:00"', "updated_on"),+ # The step and status child requests take no filter of their own; the watermark bounds+ # their parent walk instead+ ("pipeline_steps", True, CUTOFF, "pipeline_created_on", None, None),+ ("commit_statuses", True, CUTOFF, "commit_date", None, None),+ # Branches are full refresh, but still sort explicitly so pages can't shift mid-walk+ ("branches", False, None, None, None, "name"),# The activity feed ignores both, so neither param is sent("pull_request_activity", True, CUTOFF, "activity_date", None, None),# Environments have no cursor at all@@ -381,6 +390,9 @@ def test_validate_credentials_status_mapping(status, expected_valid, expected_me"activity_date",),("pull_request_comments", ["repository_uuid", "pull_request_id", "id"], "desc", "created_on"),+ ("pipeline_steps", ["repository_uuid", "pipeline_uuid", "uuid"], "desc", "pipeline_created_on"),+ ("commit_statuses", ["repository_uuid", "commit_hash", "key"], "desc", "commit_date"),+ ("branches", ["repository_uuid", "name"], "desc", None),],)def test_source_response_shape(endpoint, expected_primary_keys, expected_sort_mode, expected_partition_key):@@ -532,7 +544,10 @@ def test_pull_request_fan_out_bounds_the_parent_walk(should_use_incremental, lasdef test_pull_request_fan_out_resumes_past_already_synced_pull_requests():manager = _manager(BitbucketResumeConfig(- next_url="https://api.bitbucket.org/2.0/comments-page-2", repo_slug="repo-b", pull_request_id=12+ next_url="https://api.bitbucket.org/2.0/comments-page-2",+ repo_slug="repo-b",+ parent_id="12",+ parent_cursor="12",))session = _session_returning(@@ -553,6 +568,34 @@ def test_pull_request_fan_out_resumes_past_already_synced_pull_requests():assert [row["id"] for batch in batches for row in batch] == [502, 503]+def test_pipeline_steps_drop_the_private_registry_password():+ # A step pulling from a private registry carries the registry password in `image`;+ # syncing it would hand the credential to anyone with warehouse query access+ session = _session_returning(+ _response({"values": [REPO_PAGE["values"][0]]}),+ _response({"values": [{"uuid": "{p1}", "created_on": "2024-07-01T00:00:00Z"}], "page": 1}),+ _response(+ {+ "values": [+ {"uuid": "{s1}", "image": {"name": "acme/build", "username": "ci", "password": "hunter2"}},+ {"uuid": "{s2}", "image": {"name": "python:3.12"}},+ {"uuid": "{s3}"},+ ]+ }+ ),+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", "pipeline_steps", mock.Mock(), _manager()))++ rows = [row for batch in batches for row in batch]+ assert [row.get("image") for row in rows] == [+ {"name": "acme/build", "username": "ci"},+ {"name": "python:3.12"},+ None,+ ]++def test_pull_request_comments_drops_unpublished_drafts():# `pending` comments are the connector identity's own unpublished drafts; the API has no# server-side filter for them, so syncing them would expose one person's drafts@@ -607,6 +650,155 @@ def test_pull_request_fan_out_skips_repo_when_the_pull_request_listing_404s():assert [row["id"] for batch in batches for row in batch] == [601]+ "order,value,bookmark,expected",+ [+ # Pull requests are walked oldest-first by id, so anything below the bookmark is done+ ("id_asc", 11, "12", True),+ ("id_asc", 12, "12", False),+ ("id_asc", 13, "12", False),+ # Pipelines and commits are walked newest-first, so anything newer is done+ ("datetime_desc", "2024-07-01T00:00:00+00:00", "2024-06-01T00:00:00+00:00", True),+ ("datetime_desc", "2024-05-01T00:00:00+00:00", "2024-06-01T00:00:00+00:00", False),+ # A parent we cannot place must be re-walked, never skipped+ ("id_asc", None, "12", False),+ ("datetime_desc", None, "2024-06-01T00:00:00+00:00", False),+ ("datetime_desc", "not a date", "2024-06-01T00:00:00+00:00", False),+ ],+)+def test_parent_precedes_bookmark(order, value, bookmark, expected):+ assert _parent_precedes_bookmark(order, value, bookmark) is expected+++def test_fan_out_parent_walk_stops_at_the_cap_and_warns():+ # One request per parent, so an uncapped first sync of a long-lived repo would outlast+ # any rate budget. Truncating silently would be worse than the cost, hence the warning.+ pipeline_steps_fan_out = BITBUCKET_ENDPOINTS["pipeline_steps"].fan_out+ assert pipeline_steps_fan_out is not None+ fan_out = dataclasses.replace(pipeline_steps_fan_out, max_parents_per_repo=2)+ page = {+ "values": [{"uuid": "{p1}"}, {"uuid": "{p2}"}, {"uuid": "{p3}"}],+ "next": "https://api.bitbucket.org/2.0/repositories/ws/repo-a/pipelines/?page=2",+ "page": 1,+ }+ session = _session_returning(_response(page))+ logger = mock.Mock()++ parents = list(_iter_fan_out_parents(session, fan_out, "ws", "repo-a", logger, None))++ assert [parent["uuid"] for parent in parents] == ["{p1}", "{p2}"]+ logger.warning.assert_called_once()+++ "endpoint,parent,expected_path,expected_injected",+ [+ # Pipeline uuids are braced, which is not path-safe+ (+ "pipeline_steps",+ {"uuid": "{p1}", "created_on": "2024-07-01T00:00:00Z"},+ "/pipelines/%7Bp1%7D/steps/",+ {"pipeline_uuid": "{p1}", "pipeline_created_on": "2024-07-01T00:00:00Z"},+ ),+ (+ "commit_statuses",+ {"hash": "abc123", "date": "2024-07-01T00:00:00+00:00"},+ "/commit/abc123/statuses",+ {"commit_hash": "abc123", "commit_date": "2024-07-01T00:00:00+00:00"},+ ),+ ],+)+def test_second_level_fan_out_injects_the_parent_the_child_row_cannot_name(+ endpoint, parent, expected_path, expected_injected+):+ # Neither a step nor a status carries a reference back to its parent, and both the+ # primary key and the partition key read only the injected columns+ session = _session_returning(+ _response({"values": [REPO_PAGE["values"][0]]}), # repo enumeration+ _response({"values": [parent], "page": 1}),+ _response({"values": [{"uuid": "{s1}", "key": "BB-DEPLOY"}]}),+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", endpoint, mock.Mock(), _manager()))++ assert expected_path in _requested_urls(session)[2]+ row = batches[0][0]+ assert {column: row[column] for column in expected_injected} == expected_injected+ assert row["repository_uuid"] == "{uuid-a}"+++def test_pipeline_steps_incremental_stops_the_pipeline_walk_at_the_watermark():+ # Pipelines ignore `q`, so the watermark has to stop the parent walk client-side. Without+ # it every sync would fetch the steps of every pipeline that ever ran.+ fresh = {+ "values": [{"uuid": "{p1}", "created_on": "2024-07-01T00:00:00Z"}],+ "next": "https://api.bitbucket.org/2.0/repositories/ws/repo-a/pipelines/?page=2",+ "page": 1,+ }+ stale = {"values": [{"uuid": "{p2}", "created_on": "2023-01-01T00:00:00Z"}], "page": 2}+ session = _session_returning(+ _response({"values": [REPO_PAGE["values"][0]]}),+ _response(fresh),+ _response({"values": [{"uuid": "{s1}"}]}), # steps of {p1}+ _response(stale),+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(+ get_rows(+ BitbucketAuth(),+ "ws",+ "pipeline_steps",+ mock.Mock(),+ _manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=CUTOFF,+ incremental_field="pipeline_created_on",+ )+ )++ assert [row["pipeline_uuid"] for batch in batches for row in batch] == ["{p1}"]+ # The stale pipeline page was fetched to discover it was stale, but its steps never were+ assert len(_requested_urls(session)) == 4+++def test_second_level_fan_out_resumes_past_already_walked_parents():+ manager = _manager(+ BitbucketResumeConfig(+ next_url="https://api.bitbucket.org/2.0/steps-page-2",+ repo_slug="repo-b",+ parent_id="{p2}",+ parent_cursor="2024-07-02T00:00:00Z",+ )+ )+ session = _session_returning(+ _response(REPO_PAGE),+ _response(+ {+ "values": [+ {"uuid": "{p1}", "created_on": "2024-07-03T00:00:00Z"},+ {"uuid": "{p2}", "created_on": "2024-07-02T00:00:00Z"},+ {"uuid": "{p3}", "created_on": "2024-07-01T00:00:00Z"},+ ],+ "page": 1,+ }+ ),+ _response({"values": [{"uuid": "{s2}"}]}), # resumed page of {p2}+ _response({"values": [{"uuid": "{s3}"}]}),+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", "pipeline_steps", mock.Mock(), manager))++ urls = _requested_urls(session)+ # repo-a is skipped, {p1} is newer than the bookmark, and {p2} restarts at its saved URL+ assert urls[1].startswith("https://api.bitbucket.org/2.0/repositories/ws/repo-b/pipelines/?")+ assert urls[2] == "https://api.bitbucket.org/2.0/steps-page-2"+ assert "/pipelines/%7Bp3%7D/steps/" in urls[3]+ assert [row["uuid"] for batch in batches for row in batch] == ["{s2}", "{s3}"]++def test_session_uses_basic_auth_for_api_token_and_bearer_for_access_token():with mock.patch.object(bitbucket, "make_tracked_session", return_value=requests.Session()):basic = bitbucket._make_session(BitbucketAuth(email="[email protected]", api_token="tok"))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/tests/test_bitbucket_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/tests/test_bitbucket_source.pyindex c0be77e26e62..b779f071cf22 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/tests/test_bitbucket_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/tests/test_bitbucket_source.py@@ -2,6 +2,7 @@ import pytestfrom unittest import mockfrom products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket.bitbucket import BitbucketAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket.settings import BITBUCKET_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket.source import BitbucketSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bitbucket import (BitbucketAuthMethodConfig,@@ -56,6 +57,7 @@ def test_connection_host_fields_force_secret_reentry_on_workspace_change():# incremental toggle would silently behave like a full refresh("deployments", False),("workspace_members", False),+ ("branches", False),],)def test_get_schemas_incremental_support(endpoint, supports_incremental):@@ -141,3 +143,11 @@ def test_source_for_pipeline_plumbs_arguments(should_use_incremental, last_valuedb_incremental_field_last_value=expected_last_value,incremental_field="date",)++[email protected]("endpoint", sorted(BITBUCKET_ENDPOINTS))+def test_canonical_descriptions_document_the_primary_key_columns(endpoint):+ # Several key columns are injected by the transport rather than returned by Bitbucket, so+ # the LLM fallback cannot derive them from the vendor docs at all+ columns = BitbucketSource().get_canonical_descriptions()[endpoint]["columns"]+ assert set(BITBUCKET_ENDPOINTS[endpoint].primary_keys) <= set(columns)