: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 the microsoft azure (application insights) import source (#112204)
Tom Owers77cf55f1404c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 7e3e29f37646..3c1d282b0e74 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -124,6 +124,7 @@ the row lists both.| aws_step_functions | HTTP | requests | ✅ || aws_systems_manager | HTTP | requests | ✅ || aws_waf | HTTP | requests | ✅ |+| azure_application_insights | HTTP | requests | ✅ || azure_cost_management | HTTP | requests | ✅ || azure_devops | HTTP | requests | ✅ || babelforce | HTTP | requests | ✅ |@@ -980,7 +981,6 @@ doesn't conflict with concurrent PRs.- azure_activity_log- azure_advisor- azure_api_management-- azure_application_insights- azure_blob- azure_data_explorer- azure_data_factorydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/azure_application_insights.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/azure_application_insights.pynew file mode 100644index 000000000000..ed74590ae4f7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/azure_application_insights.py@@ -0,0 +1,181 @@+import json+from collections.abc import Iterator+from datetime import UTC, datetime+from typing import Any+from uuid import UUID++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.azure_application_insights.settings import (+ API_BASE_URL,+ ENDPOINTS,+ LATE_ARRIVAL_OVERLAP,+ PAGE_SIZE,+ SYNC_WINDOW,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import OAuth2Auth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.azureapplicationinsights import (+ AzureApplicationInsightsSourceConfig,+)+++@frozen+class AzureApplicationInsightsResumeConfig:+ start: str+ end: str+ timestamp: str | None = None+ item_id: str | None = None+++def validate_config(config: AzureApplicationInsightsSourceConfig) -> None:+ for name in ("tenant_id", "client_id", "application_id"):+ try:+ UUID(getattr(config, name))+ except (ValueError, TypeError, AttributeError):+ raise ValueError(f"Enter a valid UUID for {name.replace('_', ' ')}.") from None+ if not config.client_secret.strip():+ raise ValueError("Enter the client secret from your Microsoft Entra app registration.")+++def normalize_response(payload: dict[str, Any]) -> list[dict[str, Any]]:+ if payload.get("error"):+ raise ValueError("Azure query returned incomplete results. Reduce the telemetry volume and try again.")+ tables = payload.get("tables")+ if not isinstance(tables, list):+ raise ValueError("Azure query response has no result table.")+ primary = [table for table in tables if table.get("name") == "PrimaryResult"]+ if len(primary) != 1:+ raise ValueError("Azure query response has no result table.")+ table = primary[0]+ columns = table["columns"]+ names = [column["name"] for column in columns]+ rows = []+ for values in table["rows"]:+ row = dict(zip(names, values, strict=True))+ for column in columns:+ name = column["name"]+ if column["type"] == "dynamic" and isinstance(row[name], str):+ row[name] = json.loads(row[name])+ rows.append(row)+ return rows+++class AzureApplicationInsightsClient:+ def __init__(+ self, config: AzureApplicationInsightsSourceConfig, api_version: str, team_id: int, job_id: str+ ) -> None:+ validate_config(config)+ if api_version != "v1":+ raise ValueError("Unsupported Application Insights API version.")+ self.application_id = str(UUID(config.application_id))+ self.api_version = api_version+ self.team_id = team_id+ self.job_id = job_id+ self.auth = OAuth2Auth(+ token_url=f"https://login.microsoftonline.com/{UUID(config.tenant_id)}/oauth2/token",+ client_id=str(UUID(config.client_id)),+ client_secret=config.client_secret,+ extra_token_request_params={"resource": API_BASE_URL},+ )++ def query(self, query: str, timespan: str) -> list[dict[str, Any]]:+ config: RESTAPIConfig = {+ "client": {+ "base_url": API_BASE_URL,+ "auth": self.auth,+ "paginator": "single_page",+ "allowed_hosts": ["api.applicationinsights.io"],+ "allow_redirects": False,+ "request_timeout": (10, 120),+ },+ "resources": [+ {+ "name": "query",+ "endpoint": {+ "path": f"/{self.api_version}/apps/{self.application_id}/query",+ "method": "POST",+ "json": {"query": query, "timespan": timespan},+ "data_selector": "$",+ },+ "data_map": normalize_response,+ }+ ],+ }+ return [row for page in rest_api_resource(config, self.team_id, self.job_id, None) for row in page]++ def read_rows(+ self,+ endpoint: str,+ manager: ResumableSourceManager[AzureApplicationInsightsResumeConfig],+ last_value: datetime | str | None,+ ) -> Iterator[list[dict[str, Any]]]:+ if endpoint not in ENDPOINTS:+ raise ValueError("Unknown Application Insights table.")+ state = manager.load_state() if manager.can_resume() else None+ if state is None:+ end = datetime.now(UTC)+ start = end - SYNC_WINDOW+ if last_value is not None:+ watermark = datetime.fromisoformat(last_value) if isinstance(last_value, str) else last_value+ watermark = watermark.replace(tzinfo=UTC) if watermark.tzinfo is None else watermark.astimezone(UTC)+ start = max(start, watermark - LATE_ARRIVAL_OVERLAP)+ state = AzureApplicationInsightsResumeConfig(start=start.isoformat(), end=end.isoformat())+ while True:+ # String literals preserve Azure's sub-microsecond timestamps across page boundaries.+ query = (+ f"{endpoint} | where timestamp >= todatetime({json.dumps(state.start)})"+ f" and timestamp < todatetime({json.dumps(state.end)})"+ )+ if state.timestamp is not None:+ timestamp = f"todatetime({json.dumps(state.timestamp)})"+ query += (+ f" | where timestamp > {timestamp} or (timestamp == {timestamp}"+ f" and strcmp(tostring(itemId), {json.dumps(state.item_id)}) > 0)"+ )+ query += f" | order by timestamp asc, itemId asc | take {PAGE_SIZE}"+ rows = self.query(query, f"{state.start}/{state.end}")+ if not rows:+ manager.safe_point()+ return+ for row in rows:+ if (+ not isinstance(row.get("timestamp"), str)+ or not isinstance(row.get("itemId"), str)+ or not row["itemId"]+ ):+ raise ValueError("Azure telemetry is missing its timestamp or item ID.")+ last = rows[-1]+ if (last["timestamp"], last["itemId"]) == (state.timestamp, state.item_id):+ raise ValueError("Azure query pagination did not advance.")+ state = AzureApplicationInsightsResumeConfig(+ start=state.start, end=state.end, timestamp=last["timestamp"], item_id=last["itemId"]+ )+ manager.save_state(state)+ yield rows+ manager.safe_point()+ if len(rows) < PAGE_SIZE:+ return+++def azure_application_insights_source(+ config: AzureApplicationInsightsSourceConfig,+ api_version: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ manager: ResumableSourceManager[AzureApplicationInsightsResumeConfig],+ last_value: datetime | str | None,+) -> SourceResponse:+ client = AzureApplicationInsightsClient(config, api_version, team_id, job_id)+ return SourceResponse(+ name=endpoint,+ items=lambda: client.read_rows(endpoint, manager, last_value),+ primary_keys=["itemId"],+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/canonical_descriptions.pynew file mode 100644index 000000000000..3f95e1a67c55--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/canonical_descriptions.py@@ -0,0 +1,56 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++DOCS_URL = "https://learn.microsoft.com/en-us/azure/azure-monitor/app/data-model-complete"+COMMON_COLUMNS = {+ "timestamp": "Time when the telemetry item was recorded.",+ "itemId": "Unique identifier for the telemetry item.",+ "itemCount": "Number of occurrences represented by the telemetry item.",+ "operation_Id": "Identifier for the root operation that groups related telemetry.",+ "cloud_RoleName": "Name of the application role that produced the telemetry.",+}+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "requests": {+ "description": "Incoming application requests, with their duration and result.",+ "docs_url": DOCS_URL,+ "columns": {+ **COMMON_COLUMNS,+ "name": "Name of the request.",+ "duration": "Request duration in milliseconds.",+ "success": "Whether the request succeeded.",+ "resultCode": "Response code returned by the application.",+ },+ },+ "dependencies": {+ "description": "Calls to external services or storage, with their duration and result.",+ "docs_url": DOCS_URL,+ "columns": {+ **COMMON_COLUMNS,+ "target": "Target of the dependency call.",+ "duration": "Dependency call duration in milliseconds.",+ "success": "Whether the dependency call succeeded.",+ },+ },+ "exceptions": {+ "description": "Application exceptions and their diagnostic details.",+ "docs_url": DOCS_URL,+ "columns": {+ **COMMON_COLUMNS,+ "problemId": "Identifier that groups exceptions from the same problem.",+ "type": "Type of exception.",+ "outerMessage": "Message from the outer exception.",+ },+ },+ "availabilityResults": {+ "description": "Availability test results that measure application responsiveness and uptime.",+ "docs_url": DOCS_URL,+ "columns": {+ **COMMON_COLUMNS,+ "name": "Name of the availability test.",+ "location": "Location where the test ran.",+ "success": "Whether the availability test succeeded.",+ "duration": "Availability test duration in milliseconds.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/settings.pynew file mode 100644index 000000000000..6989e884f09a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/settings.py@@ -0,0 +1,22 @@+from datetime import timedelta++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++API_BASE_URL = "https://api.applicationinsights.io"+API_DOCS_URL = "https://learn.microsoft.com/en-us/rest/api/application-insights/query/execute"+AUTH_DOCS_URL = "https://learn.microsoft.com/en-us/azure/azure-monitor/app/azure-ad-authentication"+PAGE_SIZE = 1000+SYNC_WINDOW = timedelta(days=7)+LATE_ARRIVAL_OVERLAP = timedelta(hours=1)+ENDPOINTS = ("requests", "dependencies", "exceptions", "availabilityResults")+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: [+ {+ "label": "timestamp",+ "field": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field_type": IncrementalFieldType.DateTime,+ }+ ]+ for name in ENDPOINTS+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/source.pyindex a1e3fbe8fee8..fb2ca8647fa2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/source.py@@ -1,20 +1,141 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from requests import HTTPError++from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.azure_application_insights.azure_application_insights import (+ AzureApplicationInsightsClient,+ AzureApplicationInsightsResumeConfig,+ azure_application_insights_source,+ validate_config,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.azure_application_insights.settings import (+ API_DOCS_URL,+ AUTH_DOCS_URL,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (+ OAUTH2_PERMANENT_ERROR_MARKER,+ OAuth2AuthRequestError,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.azureapplicationinsights import (AzureApplicationInsightsSourceConfig,)from products.warehouse_sources.backend.types import ExternalDataSourceType+AUTH_ERROR = "Azure authentication failed. Check the tenant ID, client ID, and client secret."+PERMISSION_ERROR = "Grant your Microsoft Entra app the Reader role on this Application Insights resource."+APP_ERROR = "Application Insights could not find the resource. Check the application ID and its access permissions."+@SourceRegistry.register-class AzureApplicationInsightsSource(SimpleSource[AzureApplicationInsightsSourceConfig]):+class AzureApplicationInsightsSource(+ ResumableSource[AzureApplicationInsightsSourceConfig, AzureApplicationInsightsResumeConfig]+):+ supported_versions = ("v1",)+ default_version = "v1"+ api_docs_url = API_DOCS_URL+ lists_tables_without_credentials = True+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AZUREAPPLICATIONINSIGHTS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": AUTH_ERROR,+ "403 Client Error": PERMISSION_ERROR,+ "404 Client Error": APP_ERROR,+ OAUTH2_PERMANENT_ERROR_MARKER: AUTH_ERROR,+ "Azure query returned incomplete results": "Azure returned incomplete results. Reduce the telemetry volume and try again.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.azure_application_insights.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AzureApplicationInsightsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=ENDPOINTS)++ def validate_credentials(+ self,+ config: AzureApplicationInsightsSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ try:+ validate_config(config)+ except ValueError as error:+ return False, str(error)+ if schema_name is not None and schema_name not in ENDPOINTS:+ return False, "Unknown Application Insights table."+ client = AzureApplicationInsightsClient(config, self.resolve_api_version(api_version), team_id, "")+ try:+ client.query(f"{schema_name} | take 1" if schema_name else "print 1", "PT1M")+ except OAuth2AuthRequestError as error:+ if error.is_permanent:+ return False, AUTH_ERROR+ raise+ except HTTPError as error:+ status = error.response.status_code if error.response is not None else None+ if status == 403 and schema_name is None:+ return True, None+ if status in (401, 403, 404):+ return False, {401: AUTH_ERROR, 403: PERMISSION_ERROR, 404: APP_ERROR}[status]+ raise+ return True, None++ def get_resumable_source_manager(+ self, inputs: SourceInputs+ ) -> ResumableSourceManager[AzureApplicationInsightsResumeConfig]:+ return ResumableSourceManager(inputs, AzureApplicationInsightsResumeConfig)++ def source_for_pipeline(+ self,+ config: AzureApplicationInsightsSourceConfig,+ resumable_source_manager: ResumableSourceManager[AzureApplicationInsightsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return azure_application_insights_source(+ config=config,+ api_version=self.resolve_api_version(inputs.api_version),+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ manager=resumable_source_manager,+ last_value=inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(@@ -22,6 +143,51 @@ class AzureApplicationInsightsSource(SimpleSource[AzureApplicationInsightsSourcecategory=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Microsoft Azure (Application Insights)",iconPath="/static/services/azure_application_insights.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ caption=(+ "Use a Microsoft Entra app registration with the Reader role on your Application Insights resource. "+ "Create its client secret under **App registrations > Certificates & secrets**. "+ "Find the Application Insights application ID under **API Access**. "+ f"Follow [Microsoft's authentication setup]({AUTH_DOCS_URL}). "+ "Supports Azure public cloud. Each sync reads at most the last seven days. "+ "Incremental sync repeats the previous hour to capture delayed telemetry. "+ "Older telemetry requires a separate export."+ ),+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="tenant_id",+ label="Tenant ID",+ type=SourceFieldInputConfigType.TEXT,+ secret=False,+ required=True,+ placeholder="00000000-0000-0000-0000-000000000000",+ ),+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ secret=False,+ required=True,+ placeholder="00000000-0000-0000-0000-000000000000",+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ secret=True,+ required=True,+ placeholder="",+ ),+ SourceFieldInputConfig(+ name="application_id",+ label="Application Insights application ID",+ type=SourceFieldInputConfigType.TEXT,+ secret=False,+ required=True,+ placeholder="00000000-0000-0000-0000-000000000000",+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/tests/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/tests/conftest.pynew file mode 100644index 000000000000..4fd709c96a99--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/tests/conftest.py@@ -0,0 +1,52 @@+import json+from http.client import responses+from io import BytesIO+from typing import Any++import pytest+from unittest.mock import MagicMock++from requests import PreparedRequest, Response, Session+from urllib3.response import HTTPResponse++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.azureapplicationinsights import (+ AzureApplicationInsightsSourceConfig,+)+++def config() -> AzureApplicationInsightsSourceConfig:+ return AzureApplicationInsightsSourceConfig(+ tenant_id="00000000-0000-0000-0000-000000000001",+ client_id="00000000-0000-0000-0000-000000000002",+ application_id="00000000-0000-0000-0000-000000000003",+ client_secret="fake-client-secret",+ )+++def manager() -> MagicMock:+ manager = MagicMock()+ manager.can_resume.return_value = False+ return manager+++def http_mock(monkeypatch: pytest.MonkeyPatch) -> MagicMock:+ handler = MagicMock()++ def send(session: Session, request: PreparedRequest, **kwargs: Any) -> Response:+ status, body = handler(request)+ response = Response()+ response.status_code = status+ response.reason = responses[status]+ response.url = request.url or ""+ response.request = request+ response._content = json.dumps(body).encode()+ response.raw = HTTPResponse(body=BytesIO(response._content), preload_content=False)+ response._content_consumed = True # type: ignore[attr-defined]+ response.headers["Content-Type"] = "application/json"+ return response++ monkeypatch.setattr(Session, "send", send)+ return handlerdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/tests/test_azure_application_insights.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/tests/test_azure_application_insights.pynew file mode 100644index 000000000000..d3e8a2bffab1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/tests/test_azure_application_insights.py@@ -0,0 +1,231 @@+import json+from collections.abc import Iterable+from datetime import UTC, datetime+from typing import Any, cast+from urllib.parse import parse_qs++import pytest+import time_machine+from unittest.mock import MagicMock++from requests import HTTPError++from products.warehouse_sources.backend.temporal.data_imports.sources.azure_application_insights.azure_application_insights import (+ AzureApplicationInsightsClient,+ AzureApplicationInsightsResumeConfig,+ azure_application_insights_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.azure_application_insights.source import (+ AzureApplicationInsightsSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (+ RESTClientRetryableError,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.azureapplicationinsights import (+ AzureApplicationInsightsSourceConfig,+)++TOKEN = {"access_token": "fake-access-token", "expires_in": 3600}+TIMESTAMP = "2026-01-07T10:00:00.1234567Z"+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.azure_application_insights.azure_application_insights"+++def payload(ids: list[str]) -> dict[str, Any]:+ return {+ "tables": [+ {+ "name": "PrimaryResult",+ "columns": [+ {"name": "timestamp", "type": "datetime"},+ {"name": "itemId", "type": "string"},+ {"name": "customDimensions", "type": "dynamic"},+ ],+ "rows": [[TIMESTAMP, item_id, '{"environment":"test"}'] for item_id in ids],+ }+ ]+ }+++@time_machine.travel("2026-01-08T12:00:00Z", tick=False)[email protected]("terminal_ids", [[], ["c"]])+def test_pagination_auth_and_checkpoint(+ config: AzureApplicationInsightsSourceConfig,+ manager: MagicMock,+ http_mock: MagicMock,+ monkeypatch: pytest.MonkeyPatch,+ terminal_ids: list[str],+) -> None:+ monkeypatch.setattr(f"{MODULE}.PAGE_SIZE", 2)+ http_mock.side_effect = [(200, TOKEN), (200, payload(["a", "b"])), (200, payload(terminal_ids))]+ response = azure_application_insights_source(config, "v1", "requests", 1, "job", manager, None)+ batches = iter(cast(Iterable[list[dict[str, Any]]], response.items()))+ first = next(batches)+ assert first[0]["customDimensions"] == {"environment": "test"}+ assert manager.save_state.call_args.args[0].item_id == "b"+ assert manager.save_state.call_args.args[0].timestamp == TIMESTAMP+ assert [row["itemId"] for batch in [first, *batches] for row in batch] == ["a", "b", *terminal_ids]+ token_request, first_request, second_request = [call.args[0] for call in http_mock.call_args_list]+ assert token_request.url == f"https://login.microsoftonline.com/{config.tenant_id}/oauth2/token"+ assert parse_qs(token_request.body) == {+ "client_id": [config.client_id],+ "client_secret": [config.client_secret],+ "grant_type": ["client_credentials"],+ "resource": ["https://api.applicationinsights.io"],+ }+ assert first_request.url == f"https://api.applicationinsights.io/v1/apps/{config.application_id}/query"+ assert first_request.method == "POST"+ assert first_request.headers["Authorization"] == "Bearer fake-access-token"+ assert second_request.headers["Authorization"] == "Bearer fake-access-token"+ first_body, second_body = json.loads(first_request.body), json.loads(second_request.body)+ assert first_body["timespan"] == "2026-01-01T12:00:00+00:00/2026-01-08T12:00:00+00:00"+ assert second_body["timespan"] == first_body["timespan"]+ assert 'strcmp(tostring(itemId), "b") > 0' in second_body["query"]+ assert TIMESTAMP in second_body["query"]+ assert "order by timestamp asc, itemId asc | take 2" in first_body["query"]+ assert response.sort_mode == "asc"+ manager.safe_point.assert_called()+++@time_machine.travel("2026-01-08T12:00:00Z", tick=False)+ ("last_value", "expected_start"),+ [+ (None, "2026-01-01T12:00:00+00:00"),+ ("2026-01-07T12:00:00Z", "2026-01-07T11:00:00+00:00"),+ (datetime(2026, 1, 7, 12), "2026-01-07T11:00:00+00:00"),+ (datetime(2026, 1, 7, 12, tzinfo=UTC), "2026-01-07T11:00:00+00:00"),+ ("2025-12-01T12:00:00Z", "2026-01-01T12:00:00+00:00"),+ ],+)+def test_incremental_and_full_refresh_window(+ config: AzureApplicationInsightsSourceConfig,+ manager: MagicMock,+ http_mock: MagicMock,+ last_value: datetime | str | None,+ expected_start: str,+) -> None:+ http_mock.side_effect = [(200, TOKEN), (200, payload([]))]+ response = azure_application_insights_source(config, "v1", "dependencies", 1, "job", manager, last_value)+ assert list(cast(Iterable[Any], response.items())) == []+ body = json.loads(http_mock.call_args.args[0].body)+ assert body["timespan"] == f"{expected_start}/2026-01-08T12:00:00+00:00"+ assert f'timestamp >= todatetime("{expected_start}")' in body["query"]+ assert "strcmp" not in body["query"]+ manager.save_state.assert_not_called()+++@time_machine.travel("2026-02-08T12:00:00Z", tick=False)+def test_resume_preserves_window_and_escapes_cursor(+ config: AzureApplicationInsightsSourceConfig,+ manager: MagicMock,+ http_mock: MagicMock,+) -> None:+ manager.can_resume.return_value = True+ manager.load_state.return_value = AzureApplicationInsightsResumeConfig(+ start="2026-01-01T12:00:00Z", end="2026-01-08T12:00:00Z", timestamp=TIMESTAMP, item_id='a"\\b'+ )+ http_mock.side_effect = [(200, TOKEN), (200, payload([]))]+ response = azure_application_insights_source(config, "v1", "exceptions", 1, "job", manager, None)+ assert list(cast(Iterable[Any], response.items())) == []+ body = json.loads(http_mock.call_args.args[0].body)+ assert body["timespan"] == "2026-01-01T12:00:00Z/2026-01-08T12:00:00Z"+ assert f"strcmp(tostring(itemId), {json.dumps('a' + chr(34) + chr(92) + 'b')})" in body["query"]+++ ("body", "message"),+ [+ ({"tables": [], "error": {"code": "PartialError"}}, "incomplete results"),+ ({}, "no result table"),+ ({"tables": []}, "no result table"),+ (payload([""]), "missing its timestamp or item ID"),+ ],+)+def test_bad_results_do_not_advance_checkpoint(+ config: AzureApplicationInsightsSourceConfig,+ manager: MagicMock,+ http_mock: MagicMock,+ body: dict[str, Any],+ message: str,+) -> None:+ http_mock.side_effect = [(200, TOKEN), (200, body)]+ response = azure_application_insights_source(config, "v1", "availabilityResults", 1, "job", manager, None)+ with pytest.raises(ValueError, match=message):+ list(cast(Iterable[Any], response.items()))+ manager.save_state.assert_not_called()++[email protected]("status", [401, 403, 404, 429, 500, 503])+def test_http_error_classification(+ config: AzureApplicationInsightsSourceConfig, http_mock: MagicMock, status: int+) -> None:+ client = AzureApplicationInsightsClient(config, "v1", 1, "job")+ client.auth._apply_token_response(TOKEN)+ http_mock.return_value = (status, {"error": {"code": "TestError"}})+ expected = HTTPError if status in (401, 403, 404) else RESTClientRetryableError+ with pytest.raises(expected) as error:+ client.query("print 1", "PT1M")+ patterns = AzureApplicationInsightsSource().get_non_retryable_errors()+ assert any(pattern in str(error.value) for pattern in patterns) == (status in (401, 403, 404))+++ ("version", "endpoint", "message"),+ [+ ("v2", "requests", "Unsupported Application Insights API version"),+ ("v1", "requests | take 1", "Unknown Application Insights table"),+ ],+)+def test_invalid_query_target_makes_no_request(+ config: AzureApplicationInsightsSourceConfig,+ manager: MagicMock,+ http_mock: MagicMock,+ version: str,+ endpoint: str,+ message: str,+) -> None:+ with pytest.raises(ValueError, match=message):+ response = azure_application_insights_source(config, version, endpoint, 1, "job", manager, None)+ list(cast(Iterable[Any], response.items()))+ http_mock.assert_not_called()+++def test_repeated_cursor_does_not_advance_checkpoint(+ config: AzureApplicationInsightsSourceConfig,+ manager: MagicMock,+ http_mock: MagicMock,+) -> None:+ manager.can_resume.return_value = True+ manager.load_state.return_value = AzureApplicationInsightsResumeConfig(+ start="2026-01-01T12:00:00Z", end="2026-01-08T12:00:00Z", timestamp=TIMESTAMP, item_id="a"+ )+ http_mock.side_effect = [(200, TOKEN), (200, payload(["a"]))]+ response = azure_application_insights_source(config, "v1", "requests", 1, "job", manager, None)+ with pytest.raises(ValueError, match="pagination did not advance"):+ list(cast(Iterable[Any], response.items()))+ manager.save_state.assert_not_called()+++@time_machine.travel("2026-01-08T12:00:00Z", tick=False)[email protected]("incremental", [False, True])+def test_pipeline_applies_watermark_only_for_incremental_sync(+ config: AzureApplicationInsightsSourceConfig,+ manager: MagicMock,+ http_mock: MagicMock,+ incremental: bool,+) -> None:+ inputs = MagicMock(+ api_version="v1",+ schema_name="requests",+ team_id=1,+ job_id="job",+ should_use_incremental_field=incremental,+ db_incremental_field_last_value="2026-01-07T12:00:00Z",+ )+ http_mock.side_effect = [(200, TOKEN), (200, payload([]))]+ response = AzureApplicationInsightsSource().source_for_pipeline(config, manager, inputs)+ assert list(cast(Iterable[Any], response.items())) == []+ body = json.loads(http_mock.call_args.args[0].body)+ assert body["timespan"].split("/")[0] == (+ "2026-01-07T11:00:00+00:00" if incremental else "2026-01-01T12:00:00+00:00"+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/tests/test_azure_application_insights_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/tests/test_azure_application_insights_source.pynew file mode 100644index 000000000000..b984f7b8cc36--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_application_insights/tests/test_azure_application_insights_source.py@@ -0,0 +1,103 @@+import json++import pytest+from unittest.mock import MagicMock++from products.warehouse_sources.backend.temporal.data_imports.sources.azure_application_insights.source import (+ APP_ERROR,+ AUTH_ERROR,+ PERMISSION_ERROR,+ AzureApplicationInsightsSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (+ OAuth2AuthRequestError,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.azureapplicationinsights import (+ AzureApplicationInsightsSourceConfig,+)+++ ("status", "schema", "result"),+ [+ (200, None, (True, None)),+ (200, "requests", (True, None)),+ (401, None, (False, AUTH_ERROR)),+ (403, None, (True, None)),+ (403, "requests", (False, PERMISSION_ERROR)),+ (404, None, (False, APP_ERROR)),+ ],+)+def test_credential_probe_status(+ config: AzureApplicationInsightsSourceConfig,+ http_mock: MagicMock,+ status: int,+ schema: str | None,+ result: tuple[bool, str | None],+) -> None:+ http_mock.side_effect = [+ (200, {"access_token": "fake-token", "expires_in": 3600}),+ (status, {"tables": [{"name": "PrimaryResult", "columns": [], "rows": []}]}),+ ]+ assert AzureApplicationInsightsSource().validate_credentials(config, 1, schema_name=schema) == result+ assert http_mock.call_count == 2+ assert json.loads(http_mock.call_args.args[0].body) == {+ "query": "requests | take 1" if schema else "print 1",+ "timespan": "PT1M",+ }+++ ("status", "error_code"),+ [+ (400, "invalid_client"),+ (401, "invalid_client"),+ (429, "temporarily_unavailable"),+ (503, "temporarily_unavailable"),+ ],+)+def test_token_error_mapping(+ config: AzureApplicationInsightsSourceConfig,+ http_mock: MagicMock,+ status: int,+ error_code: str,+) -> None:+ http_mock.return_value = (status, {"error": error_code})+ source = AzureApplicationInsightsSource()+ if status in (400, 401):+ assert source.validate_credentials(config, 1) == (False, AUTH_ERROR)+ else:+ with pytest.raises(OAuth2AuthRequestError) as error:+ source.validate_credentials(config, 1)+ assert not error.value.is_permanent+ assert http_mock.call_count == 1+++ ("field", "value"),+ [+ ("tenant_id", "../common"),+ ("client_id", "invalid"),+ ("application_id", "id/query?query=evil"),+ ("client_secret", " "),+ ],+)+def test_invalid_config_makes_no_request(+ config: AzureApplicationInsightsSourceConfig,+ http_mock: MagicMock,+ field: str,+ value: str,+) -> None:+ setattr(config, field, value)+ valid, message = AzureApplicationInsightsSource().validate_credentials(config, 1)+ assert valid is False+ assert message and "Enter" in message+ http_mock.assert_not_called()+++def test_unknown_schema_makes_no_request(config: AzureApplicationInsightsSourceConfig, http_mock: MagicMock) -> None:+ assert AzureApplicationInsightsSource().validate_credentials(config, 1, schema_name="requests | take 10") == (+ False,+ "Unknown Application Insights table.",+ )+ http_mock.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/azureapplicationinsights.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/azureapplicationinsights.pyindex 64455d9604f4..e7c6ae8f1cfe 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/azureapplicationinsights.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/azureapplicationinsights.py@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AzureApplicationInsightsSourceConfig(config.Config):- pass+ tenant_id: str+ client_id: str+ client_secret: str+ application_id: str