:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement azure devops import source (#62918)
Tom Owersaf91b52f50e3
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 60403ee5190c..68ad8b217b3a 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -49,6 +49,7 @@ the row lists both.| asana | HTTP | requests | ✅ || ashby | HTTP | requests | ✅ || attio | HTTP | requests + `rest_source.RESTClient` | ✅ |+| azure_devops | HTTP | requests | ✅ || bamboohr | HTTP | requests | ✅ || bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) || bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |@@ -213,7 +214,6 @@ doesn't conflict with concurrent PRs.- attentive- auth0- azure_blob-- azure_devops- bigcommerce- box- braintreediff --git a/posthog/temporal/data_imports/sources/azure_devops/azure_devops.py b/posthog/temporal/data_imports/sources/azure_devops/azure_devops.pynew file mode 100644index 000000000000..171c5bc9d6da--- /dev/null+++ b/posthog/temporal/data_imports/sources/azure_devops/azure_devops.py@@ -0,0 +1,264 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import quote, urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.azure_devops.settings import AZURE_DEVOPS_ENDPOINTS+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++AZURE_DEVOPS_BASE_URL = "https://dev.azure.com"+API_VERSION = "7.1"+PAGE_SIZE = 200+REQUEST_TIMEOUT_SECONDS = 60+# Rate limiting is 200 TSTUs per identity per sliding 5-minute window; 429s+# carry Retry-After but exponential backoff is sufficient.+MAX_RETRY_ATTEMPTS = 5+++class AzureDevOpsRetryableError(Exception):+ pass+++class AzureDevOpsAuthError(Exception):+ pass+++class AzureDevOpsResumeConfig:+ # Only the org-level work item revisions stream persists resume state —+ # its continuationToken is a purpose-built watermark. Project-fan-out+ # streams restart on retry (merge dedupes on primary keys).+ continuation_token: str+++def _get_session(personal_access_token: str) -> requests.Session:+ session = make_tracked_session(redact_values=(personal_access_token,))+ # PATs go in the Basic-auth password with an empty username.+ session.auth = ("", personal_access_token)+ return session+++def _validate_organization(organization: str) -> str:+ org = organization.strip().removeprefix("https://").removeprefix("http://")+ org = org.removeprefix("dev.azure.com/").split("/")[0]+ if not re.fullmatch(r"[a-zA-Z0-9._-]+", org):+ raise ValueError(f"Invalid Azure DevOps organization: {organization}")+ return org+++def _format_datetime(value: Any) -> str:+ """Format an incremental cursor for Azure DevOps date-time filters (ISO 8601 UTC)."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00Z")+ return str(value)+++def _flatten_revision(item: dict[str, Any]) -> dict[str, Any]:+ # Revision payloads nest everything interesting under `fields`; copy the+ # watermark field to the top level so the pipeline can track it.+ changed = (item.get("fields") or {}).get("System.ChangedDate")+ if changed is not None:+ return {**item, "changed_date": changed}+ return item+++def validate_credentials(organization: str, personal_access_token: str) -> bool:+ """Confirm the PAT and organization are valid with a cheap projects probe.++ Azure DevOps answers an invalid PAT with a 203 + HTML sign-in page rather+ than a 401, so only an exact 200 counts."""+ try:+ org = _validate_organization(organization)+ response = _get_session(personal_access_token).get(+ f"{AZURE_DEVOPS_BASE_URL}/{quote(org)}/_apis/projects?{urlencode({'$top': 1, 'api-version': API_VERSION})}",+ timeout=10,+ )+ return response.status_code == 200+ except Exception:+ return False+++def get_rows(+ organization: str,+ personal_access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AzureDevOpsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = AZURE_DEVOPS_ENDPOINTS[endpoint]+ session = _get_session(personal_access_token)+ org = _validate_organization(organization)++ @retry(+ retry=retry_if_exception_type((AzureDevOpsRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=120),+ reraise=True,+ )+ def fetch(path: str, params: dict[str, Any]) -> requests.Response:+ url = f"{AZURE_DEVOPS_BASE_URL}/{quote(org)}{path}?{urlencode({**params, 'api-version': API_VERSION})}"+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise AzureDevOpsRetryableError(+ f"Azure DevOps API error (retryable): status={response.status_code}, url={url}"+ )++ # An invalid/expired PAT yields a 203 with an HTML sign-in page.+ if response.status_code == 203:+ raise AzureDevOpsAuthError(+ "Azure DevOps returned a sign-in page (203) — the personal access token is invalid or expired."+ )++ if not response.ok:+ logger.error(f"Azure DevOps API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response++ incremental_value = (+ _format_datetime(db_incremental_field_last_value)+ if should_use_incremental_field and db_incremental_field_last_value is not None+ else None+ )++ def base_params() -> dict[str, Any]:+ params: dict[str, Any] = {}+ if config.incremental_param is not None and incremental_value is not None:+ params[config.incremental_param] = incremental_value+ return params++ def iterate_header_token(+ path: str, extra: dict[str, Any], use_base_params: bool = True+ ) -> Iterator[list[dict[str, Any]]]:+ token: Optional[str] = None+ while True:+ params = {**(base_params() if use_base_params else {}), **extra, "$top": PAGE_SIZE}+ if token:+ params["continuationToken"] = token+ response = fetch(path, params)+ items = response.json().get("value", []) or []+ if items:+ yield items+ token = response.headers.get("x-ms-continuationtoken")+ if not token or not items:+ return++ def iterate_skip(path: str, extra: dict[str, Any]) -> Iterator[list[dict[str, Any]]]:+ skip = 0+ while True:+ params = {**base_params(), **extra, "$top": PAGE_SIZE, "$skip": skip}+ response = fetch(path, params)+ items = response.json().get("value", []) or []+ if items:+ yield items+ if len(items) < PAGE_SIZE:+ return+ skip += PAGE_SIZE++ def project_names() -> list[str]:+ # Project enumeration is independent of the data endpoint being synced,+ # so it must not carry that endpoint's incremental filter.+ names: list[str] = []+ for page in iterate_header_token("/_apis/projects", {}, use_base_params=False):+ names.extend(item["name"] for item in page if item.get("name"))+ return names++ if endpoint == "projects":+ yield from iterate_header_token(config.path, {})+ return++ if endpoint == "repositories":+ for project in project_names():+ response = fetch(config.path.replace("{project}", quote(project)), {})+ items = response.json().get("value", []) or []+ if items:+ yield items+ return++ if endpoint == "builds":+ for project in project_names():+ # Ascending queue-time order keeps the incremental watermark monotonic.+ yield from iterate_header_token(+ config.path.replace("{project}", quote(project)), {"queryOrder": "queueTimeAscending"}+ )+ return++ if endpoint == "pull_requests":+ extra = {"searchCriteria.status": "all"}+ if incremental_value is not None:+ extra["searchCriteria.queryTimeRangeType"] = "created"+ for project in project_names():+ yield from iterate_skip(config.path.replace("{project}", quote(project)), extra)+ return++ # work_item_revisions: org-level reporting endpoint with a body+ # continuationToken that doubles as a resumable watermark.+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ token = resume_config.continuation_token if resume_config is not None else None+ if token is not None:+ logger.debug(f"Azure DevOps: resuming {endpoint} from continuation token")++ while True:+ # A continuationToken fully encodes the stream position, so once we have+ # one (from a resumed run or the previous batch) it must be sent alone —+ # pairing it with startDateTime would reset the stream to the watermark.+ params = {"continuationToken": token} if token else base_params()+ body = fetch(config.path, params).json()+ items = [_flatten_revision(item) for item in (body.get("values", []) or [])]++ if items:+ yield items++ token = body.get("continuationToken")+ if body.get("isLastBatch", True) or not token:+ break++ # Save state AFTER yielding the batch so a crash re-yields it (merge+ # dedupes on primary keys) rather than skipping it.+ resumable_source_manager.save_state(AzureDevOpsResumeConfig(continuation_token=token))+++def azure_devops_source(+ organization: str,+ personal_access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AzureDevOpsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = AZURE_DEVOPS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ organization=organization,+ personal_access_token=personal_access_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ sort_mode=config.sort_mode,+ )diff --git a/posthog/temporal/data_imports/sources/azure_devops/settings.py b/posthog/temporal/data_imports/sources/azure_devops/settings.pynew file mode 100644index 000000000000..52443737aed8--- /dev/null+++ b/posthog/temporal/data_imports/sources/azure_devops/settings.py@@ -0,0 +1,93 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++# Azure DevOps mixes pagination styles per endpoint, dispatched by name in+# azure_devops.py:+# - projects/builds: continuationToken via the x-ms-continuationtoken header+# - pull_requests: $top/$skip offset paging+# - work_item_revisions: body continuationToken + isLastBatch (reporting endpoint)+# - repositories: single per-project response+@dataclass+class AzureDevOpsEndpointConfig:+ name: str+ # Path template under https://dev.azure.com/{organization}; `{project}` is+ # substituted during the per-project fan-out.+ path: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Query param that pushes the incremental cursor server-side.+ incremental_param: Optional[str] = None+ # Stable creation/event-time field used for datetime partitioning.+ partition_key: Optional[str] = None+ sort_mode: Literal["asc", "desc"] = "asc"+++AZURE_DEVOPS_ENDPOINTS: dict[str, AzureDevOpsEndpointConfig] = {+ "projects": AzureDevOpsEndpointConfig(+ name="projects",+ path="/_apis/projects",+ ),+ "repositories": AzureDevOpsEndpointConfig(+ name="repositories",+ path="/{project}/_apis/git/repositories",+ ),+ "builds": AzureDevOpsEndpointConfig(+ name="builds",+ path="/{project}/_apis/build/builds",+ partition_key="queueTime",+ # minTime filters on queue time; queryOrder=queueTimeAscending keeps+ # the watermark monotonic.+ incremental_param="minTime",+ incremental_fields=[+ {+ "label": "queueTime",+ "type": IncrementalFieldType.DateTime,+ "field": "queueTime",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "pull_requests": AzureDevOpsEndpointConfig(+ name="pull_requests",+ path="/{project}/_apis/git/pullrequests",+ primary_keys=["pullRequestId"],+ partition_key="creationDate",+ incremental_param="searchCriteria.minTime",+ # PR search returns newest-first with no ascending option; the pipeline+ # defers desc watermark commits until a run completes.+ sort_mode="desc",+ incremental_fields=[+ {+ "label": "creationDate",+ "type": IncrementalFieldType.DateTime,+ "field": "creationDate",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "work_item_revisions": AzureDevOpsEndpointConfig(+ name="work_item_revisions",+ path="/_apis/wit/reporting/workitemrevisions",+ # Revisions are append-only; (id, rev) identifies one revision.+ primary_keys=["id", "rev"],+ partition_key="changed_date",+ incremental_param="startDateTime",+ incremental_fields=[+ {+ "label": "changed_date",+ "type": IncrementalFieldType.DateTime,+ "field": "changed_date",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+}++ENDPOINTS = tuple(AZURE_DEVOPS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in AZURE_DEVOPS_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/azure_devops/source.py b/posthog/temporal/data_imports/sources/azure_devops/source.pyindex 80537c60b0e7..b87e4e5d8ede 100644--- a/posthog/temporal/data_imports/sources/azure_devops/source.py+++ b/posthog/temporal/data_imports/sources/azure_devops/source.py@@ -1,29 +1,132 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.azure_devops.azure_devops import (+ AzureDevOpsResumeConfig,+ azure_devops_source,+ validate_credentials as validate_azure_devops_credentials,+)+from posthog.temporal.data_imports.sources.azure_devops.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import AzureDevOpsSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class AzureDevOpsSource(SimpleSource[AzureDevOpsSourceConfig]):+class AzureDevOpsSource(ResumableSource[AzureDevOpsSourceConfig, AzureDevOpsResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AZUREDEVOPS+ @property+ def connection_host_fields(self) -> list[str]:+ # The PAT is sent to dev.azure.com/<organization>, so retargeting the+ # organization must force re-entry of the token.+ return ["organization"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "the personal access token is invalid or expired": "Azure DevOps authentication failed. Please check your personal access token (it may have expired).",+ "401 Client Error: Unauthorized for url: https://dev.azure.com": "Azure DevOps authentication failed. Please check your personal access token.",+ "403 Client Error: Forbidden for url: https://dev.azure.com": "Azure DevOps denied access. Please check that your personal access token has read scopes for this data.",+ "404 Client Error: Not Found for url: https://dev.azure.com": "Azure DevOps organization not found. Please check the organization name.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.AZURE_DEV_OPS,label="Azure DevOps",+ caption="""Enter your Azure DevOps credentials to pull your project, build, and work item data into the PostHog Data warehouse.++Your organization is the first path segment of your Azure DevOps URL — for `dev.azure.com/myorg` enter `myorg`. Create a personal access token under User settings > Personal access tokens with read scopes for the data you want to sync (Work Items, Code, Build, Project and Team).""",iconPath="/static/services/azure_devops.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/azure-devops",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="organization",+ label="Organization",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="myorg",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="personal_access_token",+ label="Personal access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: AzureDevOpsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in ENDPOINTS+ ]++ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]++ return schemas++ def validate_credentials(+ self, config: AzureDevOpsSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_azure_devops_credentials(config.organization, config.personal_access_token):+ return True, None++ return False, "Invalid Azure DevOps credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AzureDevOpsResumeConfig]:+ return ResumableSourceManager[AzureDevOpsResumeConfig](inputs, AzureDevOpsResumeConfig)++ def source_for_pipeline(+ self,+ config: AzureDevOpsSourceConfig,+ resumable_source_manager: ResumableSourceManager[AzureDevOpsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return azure_devops_source(+ organization=config.organization,+ personal_access_token=config.personal_access_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/posthog/temporal/data_imports/sources/azure_devops/tests/test_azure_devops.py b/posthog/temporal/data_imports/sources/azure_devops/tests/test_azure_devops.pynew file mode 100644index 000000000000..d532c2269733--- /dev/null+++ b/posthog/temporal/data_imports/sources/azure_devops/tests/test_azure_devops.py@@ -0,0 +1,293 @@+from datetime import UTC, date, datetime+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.azure_devops.azure_devops import (+ AzureDevOpsAuthError,+ AzureDevOpsResumeConfig,+ _flatten_revision,+ _format_datetime,+ _validate_organization,+ azure_devops_source,+ get_rows,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.azure_devops.settings import AZURE_DEVOPS_ENDPOINTS, ENDPOINTS+++def _make_manager(resume_state: AzureDevOpsResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _response(body: dict[str, Any], continuation_header: str | None = None) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = 200+ resp.ok = True+ resp.headers = {"x-ms-continuationtoken": continuation_header} if continuation_header else {}+ return resp+++class TestValidateOrganization:+ @pytest.mark.parametrize(+ "value, expected",+ [+ ("myorg", "myorg"),+ (" myorg ", "myorg"),+ ("https://dev.azure.com/myorg", "myorg"),+ ("dev.azure.com/myorg/project", "myorg"),+ ("my-org.unit_1", "my-org.unit_1"),+ ],+ )+ def test_valid_organizations(self, value, expected):+ assert _validate_organization(value) == expected++ @pytest.mark.parametrize("value", ["", "my org", "org?x=1"])+ def test_invalid_organizations_raise(self, value):+ with pytest.raises(ValueError):+ _validate_organization(value)+++class TestFormatDatetime:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05Z"),+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05Z"),+ (date(2024, 1, 2), "2024-01-02T00:00:00Z"),+ ("2024-01-02T03:04:05Z", "2024-01-02T03:04:05Z"),+ ],+ )+ def test_format_values(self, value, expected):+ assert _format_datetime(value) == expected+++class TestFlattenRevision:+ def test_copies_changed_date_to_top_level(self):+ item = {"id": 1, "rev": 2, "fields": {"System.ChangedDate": "2024-01-02T03:04:05Z"}}+ assert _flatten_revision(item)["changed_date"] == "2024-01-02T03:04:05Z"++ @pytest.mark.parametrize("item", [{"id": 1, "rev": 2}, {"id": 1, "fields": {}}, {"id": 1, "fields": None}])+ def test_leaves_items_without_changed_date_untouched(self, item):+ assert _flatten_revision(item) == item+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [+ (200, True),+ # An invalid PAT yields a 203 + HTML sign-in page, not a 401.+ (203, False),+ (401, False),+ (404, False),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session")+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):+ response = mock.MagicMock()+ response.status_code = status_code+ mock_session.return_value.get.return_value = response++ assert validate_credentials("myorg", "pat") is expected++ @mock.patch("posthog.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session")+ def test_validate_credentials_rejects_bad_org_without_request(self, mock_session):+ assert validate_credentials("my org!", "pat") is False+ mock_session.return_value.get.assert_not_called()+++class TestGetRows:+ @mock.patch("posthog.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session")+ def test_projects_paginate_via_header_token(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({"value": [{"id": "p1", "name": "Alpha"}]}, continuation_header="tok1"),+ _response({"value": [{"id": "p2", "name": "Beta"}]}),+ ]++ manager = _make_manager()+ batches = list(get_rows("myorg", "pat", "projects", mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == ["p1", "p2"]+ second_url = mock_session.return_value.get.call_args_list[1].args[0]+ assert parse_qs(urlparse(second_url).query)["continuationToken"] == ["tok1"]++ @mock.patch("posthog.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session")+ def test_builds_fan_out_per_project_with_ascending_order(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({"value": [{"id": "p1", "name": "Alpha"}]}),+ _response({"value": [{"id": 1, "queueTime": "2024-01-01T00:00:00Z"}]}),+ ]++ manager = _make_manager()+ batches = list(get_rows("myorg", "pat", "builds", mock.MagicMock(), manager))++ assert batches == [[{"id": 1, "queueTime": "2024-01-01T00:00:00Z"}]]+ build_url = mock_session.return_value.get.call_args_list[1].args[0]+ parsed = urlparse(build_url)+ assert parsed.path == "/myorg/Alpha/_apis/build/builds"+ assert parse_qs(parsed.query)["queryOrder"] == ["queueTimeAscending"]++ @mock.patch("posthog.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session")+ def test_builds_incremental_includes_min_time(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({"value": [{"id": "p1", "name": "Alpha"}]}),+ _response({"value": []}),+ ]++ manager = _make_manager()+ list(+ get_rows(+ "myorg",+ "pat",+ "builds",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),+ )+ )++ build_url = mock_session.return_value.get.call_args_list[1].args[0]+ assert parse_qs(urlparse(build_url).query)["minTime"] == ["2024-01-02T00:00:00Z"]++ @mock.patch("posthog.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session")+ def test_pull_requests_use_skip_pagination_and_status_all(self, mock_session):+ full_page = {"value": [{"pullRequestId": i} for i in range(200)]}+ mock_session.return_value.get.side_effect = [+ _response({"value": [{"id": "p1", "name": "Alpha"}]}),+ _response(full_page),+ _response({"value": [{"pullRequestId": 999}]}),+ ]++ manager = _make_manager()+ batches = list(get_rows("myorg", "pat", "pull_requests", mock.MagicMock(), manager))++ assert len(batches) == 2+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list[1:]]+ assert parse_qs(urlparse(urls[0]).query)["searchCriteria.status"] == ["all"]+ assert parse_qs(urlparse(urls[0]).query)["$skip"] == ["0"]+ assert parse_qs(urlparse(urls[1]).query)["$skip"] == ["200"]++ @mock.patch("posthog.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session")+ def test_work_item_revisions_walk_batches_and_flatten(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response(+ {+ "values": [{"id": 1, "rev": 1, "fields": {"System.ChangedDate": "2024-01-01T00:00:00Z"}}],+ "continuationToken": "tok1",+ "isLastBatch": False,+ }+ ),+ _response({"values": [{"id": 1, "rev": 2, "fields": {}}], "isLastBatch": True}),+ ]++ manager = _make_manager()+ batches = list(get_rows("myorg", "pat", "work_item_revisions", mock.MagicMock(), manager))++ assert batches[0][0]["changed_date"] == "2024-01-01T00:00:00Z"+ assert len(batches) == 2+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0].continuation_token == "tok1"++ @mock.patch("posthog.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session")+ def test_work_item_revisions_resume_from_saved_token(self, mock_session):+ mock_session.return_value.get.return_value = _response({"values": [], "isLastBatch": True})++ manager = _make_manager(AzureDevOpsResumeConfig(continuation_token="tok_resume"))+ list(get_rows("myorg", "pat", "work_item_revisions", mock.MagicMock(), manager))++ url = mock_session.return_value.get.call_args.args[0]+ assert parse_qs(urlparse(url).query)["continuationToken"] == ["tok_resume"]++ @mock.patch("posthog.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session")+ def test_work_item_revisions_resume_does_not_send_start_date_time(self, mock_session):+ # A continuationToken fully encodes the stream position; pairing it with+ # startDateTime would reset the stream to the watermark on resume.+ mock_session.return_value.get.return_value = _response({"values": [], "isLastBatch": True})++ manager = _make_manager(AzureDevOpsResumeConfig(continuation_token="tok_resume"))+ list(+ get_rows(+ "myorg",+ "pat",+ "work_item_revisions",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),+ )+ )++ query = parse_qs(urlparse(mock_session.return_value.get.call_args.args[0]).query)+ assert query["continuationToken"] == ["tok_resume"]+ assert "startDateTime" not in query++ @mock.patch("posthog.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session")+ def test_project_enumeration_does_not_carry_endpoint_incremental_param(self, mock_session):+ # Project enumeration is independent of the data endpoint being synced,+ # so the builds incremental filter must not leak into it.+ mock_session.return_value.get.side_effect = [+ _response({"value": [{"id": "p1", "name": "Alpha"}]}),+ _response({"value": []}),+ ]++ manager = _make_manager()+ list(+ get_rows(+ "myorg",+ "pat",+ "builds",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),+ )+ )++ projects_url = mock_session.return_value.get.call_args_list[0].args[0]+ assert urlparse(projects_url).path == "/myorg/_apis/projects"+ assert "minTime" not in parse_qs(urlparse(projects_url).query)++ @mock.patch("posthog.temporal.data_imports.sources.azure_devops.azure_devops.make_tracked_session")+ def test_sign_in_page_raises_auth_error(self, mock_session):+ response = mock.MagicMock()+ response.status_code = 203+ response.ok = True+ mock_session.return_value.get.return_value = response++ manager = _make_manager()+ with pytest.raises(AzureDevOpsAuthError):+ list(get_rows("myorg", "pat", "projects", mock.MagicMock(), manager))+++class TestAzureDevOpsSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = AZURE_DEVOPS_ENDPOINTS[endpoint]+ response = azure_devops_source("myorg", "pat", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == config.sort_mode+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_pull_requests_are_desc_sorted(self):+ response = azure_devops_source("myorg", "pat", "pull_requests", mock.MagicMock(), _make_manager())+ assert response.sort_mode == "desc"++ @pytest.mark.parametrize("config", list(AZURE_DEVOPS_ENDPOINTS.values()))+ def test_partition_keys_are_stable_fields(self, config):+ if config.partition_key:+ assert config.partition_key in {"queueTime", "creationDate", "changed_date"}diff --git a/posthog/temporal/data_imports/sources/azure_devops/tests/test_azure_devops_source.py b/posthog/temporal/data_imports/sources/azure_devops/tests/test_azure_devops_source.pynew file mode 100644index 000000000000..2d52d57c7248--- /dev/null+++ b/posthog/temporal/data_imports/sources/azure_devops/tests/test_azure_devops_source.py@@ -0,0 +1,149 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.azure_devops.azure_devops import AzureDevOpsResumeConfig+from posthog.temporal.data_imports.sources.azure_devops.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.azure_devops.source import AzureDevOpsSource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import AzureDevOpsSourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestAzureDevOpsSource:+ def setup_method(self):+ self.source = AzureDevOpsSource()+ self.team_id = 123+ self.config = AzureDevOpsSourceConfig(organization="myorg", personal_access_token="pat")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.AZUREDEVOPS++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "AzureDevOps"+ assert config.label == "Azure DevOps"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/azure_devops.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["organization", "personal_access_token"]++ def test_connection_host_fields_includes_organization(self):+ # The PAT is sent to dev.azure.com/<organization>, so retargeting the+ # organization must force re-entry of the token.+ assert self.source.connection_host_fields == ["organization"]++ def test_pat_field_is_secret_password(self):+ config = self.source.get_source_config+ token_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "personal_access_token"+ )+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "Azure DevOps returned a sign-in page (203) — the personal access token is invalid or expired.",+ "401 Client Error: Unauthorized for url: https://dev.azure.com/myorg/_apis/projects",+ "403 Client Error: Forbidden for url: https://dev.azure.com/myorg/Alpha/_apis/build/builds",+ "404 Client Error: Not Found for url: https://dev.azure.com/nope/_apis/projects",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_vendor_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "500 Server Error for url: https://dev.azure.com/myorg/_apis/projects",+ ],+ )+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_vendor_error for key in non_retryable_errors)++ def test_get_schemas(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ incremental = {schema.name for schema in schemas if schema.supports_incremental}+ assert incremental == {"builds", "pull_requests", "work_item_revisions"}++ def test_incremental_schemas_advertise_their_fields(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["builds"].incremental_fields == INCREMENTAL_FIELDS["builds"]+ assert [f["field"] for f in schemas["work_item_revisions"].incremental_fields] == ["changed_date"]+ assert schemas["projects"].incremental_fields == []+ assert schemas["projects"].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["builds"])+ assert len(schemas) == 1+ assert schemas[0].name == "builds"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid Azure DevOps credentials"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.azure_devops.source.validate_azure_devops_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("myorg", "pat")++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is AzureDevOpsResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.azure_devops.source.azure_devops_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_ado_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "work_item_revisions"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_ado_source.assert_called_once()+ kwargs = mock_ado_source.call_args.kwargs+ assert kwargs["organization"] == "myorg"+ assert kwargs["personal_access_token"] == "pat"+ assert kwargs["endpoint"] == "work_item_revisions"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"++ @mock.patch("posthog.temporal.data_imports.sources.azure_devops.source.azure_devops_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_ado_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "projects"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_ado_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 71cbccc72801..6319e97b2c8e 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -215,7 +215,8 @@ class AzureBlobSourceConfig(config.Config):@config.configclass AzureDevOpsSourceConfig(config.Config):- pass+ organization: str+ personal_access_token: str@config.config