: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(bitbucket): sync pr activity, comments, environments and projects (#99812)
Tom Owers6b6ab1efbcef
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 8871ce9a3ebd..36f0e6cedb73 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@@ -809,14 +809,14 @@ Note: BigMailer's public API exposes no per-recipient engagement or event endpoi## Bitbucket — gaps-Today (6): `commits`, `deployments`, `pipelines`, `pull_requests`, `repositories`, `workspace_members`+Today (10): `commits`, `deployments`, `environments`, `pipelines`, `projects`, `pull_request_activity`, `pull_request_comments`, `pull_requests`, `repositories`, `workspace_members`Diffed against: <https://api.bitbucket.org/swagger.json>-- [ ] `repositories/{workspace}/{repo}/pullrequests/{id}/activity` — approval, review and update transition history — the backbone of PR cycle-time analysis (high)-- [ ] `repositories/{workspace}/{repo}/pullrequests/{id}/comments` — code review comment volume and latency (high)-- [ ] `repositories/{workspace}/{repo}/environments` — lookup resolving the environment referenced by the deployments we already sync (high)-- [ ] `workspaces/{workspace}/projects` — lookup grouping the repositories we already sync under a project key (high)+- [x] `repositories/{workspace}/{repo}/pullrequests/{id}/activity` — approval, review and update transition history — the backbone of PR cycle-time analysis (high)+- [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)@@ -826,6 +826,10 @@ Diffed against: <https://api.bitbucket.org/swagger.json>- [ ] `repositories/{workspace}/{repo}/issues/{id}/comments` — issue discussion volume (medium)- [ ] `repositories/{workspace}/{repo}/issues/{id}/changes` — issue state transition history (low)+Note: `pull_request_activity` syncs the repo-level `pullrequests/activity` feed rather than the+per-pull-request path listed above. Both return the same entries; the repo-level feed covers every+pull request in one walk, so it costs one request per page instead of one per pull request.+## Bitrise — gapsToday (4): `apps`, `artifacts`, `builds`, `workflows`diff --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 e0465c9fe681..8dcb2481347d 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@@ -1,5 +1,5 @@import dataclasses-from collections.abc import Iterator+from collections.abc import Callable, Iteratorfrom datetime import UTC, date, datetimefrom typing import Any, Optionalfrom urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit@@ -27,7 +27,7 @@ class BitbucketRetryableError(Exception):pass[email protected](frozen=True)class BitbucketResumeConfig:# Full URL of the next page to fetch. None means "start the current bookmark's list# from its first page" (the URL is built fresh when the loop reaches it).@@ -36,6 +36,10 @@ 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@dataclasses.dataclass(frozen=True)@@ -225,6 +229,58 @@ def _normalize_member_row(row: dict[str, Any]) -> dict[str, Any]:return {**row, "user_uuid": user.get("uuid"), "user_display_name": user.get("display_name")}+# The kinds of entry the v2.0 activity feed returns; each row carries exactly one of them+# alongside the pull request it belongs to.+_ACTIVITY_TYPES = ("comment", "update", "approval", "changes_requested")+++def _normalize_activity_row(row: dict[str, Any]) -> dict[str, Any]:+ """Lift the activity kind, its timestamp and its actor to top-level columns. The entry+ itself is polymorphic and carries no id, so the primary key and the incremental cursor+ have nothing stable to read without this."""+ pull_request = row.get("pull_request") or {}+ activity_type = next((kind for kind in _ACTIVITY_TYPES if kind in row), None)+ detail = (row.get(activity_type) or {}) if activity_type else {}+ # Comments date themselves with created_on; updates and approvals use date. Updates+ # name their actor `author`, the rest `user`.+ actor = detail.get("user") or detail.get("author") or {}+ return {+ **row,+ "pull_request_id": pull_request.get("id"),+ "activity_type": activity_type,+ "activity_date": detail.get("date") or detail.get("created_on"),+ "actor_uuid": actor.get("uuid"),+ "actor_display_name": actor.get("display_name"),+ }+++def _normalize_comment_row(row: dict[str, Any]) -> dict[str, Any]:+ pull_request = row.get("pullrequest") or {}+ user = row.get("user") or {}+ return {**row, "pull_request_id": pull_request.get("id"), "user_uuid": user.get("uuid")}+++_ROW_MAPPERS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {+ "workspace_members": _normalize_member_row,+ "pull_request_activity": _normalize_activity_row,+ "pull_request_comments": _normalize_comment_row,+}++# A pending comment is an unpublished draft that only its author can read, and the API+# returns the connector identity's own drafts. Syncing them would put one person's private+# drafts in front of everyone with warehouse query access, so they are dropped.+_ROW_FILTERS: dict[str, Callable[[dict[str, Any]], bool]] = {+ "pull_request_comments": lambda row: not row.get("pending"),+}+++def _map_rows(endpoint: str, items: list[dict[str, Any]], repo: dict[str, Any] | None) -> list[dict[str, Any]]:+ mapper = _ROW_MAPPERS.get(endpoint)+ row_filter = _ROW_FILTERS.get(endpoint)+ rows = (item for item in items if row_filter is None or row_filter(item))+ return [_normalize_row(mapper(row) if mapper else row, repo) for row in rows]++def _iter_repositories(session: requests.Session, workspace: str, logger: FilteringBoundLogger) -> Iterator[dict[str, Any]]:@@ -267,14 +323,13 @@ def _get_top_level_rows(else:url = _build_url(config.path.format(workspace=workspace), params)- is_members = config.name == "workspace_members"while True:data = _fetch_page(session, url, logger)items = data.get("values", [])next_url = data.get("next")if items:- yield [_normalize_member_row(item) if is_members else item for item in items]+ yield _map_rows(config.name, items, None)# Save AFTER yielding (and only when more pages remain) so a crash re-yields# the last page rather than skipping it — merge dedupes on the primary key.if next_url:@@ -321,13 +376,14 @@ def _get_fan_out_rows(if next_url and config.rebuild_page_urls:next_url = _increment_page_url(url, int(data.get("page") or 1))- if cutoff is not None and cursor_field and _page_predates_cutoff(items, cursor_field, cutoff):+ rows = _map_rows(config.name, items, repo)+ if cutoff is not None and cursor_field and _page_predates_cutoff(rows, cursor_field, cutoff):# Newest-first scroll walked past the watermark: everything from here# back is already synced, so stop without yielding this page.break- if items:- yield [_normalize_row(item, repo) for item in items]+ if rows:+ yield rowsif next_url:resumable_source_manager.save_state(BitbucketResumeConfig(next_url=next_url, repo_slug=repo["slug"])@@ -352,6 +408,131 @@ def _get_fan_out_rows()+def _iter_pull_requests(+ session: requests.Session,+ workspace: str,+ repo_slug: str,+ logger: FilteringBoundLogger,+ since: datetime | None,+) -> 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)}"'))++ url = _build_url(parent.path.format(workspace=workspace, repo_slug=repo_slug), params)+ while True:+ data = _fetch_page(session, url, logger)+ yield from data.get("values", [])+ next_url = data.get("next")+ if not next_url:+ break+ url = next_url+++def _get_pull_request_fan_out_rows(+ session: requests.Session,+ config: BitbucketEndpointConfig,+ 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.++ 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."""+ 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 None+ remaining = repos+ resume_pull_request: int | None = None+ resume_url: str | None = None+ if 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_url = resume.next_url+ logger.debug(+ f"Bitbucket: resuming {config.name} from repo={resume.repo_slug}, "+ f"pull_request={resume_pull_request}, 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_url = resume_url if index == 0 else None++ try:+ 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+ ):+ continue++ if bookmark_url and pull_request_id == bookmark_pull_request:+ url = bookmark_url+ else:+ url = _build_url(+ config.path.format(+ workspace=workspace, repo_slug=repo["slug"], pull_request_id=pull_request_id+ ),+ params,+ )+ bookmark_url = 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)+ if rows:+ yield rows+ resumable_source_manager.save_state(+ BitbucketResumeConfig(+ next_url=next_url, repo_slug=repo["slug"], pull_request_id=pull_request_id+ )+ )++ if not next_url:+ break+ url = next_url+ except 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.+ 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"+ )+ continue+ raise+ except requests.HTTPError as exc:+ # The repository was deleted between enumeration and the pull request walk.+ 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:+ raise++ if index + 1 < len(remaining):+ resumable_source_manager.save_state(+ BitbucketResumeConfig(next_url=None, repo_slug=remaining[index + 1]["slug"])+ )++def get_rows(auth: BitbucketAuth,workspace: str,@@ -370,7 +551,17 @@ def get_rows(config, should_use_incremental_field, db_incremental_field_last_value, incremental_field)- if config.fan_out_over_repos:+ if config.fan_out_over_pull_requests:+ yield from _get_pull_request_fan_out_rows(+ session,+ config,+ workspace,+ resumable_source_manager,+ logger,+ params,+ db_incremental_field_last_value if should_use_incremental_field else None,+ )+ elif config.fan_out_over_repos:cutoff = _client_side_cutoff(config, should_use_incremental_field, db_incremental_field_last_value)cursor_field = incremental_field or config.default_incremental_fieldyield from _get_fan_out_rows(@@ -409,7 +600,9 @@ 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 else "asc",+ sort_mode="desc"+ if (endpoint_config.fan_out_over_repos or endpoint_config.fan_out_over_pull_requests)+ 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 79a8490d1bb1..11a34027a5f1 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@@ -101,6 +101,83 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"step": "The pipeline step that performed the deployment.",},},+ "pull_request_activity": {+ "description": "An entry in the activity log of a pull request: a review comment, an update to the pull request, an approval, or a request for changes.",+ "docs_url": "https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pullrequests/#api-repositories-workspace-repo-slug-pullrequests-activity-get",+ "columns": {+ "repository_uuid": "UUID of the repository the activity belongs to (injected by PostHog; part of the primary key).",+ "repository_slug": "Slug of the repository the activity belongs to (injected by PostHog).",+ "repository_full_name": "workspace/repo of the repository the activity belongs to (injected by PostHog).",+ "pull_request_id": "Numeric id of the pull request the activity belongs to (injected by PostHog; part of the primary key).",+ "activity_type": "What kind of entry this is: comment, update, approval, or changes_requested (injected by PostHog; part of the primary key).",+ "activity_date": "When the entry was recorded (injected by PostHog from the entry's own timestamp; part of the primary key).",+ "actor_uuid": "UUID of the user who made the entry (injected by PostHog).",+ "actor_display_name": "Display name of the user who made the entry (injected by PostHog).",+ "pull_request": "The pull request the entry belongs to, with its id, title and links.",+ "comment": "The comment that was posted, present only on comment entries. Carries the content, the author, and an inline property when the comment is on a file or a line of code.",+ "update": "The change made to the pull request, present only on update entries. Carries the new state, title, description, reviewers, source and destination.",+ "approval": "The approval that was given, present only on approval entries. Carries the approving user and the date.",+ "changes_requested": "The request for changes, present only on changes_requested entries. Carries the requesting user and the date.",+ },+ },+ "pull_request_comments": {+ "description": "A comment on a pull request, including global comments, inline comments on a file or line of code, and replies.",+ "docs_url": "https://developer.atlassian.com/cloud/bitbucket/rest/api-group-pullrequests/#api-repositories-workspace-repo-slug-pullrequests-pull-request-id-comments-get",+ "columns": {+ "id": "The comment's numeric id (part of the primary key).",+ "repository_uuid": "UUID of the repository the comment belongs to (injected by PostHog; part of the primary key).",+ "repository_slug": "Slug of the repository the comment belongs to (injected by PostHog).",+ "repository_full_name": "workspace/repo of the repository the comment belongs to (injected by PostHog).",+ "pull_request_id": "Numeric id of the pull request the comment belongs to (injected by PostHog; part of the primary key).",+ "user_uuid": "UUID of the comment's author (injected by PostHog from the nested user object).",+ "content": "The comment body, in raw, markup and rendered HTML form.",+ "user": "The account that wrote the comment.",+ "created_on": "When the comment was posted.",+ "updated_on": "When the comment was last edited.",+ "deleted": "Whether the comment has been deleted.",+ "pending": "Always false. PostHog does not sync unpublished draft comments.",+ "inline": "Set when the comment is on a file or a line of code; carries the path and the from/to line numbers.",+ "parent": "The comment this one replies to, for replies in a comment thread.",+ "resolution": "Who resolved the comment thread and when, if it has been resolved.",+ "pullrequest": "The pull request the comment was made on.",+ },+ },+ "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",+ "columns": {+ "uuid": "The environment's globally unique identifier (a braced UUID; primary key).",+ "repository_uuid": "UUID of the repository the environment is configured on (injected by PostHog).",+ "repository_slug": "Slug of the repository the environment is configured on (injected by PostHog).",+ "repository_full_name": "workspace/repo of the repository the environment is configured on (injected by PostHog).",+ "name": "The name of the environment.",+ "slug": "The URL-safe environment slug.",+ "category": "The category the environment is grouped under, when one is set.",+ "environment_type": "The environment type: Test, Staging, or Production.",+ "rank": "The environment's position in the repository's deployment sequence.",+ "hidden": "Whether the environment is hidden from the deployments view.",+ "lock": "The environment's current deployment lock.",+ "restrictions": "Deployment restrictions on the environment, such as admin-only deploys.",+ "deployment_gate_enabled": "Whether a deployment gate must pass before deploying.",+ "environment_lock_enabled": "Whether the environment locks while a deployment runs.",+ },+ },+ "projects": {+ "description": "A project in the workspace. Projects group repositories under a project key.",+ "docs_url": "https://developer.atlassian.com/cloud/bitbucket/rest/api-group-workspaces/#api-workspaces-workspace-projects-get",+ "columns": {+ "uuid": "The project's immutable, globally unique identifier (a braced UUID).",+ "key": "The project key, used as the prefix that groups the project's repositories.",+ "name": "The display name of the project.",+ "description": "The project description.",+ "is_private": "Whether the project is private to the workspace.",+ "has_publicly_visible_repos": "Whether the project contains publicly visible repositories.",+ "created_on": "When the project was created.",+ "updated_on": "When the project was last updated.",+ "owner": "The workspace that owns the project.",+ "workspace": "The workspace the project belongs to.",+ },+ },"workspace_members": {"description": "A user's membership in the Bitbucket Cloud workspace.","docs_url": "https://developer.atlassian.com/cloud/bitbucket/rest/api-group-workspaces/#api-workspaces-workspace-members-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 4f61c161de5a..29c7269918a5 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,7 +19,7 @@ _UPDATED_ON_CREATED_ON: list[IncrementalField] = []-@dataclass+@dataclass(frozen=True)class BitbucketEndpointConfig:name: strpath: str # Path template with {workspace} and, for fan-out endpoints, {repo_slug}@@ -33,6 +33,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# 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@@ -137,6 +140,65 @@ BITBUCKET_ENDPOINTS: dict[str, BitbucketEndpointConfig] = {fan_out_over_repos=True,primary_keys=["uuid"],),+ "pull_request_activity": BitbucketEndpointConfig(+ name="pull_request_activity",+ # The repo-level feed carries the activity of every pull request in the repo, so+ # one walk per repo replaces a walk per pull request.+ path="/repositories/{workspace}/{repo_slug}/pullrequests/activity",+ partition_key="activity_date",+ # Entries are polymorphic (comment / update / approval / changes_requested), each+ # carrying its own timestamp, so the transport lifts one to `activity_date`. The+ # endpoint ignores both `q` and `sort` but returns newest-first, so incremental+ # sync scrolls from the newest entry and stops once a whole page predates the+ # watermark, like commits and pipelines.+ incremental_fields=[+ {+ "label": "activity_date",+ "type": IncrementalFieldType.DateTime,+ "field": "activity_date",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ default_incremental_field="activity_date",+ page_size=50, # the activity feed rejects pagelen > 50+ fan_out_over_repos=True,+ # Activity entries have no id of their own. A pull request cannot record two+ # entries of the same kind at the same microsecond, so the kind and timestamp+ # complete the key.+ primary_keys=["repository_uuid", "pull_request_id", "activity_type", "activity_date"],+ ),+ "pull_request_comments": BitbucketEndpointConfig(+ name="pull_request_comments",+ path="/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/comments",+ partition_key="created_on",+ incremental_fields=_UPDATED_ON_CREATED_ON,+ default_incremental_field="updated_on",+ server_filter_field="updated_on",+ sort_param="updated_on",+ fan_out_over_pull_requests=True,+ # 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"],+ ),+ "environments": BitbucketEndpointConfig(+ name="environments",+ path="/repositories/{workspace}/{repo_slug}/environments",+ # Environments carry no timestamps; full refresh only (a handful per repo).+ incremental_fields=[],+ fan_out_over_repos=True,+ # Environment uuids are real UUIDs, unique across repositories.+ primary_keys=["uuid"],+ ),+ "projects": BitbucketEndpointConfig(+ name="projects",+ path="/workspaces/{workspace}/projects",+ partition_key="created_on",+ incremental_fields=_UPDATED_ON_CREATED_ON,+ default_incremental_field="updated_on",+ server_filter_field="updated_on",+ sort_param="updated_on",+ primary_keys=["uuid"],+ ),"workspace_members": BitbucketEndpointConfig(name="workspace_members",path="/workspaces/{workspace}/members",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/source.pyindex 4f88441ba4f5..999e61cf4878 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bitbucket/source.py@@ -60,7 +60,7 @@ class BitbucketSource(ResumableSource[BitbucketSourceConfig, BitbucketResumeConfkeywords=["atlassian", "git", "ci"],caption="""Connect your Bitbucket Cloud workspace to sync repositories, pull requests, commits, pipelines, and more.-Your credentials need the **repository**, **pullrequest**, **pipeline**, and **account** read scopes. Avoid app passwords — Atlassian is retiring them; use an API token or an access token instead.""",+Your credentials need the **repository**, **pullrequest**, **pipeline**, **project**, and **account** read scopes. Avoid app passwords — Atlassian is retiring them; use an API token or an access token instead.""",iconPath="/static/services/bitbucket.png",docsUrl="https://posthog.com/docs/cdp/sources/bitbucket",fields=cast(@@ -141,7 +141,7 @@ Your credentials need the **repository**, **pullrequest**, **pipeline**, and **adef get_non_retryable_errors(self) -> dict[str, str | None]:return {"401 Client Error: Unauthorized for url: https://api.bitbucket.org": "Your Bitbucket credentials are invalid or have been revoked. Check your email and API token (or access token), then reconnect.",- "403 Client Error: Forbidden for url: https://api.bitbucket.org": "Your Bitbucket token is missing a read scope needed to sync this data. Grant the repository, pullrequest, pipeline, and account read scopes, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.bitbucket.org": "Your Bitbucket token is missing a read scope needed to sync this data. Grant the repository, pullrequest, pipeline, project, and account read scopes, then reconnect.",# Off-origin pagination/resume URL rejected by the transport's origin pin —# deterministic until the bad resume state expires, so don't retry into it."Refusing to fetch non-Bitbucket URL": "Bitbucket returned an unexpected pagination URL. Please retry the sync; if the problem persists, contact support.",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 e6f23a9392fc..3627a86cb3d5 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@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bitbucket._as_utc_datetime,_build_initial_params,_increment_page_url,+ _normalize_activity_row,_page_predates_cutoff,bitbucket_source,get_rows,@@ -75,6 +76,14 @@ def _requested_urls(session: mock.Mock) -> list[str]:("pipelines", True, CUTOFF, "created_on", None, "-created_on"),# Commits have neither filter nor sort("commits", True, CUTOFF, "date", None, None),+ # Projects filter and sort server-side, like repositories+ ("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 activity feed ignores both, so neither param is sent+ ("pull_request_activity", True, CUTOFF, "activity_date", None, None),+ # Environments have no cursor at all+ ("environments", False, None, None, None, None),],)def test_build_initial_params_incremental_behavior(@@ -363,6 +372,15 @@ def test_validate_credentials_status_mapping(status, expected_valid, expected_me("pipelines", ["uuid"], "desc", "created_on"),("deployments", ["uuid"], "desc", None),("workspace_members", ["user_uuid"], "asc", None),+ ("projects", ["uuid"], "asc", "created_on"),+ ("environments", ["uuid"], "desc", None),+ (+ "pull_request_activity",+ ["repository_uuid", "pull_request_id", "activity_type", "activity_date"],+ "desc",+ "activity_date",+ ),+ ("pull_request_comments", ["repository_uuid", "pull_request_id", "id"], "desc", "created_on"),],)def test_source_response_shape(endpoint, expected_primary_keys, expected_sort_mode, expected_partition_key):@@ -377,6 +395,218 @@ def test_source_response_shape(endpoint, expected_primary_keys, expected_sort_moassert response.partition_mode == "datetime"+ "entry,expected_type,expected_date,expected_actor",+ [+ (+ {"comment": {"created_on": "2024-07-01T00:00:00+00:00", "user": {"uuid": "{u1}"}}},+ "comment",+ "2024-07-01T00:00:00+00:00",+ "{u1}",+ ),+ # Updates date themselves with `date` and name the actor `author`, not `user`+ (+ {"update": {"date": "2024-07-02T00:00:00+00:00", "author": {"uuid": "{u2}"}}},+ "update",+ "2024-07-02T00:00:00+00:00",+ "{u2}",+ ),+ (+ {"approval": {"date": "2024-07-03T00:00:00+00:00", "user": {"uuid": "{u3}"}}},+ "approval",+ "2024-07-03T00:00:00+00:00",+ "{u3}",+ ),+ (+ {"changes_requested": {"date": "2024-07-04T00:00:00+00:00", "user": {"uuid": "{u4}"}}},+ "changes_requested",+ "2024-07-04T00:00:00+00:00",+ "{u4}",+ ),+ # An entry kind we don't know about must still produce a row rather than raise+ ({"task": {"date": "2024-07-05T00:00:00+00:00"}}, None, None, None),+ ],+)+def test_normalize_activity_row_lifts_type_date_and_actor(entry, expected_type, expected_date, expected_actor):+ # Activity entries are polymorphic and carry no id; the primary key and the incremental+ # cursor read only these lifted columns+ row = _normalize_activity_row({"pull_request": {"id": 42}, **entry})++ assert row["pull_request_id"] == 42+ assert row["activity_type"] == expected_type+ assert row["activity_date"] == expected_date+ assert row["actor_uuid"] == expected_actor+++def test_activity_incremental_stops_at_watermark_on_the_lifted_date():+ # The cutoff has to be applied after the rows are normalized, because the raw entries have no+ # top-level timestamp, so checking them would never stop the newest-first scroll+ fresh = {+ "values": [{"pull_request": {"id": 1}, "approval": {"date": "2024-07-01T00:00:00+00:00"}}],+ "next": "https://api.bitbucket.org/2.0/repositories/ws/repo-a/pullrequests/activity?ctx=p2",+ }+ stale = {+ "values": [{"pull_request": {"id": 2}, "approval": {"date": "2023-01-01T00:00:00+00:00"}}],+ "next": "https://api.bitbucket.org/2.0/repositories/ws/repo-a/pullrequests/activity?ctx=p3",+ }+ session = _session_returning(+ _response({"values": [REPO_PAGE["values"][0]]}),+ _response(fresh),+ _response(stale),+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(+ get_rows(+ BitbucketAuth(),+ "ws",+ "pull_request_activity",+ mock.Mock(),+ _manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=CUTOFF,+ )+ )++ assert [[row["pull_request_id"] for row in batch] for batch in batches] == [[1]]+ # The stale page was fetched to discover it was stale, but page 3 never was+ assert len(_requested_urls(session)) == 3+++def test_pull_request_fan_out_walks_every_pull_request_and_injects_context():+ session = _session_returning(+ _response({"values": [REPO_PAGE["values"][0]]}), # repo enumeration+ _response({"values": [{"id": 11}, {"id": 12}]}), # repo-a pull requests+ _response({"values": [{"id": 501, "pullrequest": {"id": 11}, "user": {"uuid": "{u1}"}}]}),+ _response({"values": [{"id": 502, "pullrequest": {"id": 12}, "user": {"uuid": "{u2}"}}]}),+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", "pull_request_comments", mock.Mock(), _manager()))++ urls = _requested_urls(session)+ assert "/repositories/ws/repo-a/pullrequests/11/comments" in urls[2]+ assert "/repositories/ws/repo-a/pullrequests/12/comments" in urls[3]+ rows = [row for batch in batches for row in batch]+ assert [(row["id"], row["pull_request_id"], row["repository_uuid"], row["user_uuid"]) for row in rows] == [+ (501, 11, "{uuid-a}", "{u1}"),+ (502, 12, "{uuid-a}", "{u2}"),+ ]+++ "should_use_incremental,last_value,expected_q",+ [+ # An unbounded parent walk would issue one request per pull request that ever+ # existed on every sync+ (True, CUTOFF, 'updated_on > "2024-06-01T00:00:00+00:00"'),+ (True, None, None),+ (False, CUTOFF, None),+ ],+)+def test_pull_request_fan_out_bounds_the_parent_walk(should_use_incremental, last_value, expected_q):+ session = _session_returning(+ _response({"values": [REPO_PAGE["values"][0]]}),+ _response({"values": []}),+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ list(+ get_rows(+ BitbucketAuth(),+ "ws",+ "pull_request_comments",+ mock.Mock(),+ _manager(),+ should_use_incremental_field=should_use_incremental,+ db_incremental_field_last_value=last_value,+ )+ )++ parent_query = dict(parse_qsl(urlsplit(_requested_urls(session)[1]).query))+ assert parent_query.get("q") == expected_q+ # Sorted on the immutable created_on so ids arrive ascending for the resume bookmark+ assert parent_query["sort"] == "created_on"+++def 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+ )+ )+ session = _session_returning(+ _response(REPO_PAGE),+ _response({"values": [{"id": 11}, {"id": 12}, {"id": 13}]}), # repo-b pull requests+ _response({"values": [{"id": 502, "pullrequest": {"id": 12}}]}), # resumed page of PR 12+ _response({"values": [{"id": 503, "pullrequest": {"id": 13}}]}),+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", "pull_request_comments", mock.Mock(), manager))++ urls = _requested_urls(session)+ # repo-a is skipped, PR 11 is below the bookmark, and PR 12 restarts at its saved URL+ assert urls[1].startswith("https://api.bitbucket.org/2.0/repositories/ws/repo-b/pullrequests?")+ assert urls[2] == "https://api.bitbucket.org/2.0/comments-page-2"+ assert "/pullrequests/13/comments" in urls[3]+ assert [row["id"] for batch in batches for row in batch] == [502, 503]+++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+ session = _session_returning(+ _response({"values": [REPO_PAGE["values"][0]]}),+ _response({"values": [{"id": 11}]}),+ _response(+ {+ "values": [+ {"id": 501, "pullrequest": {"id": 11}, "pending": True},+ {"id": 502, "pullrequest": {"id": 11}, "pending": False},+ {"id": 503, "pullrequest": {"id": 11}},+ ]+ }+ ),+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", "pull_request_comments", mock.Mock(), _manager()))++ assert [row["id"] for batch in batches for row in batch] == [502, 503]+++def test_pull_request_fan_out_skips_a_deleted_pull_request_without_dropping_the_repo():+ session = _session_returning(+ _response(REPO_PAGE),+ _response({"values": [{"id": 11}, {"id": 12}]}), # repo-a pull requests+ _response({}, status=404), # PR 11 deleted between the listing and the fetch+ _response({"values": [{"id": 502, "pullrequest": {"id": 12}}]}),+ _response({"values": [{"id": 21}]}), # repo-b pull requests+ _response({"values": [{"id": 601, "pullrequest": {"id": 21}}]}),+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", "pull_request_comments", mock.Mock(), _manager()))++ # PR 12 and repo-b still sync; only the deleted pull request is skipped+ assert [row["id"] for batch in batches for row in batch] == [502, 601]+++def test_pull_request_fan_out_skips_repo_when_the_pull_request_listing_404s():+ session = _session_returning(+ _response(REPO_PAGE),+ _response({}, status=404), # repo-a deleted between enumeration and the walk+ _response({"values": [{"id": 21}]}), # repo-b pull requests+ _response({"values": [{"id": 601, "pullrequest": {"id": 21}}]}),+ )++ with mock.patch.object(bitbucket, "_make_session", return_value=session):+ batches = list(get_rows(BitbucketAuth(), "ws", "pull_request_comments", mock.Mock(), _manager()))++ assert [row["id"] for batch in batches for row in batch] == [601]++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"))