: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_cost_management source (#73796)
Tom Owersa1f19f728aad
diff --git a/frontend/public/services/azure_cost_management.png b/frontend/public/services/azure_cost_management.pngindex c5736e43b50d..d04883e8db2f 100644Binary files a/frontend/public/services/azure_cost_management.png and b/frontend/public/services/azure_cost_management.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 53e9588f5873..3b87db94acd3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -95,6 +95,7 @@ the row lists both.| awin | HTTP | requests | ✅ || aws_cost_explorer | HTTP | requests | ✅ || aws_ses | HTTP | requests | ✅ |+| azure_cost_management | HTTP | requests | ✅ || azure_devops | HTTP | requests | ✅ || babelforce | HTTP | requests | ✅ || bamboohr | HTTP | requests | ✅ |@@ -831,7 +832,6 @@ doesn't conflict with concurrent PRs.- azure_api_management- azure_application_insights- azure_blob-- azure_cost_management- azure_data_explorer- azure_data_factory- azure_log_analyticsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/azure_cost_management.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/azure_cost_management.pynew file mode 100644index 000000000000..62117d2335d0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/azure_cost_management.py@@ -0,0 +1,521 @@+import re+import time+from collections.abc import Callable, Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import quote, urlencode++import requests+import structlog+from structlog.types import FilteringBoundLogger+from urllib3.util.retry import Retry++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.azure_cost_management.settings import (+ AZURE_COST_MANAGEMENT_ENDPOINTS,+ AzureCostManagementEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse++LOGIN_HOST = "https://login.microsoftonline.com"+MANAGEMENT_HOST = "https://management.azure.com"+# Client-credentials token audience for Azure Resource Manager, which fronts Cost Management.+MANAGEMENT_TOKEN_SCOPE = "https://management.azure.com/.default"++REQUEST_TIMEOUT_SECONDS = 180+MAX_RETRY_ATTEMPTS = 6+MAX_BACKOFF_SECONDS = 120.0+# The Query API caps a single request's date range at one year, so longer backfills are walked as+# consecutive one-year windows.+MAX_WINDOW_DAYS = 365+# How far back a first sync reaches when no start date is configured.+DEFAULT_HISTORY_DAYS = 365+# Azure forecasts at most a rolling year ahead; a month is the useful horizon for daily granularity.+FORECAST_HORIZON_DAYS = 30++# Cost Management throttles per scope (roughly a handful of query calls a minute) and returns the+# wait in its own headers rather than only in `Retry-After`.+RETRY_AFTER_HEADERS = (+ "Retry-After",+ "x-ms-ratelimit-microsoft.consumption-retry-after",+ "x-ms-ratelimit-microsoft.costmanagement-retry-after",+ "x-ms-ratelimit-microsoft.costmanagement-clienttype-retry-after",+ "x-ms-ratelimit-microsoft.costmanagement-entity-retry-after",+)+# Sent so Azure buckets our throttling separately from other clients on the same subscription.+COMMAND_NAME = "PostHogDataWarehouse"+++class AzureCostManagementRetryableError(Exception):+ """Transient upstream failure (throttle or 5xx) worth retrying."""++ pass+++@frozen+class AzureCostManagementResumeConfig:+ # ISO date of the window the sync was on when state was saved. Windows are recomputed+ # deterministically, so replaying from this date skips every window already walked.+ window_start: str | None = None+ # Azure's `properties.nextLink` for the page to fetch next within that window. None means+ # "start the window from its first page".+ next_link: str | None = None+++def _snake_case(name: str) -> str:+ """`ServiceName` -> `service_name`, `ResourceId` -> `resource_id`, `CostUSD` -> `cost_usd`."""+ with_boundaries = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", name)+ return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", with_boundaries).lower()+++def normalize_scope(scope: str) -> str:+ """Trim a user-entered ARM scope to the bare path segment used to build request URLs.++ The scope is user-supplied and becomes part of the request URL, so a value carrying its own+ host (or scheme) is rejected rather than silently repointing our credentialed requests.+ """+ raw = (scope or "").strip()+ # The scope is interpolated into the request URL, so reject anything that could break out of+ # the path: a scheme/host (`://` or a protocol-relative `//`), or a delimiter (`?`, `#`, `\`)+ # that would push the appended Cost Management path into the query string or fragment and+ # repoint the credentialed request at an arbitrary ARM operation.+ if "://" in raw or raw.startswith("//") or any(char in raw for char in ("?", "#", "\\")):+ raise ValueError("Azure Cost Management scope must be an ARM path, not a URL")++ trimmed = raw.strip("/")+ if not trimmed:+ raise ValueError("Azure Cost Management scope is required")+ return trimmed+++def _endpoint_url(scope: str, operation: str, api_version: str) -> str:+ query = urlencode({"api-version": api_version})+ return f"{MANAGEMENT_HOST}/{scope}/providers/Microsoft.CostManagement/{operation}?{query}"+++def _validated_next_link(next_link: str) -> str:+ """Only follow a continuation URL that stays on Azure Resource Manager."""+ if not next_link.startswith(f"{MANAGEMENT_HOST}/"):+ raise ValueError("Azure Cost Management returned a nextLink outside management.azure.com")+ return next_link+++def _error_description(response: requests.Response) -> str:+ # Azure Resource Manager errors look like {"error": {"code": ..., "message": ...}}.+ try:+ body = response.json()+ except ValueError:+ return ""+ if not isinstance(body, dict):+ return ""+ error = body.get("error")+ if isinstance(error, dict) and error.get("message"):+ return f" — {error['message']}"+ if isinstance(body.get("error_description"), str):+ return f" — {body['error_description']}"+ return ""+++def _retry_after_seconds(response: requests.Response) -> Optional[float]:+ for header in RETRY_AFTER_HEADERS:+ raw = response.headers.get(header)+ if raw is None:+ continue+ try:+ seconds = float(raw)+ except (TypeError, ValueError):+ continue+ if seconds >= 0:+ return min(seconds, MAX_BACKOFF_SECONDS)+ return None+++def _backoff_seconds(response: requests.Response, attempt: int) -> float:+ retry_after = _retry_after_seconds(response)+ if retry_after is not None:+ return retry_after+ return min(2.0**attempt, MAX_BACKOFF_SECONDS)+++def _parse_usage_date(value: Any) -> Any:+ """Normalize Azure's `UsageDate` (an int like 20240115, or an ISO timestamp) to `YYYY-MM-DD`."""+ if value is None:+ return None+ if isinstance(value, int):+ text = str(value)+ elif isinstance(value, str):+ text = value.strip()+ else:+ return value++ if len(text) == 8 and text.isdigit():+ try:+ return date(int(text[0:4]), int(text[4:6]), int(text[6:8])).isoformat()+ except ValueError:+ return text+ try:+ return datetime.fromisoformat(text.replace("Z", "+00:00")).date().isoformat()+ except ValueError:+ return text+++def rows_from_query_result(payload: Any, scope: str) -> tuple[list[dict[str, Any]], Optional[str]]:+ """Zip the query API's `columns` + `rows` matrix into row dicts, plus the continuation link."""+ properties = payload.get("properties") if isinstance(payload, dict) else None+ if not isinstance(properties, dict):+ return [], None++ columns = [_snake_case(str(column.get("name", ""))) for column in properties.get("columns") or []]+ rows: list[dict[str, Any]] = []+ for values in properties.get("rows") or []:+ row: dict[str, Any] = dict(zip(columns, values))+ if "usage_date" in row:+ row["usage_date"] = _parse_usage_date(row["usage_date"])+ row["scope"] = scope+ rows.append(row)++ next_link = properties.get("nextLink")+ return rows, next_link if isinstance(next_link, str) and next_link else None+++def rows_from_dimensions(payload: Any, scope: str) -> list[dict[str, Any]]:+ if not isinstance(payload, dict):+ return []++ rows: list[dict[str, Any]] = []+ for item in payload.get("value") or []:+ properties = item.get("properties") or {}+ rows.append(+ {+ "scope": scope,+ "id": item.get("id"),+ "name": item.get("name"),+ "type": item.get("type"),+ "category": properties.get("category"),+ "description": properties.get("description"),+ "filter_enabled": properties.get("filterEnabled"),+ "grouping_enabled": properties.get("groupingEnabled"),+ "usage_start": properties.get("usageStart"),+ "usage_end": properties.get("usageEnd"),+ "total": properties.get("total"),+ "data": properties.get("data"),+ }+ )+ return rows+++def _to_date(value: Any) -> Optional[date]:+ if value is None:+ return None+ if isinstance(value, datetime):+ return value.date()+ if isinstance(value, date):+ return value+ try:+ return datetime.fromisoformat(str(value).replace("Z", "+00:00")).date()+ except ValueError:+ return None+++def resolve_window_start(+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ configured_start_date: str | None,+ today: date,+) -> date:+ if should_use_incremental_field:+ watermark = _to_date(db_incremental_field_last_value)+ if watermark is not None:+ # Re-pull the watermark day itself; Azure restates the tail of the window and merge+ # dedupes the overlap on the composite key.+ return min(watermark, today)++ configured = _to_date(configured_start_date)+ if configured is not None:+ return min(configured, today)++ return today - timedelta(days=DEFAULT_HISTORY_DAYS)+++def build_windows(start: date, end: date, max_days: int = MAX_WINDOW_DAYS) -> list[SyncWindow[date]]:+ """Split an inclusive date range into consecutive windows the query API will accept."""+ if start > end:+ return []++ windows: list[SyncWindow[date]] = []+ window_start = start+ while window_start <= end:+ window_end = min(window_start + timedelta(days=max_days - 1), end)+ windows.append(SyncWindow(start=window_start, end=window_end))+ window_start = window_end + timedelta(days=1)+ return windows+++def build_query_body(config: AzureCostManagementEndpointConfig, window_start: date, window_end: date) -> dict[str, Any]:+ dataset: dict[str, Any] = {+ "granularity": "Daily",+ "aggregation": {"totalCost": {"name": "Cost", "function": "Sum"}},+ }+ if config.grouping:+ dataset["grouping"] = [{"type": "Dimension", "name": dimension} for dimension in config.grouping]++ body: dict[str, Any] = {+ "type": config.export_type,+ "timeframe": "Custom",+ "timePeriod": {+ "from": f"{window_start.isoformat()}T00:00:00+00:00",+ "to": f"{window_end.isoformat()}T23:59:59+00:00",+ },+ "dataset": dataset,+ }++ if config.kind == "forecast":+ # Only the projection is wanted here — actual spend already lands in the cost tables.+ body["includeActualCost"] = False+ body["includeFreshPartialCost"] = False+ else:+ # Ascending usage date so rows arrive in watermark order across every page.+ dataset["sorting"] = [{"direction": "Ascending", "name": "UsageDate"}]++ return body+++class AzureCostManagementClient:+ """Minted-token ARM client for the Cost Management POST query API.++ The tracked session's retries are disabled (`Retry(total=0)`) because they never cover this+ source: the query API is a POST (excluded from the default retry's allowed methods) and Azure+ reports its throttle wait in vendor headers the transport can't read. Backoff is therefore+ handled once, here, rather than layered on top of the transport's.+ """++ def __init__(+ self,+ tenant_id: str,+ client_id: str,+ client_secret: str,+ logger: FilteringBoundLogger,+ sleep: Callable[[float], None] = time.sleep,+ ) -> None:+ self._tenant_id = tenant_id+ self._client_id = client_id+ self._client_secret = client_secret+ self._logger = logger+ self._sleep = sleep+ self._token: Optional[str] = None+ redact = tuple(value for value in (client_secret,) if value)+ # The token exchange body carries the client secret and returns a bearer token, neither of+ # which the name-based scrubbers recognise — keep it out of sample capture entirely.+ self._auth_session = make_tracked_session(retry=Retry(total=0), redact_values=redact, capture=False)+ self._api_session = make_tracked_session(retry=Retry(total=0), redact_values=redact)++ def mint_token(self) -> str:+ url = f"{LOGIN_HOST}/{quote(self._tenant_id, safe='')}/oauth2/v2.0/token"+ response = self._auth_session.post(+ url,+ data={+ "grant_type": "client_credentials",+ "client_id": self._client_id,+ "client_secret": self._client_secret,+ "scope": MANAGEMENT_TOKEN_SCOPE,+ },+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ if not response.ok:+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {LOGIN_HOST}{_error_description(response)}",+ response=response,+ )+ token = response.json().get("access_token")+ if not token:+ raise requests.HTTPError(f"Azure AD returned no access token for url: {LOGIN_HOST}", response=response)+ self._token = token+ return token++ def _token_or_mint(self) -> str:+ return self._token or self.mint_token()++ def request(self, method: str, url: str, body: Optional[dict[str, Any]] = None) -> Any:+ attempt = 0+ reminted = False++ while True:+ headers = {+ "Authorization": f"Bearer {self._token_or_mint()}",+ "X-Ms-Command-Name": COMMAND_NAME,+ }+ if method == "POST":+ response = self._api_session.post(+ url, json=body or {}, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS+ )+ else:+ response = self._api_session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ # Tokens last ~1h; a long backfill can outlive one, so re-mint once before giving up.+ if response.status_code == 401 and not reminted:+ reminted = True+ self._token = None+ self.mint_token()+ continue++ if response.status_code == 429 or response.status_code >= 500:+ attempt += 1+ if attempt >= MAX_RETRY_ATTEMPTS:+ raise AzureCostManagementRetryableError(+ f"Azure Cost Management error (retryable): status={response.status_code}, url={url}"+ )+ delay = _backoff_seconds(response, attempt)+ self._logger.debug(+ f"Azure Cost Management throttled: status={response.status_code}, sleeping {delay}s (attempt {attempt})"+ )+ self._sleep(delay)+ continue++ if not response.ok:+ self._logger.error(+ f"Azure Cost Management error: status={response.status_code}, body={response.text}, url={url}"+ )+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {MANAGEMENT_HOST}{_error_description(response)}",+ response=response,+ )++ return response.json()+++def validate_credentials(+ tenant_id: str, client_id: str, client_secret: str, scope: str, api_version: str+) -> tuple[bool, Optional[str]]:+ """Mint a token, then probe the scope's dimension catalog — the cheapest call that proves both+ the service principal is genuine and that it holds Cost Management Reader on the scope."""+ try:+ normalized_scope = normalize_scope(scope)+ except ValueError as error:+ return False, str(error)++ client = AzureCostManagementClient(tenant_id, client_id, client_secret, structlog.get_logger(__name__))+ try:+ client.mint_token()+ except Exception:+ return False, "Could not authenticate with Azure AD. Check the tenant ID, client ID, and client secret."++ try:+ client.request("GET", _endpoint_url(normalized_scope, "dimensions", api_version))+ except Exception:+ return (+ False,+ "Could not read Azure Cost Management for that scope. Check the scope path and that the service principal has the Cost Management Reader role on it.",+ )++ return True, None+++def get_rows(+ tenant_id: str,+ client_id: str,+ client_secret: str,+ scope: str,+ endpoint: str,+ start_date: str | None,+ api_version: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AzureCostManagementResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = AZURE_COST_MANAGEMENT_ENDPOINTS[endpoint]+ normalized_scope = normalize_scope(scope)+ client = AzureCostManagementClient(tenant_id, client_id, client_secret, logger)++ if config.kind == "dimensions":+ payload = client.request("GET", _endpoint_url(normalized_scope, "dimensions", api_version))+ rows = rows_from_dimensions(payload, normalized_scope)+ if rows:+ yield rows+ return++ today = datetime.now(tz=UTC).date()+ if config.kind == "forecast":+ windows = [SyncWindow(start=today, end=today + timedelta(days=FORECAST_HORIZON_DAYS))]+ else:+ window_start = resolve_window_start(+ should_use_incremental_field, db_incremental_field_last_value, start_date, today+ )+ windows = build_windows(window_start, today)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ pending_next_link: Optional[str] = None+ if resume is not None and resume.window_start:+ windows = [window for window in windows if window.start.isoformat() >= resume.window_start]+ pending_next_link = resume.next_link+ logger.debug(f"Azure Cost Management: resuming {endpoint} from {resume.window_start}")++ url = _endpoint_url(normalized_scope, "forecast" if config.kind == "forecast" else "query", api_version)++ for index, window in enumerate(windows):+ body = build_query_body(config, window.start, window.end)+ next_link = pending_next_link+ pending_next_link = None++ while True:+ payload = client.request("POST", _validated_next_link(next_link) if next_link else url, body)+ rows, next_link = rows_from_query_result(payload, normalized_scope)+ if rows:+ yield rows++ # Checkpoint AFTER yielding, so a crash re-yields the last page instead of skipping it.+ if not next_link:+ break+ resumable_source_manager.save_state(+ AzureCostManagementResumeConfig(window_start=window.start.isoformat(), next_link=next_link)+ )++ if index + 1 < len(windows):+ resumable_source_manager.save_state(+ AzureCostManagementResumeConfig(window_start=windows[index + 1].start.isoformat())+ )+++def azure_cost_management_source(+ tenant_id: str,+ client_id: str,+ client_secret: str,+ scope: str,+ endpoint: str,+ start_date: str | None,+ api_version: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AzureCostManagementResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = AZURE_COST_MANAGEMENT_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ tenant_id=tenant_id,+ client_id=client_id,+ client_secret=client_secret,+ scope=scope,+ endpoint=endpoint,+ start_date=start_date,+ api_version=api_version,+ 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_keys=config.partition_keys,+ partition_mode=config.partition_mode,+ partition_format=config.partition_format,+ # Windows are walked oldest-first and each query is sorted ascending on UsageDate.+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/canonical_descriptions.pynew file mode 100644index 000000000000..4635aa1db384--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/canonical_descriptions.py@@ -0,0 +1,84 @@+"""Canonical, documentation-sourced descriptions for Azure Cost Management endpoints and columns.++Sourced from the official Microsoft.CostManagement REST reference+(https://learn.microsoft.com/en-us/rest/api/cost-management/). Keyed by the endpoint names in+`settings.py` `AZURE_COST_MANAGEMENT_ENDPOINTS`, which match the `ExternalDataSchema.name` of a+synced table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_QUERY_DOCS_URL = "https://learn.microsoft.com/en-us/rest/api/cost-management/query/usage"+_FORECAST_DOCS_URL = "https://learn.microsoft.com/en-us/rest/api/cost-management/forecast/usage"+_DIMENSIONS_DOCS_URL = "https://learn.microsoft.com/en-us/rest/api/cost-management/dimensions/list"++_SHARED_COST_COLUMNS = {+ "cost": "Summed cost for the day and grouping, in the scope's billing currency.",+ "usage_date": "Day the usage was metered, as YYYY-MM-DD.",+ "currency": "Billing currency the cost is reported in.",+ "scope": "Azure Resource Manager scope the cost was queried for (for example a subscription or billing account path).",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "cost_by_service": {+ "description": "Daily actual Azure cost, grouped by service. Actual cost reflects what was charged on the invoice, including one-off reservation purchases in the month they were bought.",+ "docs_url": _QUERY_DOCS_URL,+ "columns": {+ **_SHARED_COST_COLUMNS,+ "service_name": "Azure service the cost was incurred on, such as Virtual Machines or Storage.",+ },+ },+ "cost_by_resource_group": {+ "description": "Daily actual Azure cost, grouped by resource group — the usual unit for team or environment chargeback.",+ "docs_url": _QUERY_DOCS_URL,+ "columns": {+ **_SHARED_COST_COLUMNS,+ "resource_group_name": "Resource group the cost was incurred in.",+ },+ },+ "cost_by_resource": {+ "description": "Daily actual Azure cost, grouped by individual resource. The finest grain the query API reports, so it is also the widest table.",+ "docs_url": _QUERY_DOCS_URL,+ "columns": {+ **_SHARED_COST_COLUMNS,+ "resource_id": "Full Azure Resource Manager ID of the resource the cost was incurred on.",+ },+ },+ "amortized_cost_by_service": {+ "description": "Daily amortized Azure cost, grouped by service. Amortized cost spreads reservation and savings-plan purchases evenly across the term they cover, so daily spend reflects usage rather than purchase timing.",+ "docs_url": _QUERY_DOCS_URL,+ "columns": {+ **_SHARED_COST_COLUMNS,+ "service_name": "Azure service the cost was incurred on, such as Virtual Machines or Storage.",+ },+ },+ "forecast": {+ "description": "Azure's projection of upcoming daily cost per service, based on recent usage. Recomputed in full on every sync.",+ "docs_url": _FORECAST_DOCS_URL,+ "columns": {+ **_SHARED_COST_COLUMNS,+ "service_name": "Azure service the forecast cost is attributed to.",+ "cost_status": "Whether the row is a forecast or an actual charge.",+ },+ },+ "dimensions": {+ "description": "Dimensions available for grouping and filtering cost on this scope, with the values observed on each.",+ "docs_url": _DIMENSIONS_DOCS_URL,+ "columns": {+ "scope": "Azure Resource Manager scope the dimensions were listed for.",+ "id": "Full Azure Resource Manager ID of the dimension.",+ "name": "Dimension name, as used in a query's grouping or filter (for example ResourceGroupName).",+ "type": "Resource type of the dimension entry.",+ "category": "Category the dimension belongs to.",+ "description": "Description of what the dimension represents.",+ "filter_enabled": "Whether cost queries can filter on this dimension.",+ "grouping_enabled": "Whether cost queries can group by this dimension.",+ "usage_start": "Start of the period the returned dimension values were observed over.",+ "usage_end": "End of the period the returned dimension values were observed over.",+ "total": "Total number of values the dimension has over that period.",+ "data": "Sample of the dimension's values over that period.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/settings.pynew file mode 100644index 000000000000..6b14ba88b3fc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/settings.py@@ -0,0 +1,131 @@+from dataclasses import field+from typing import Literal, Optional++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (+ PartitionFormat,+ PartitionMode,+)+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Azure restates cost for several days after usage lands (late meters, credits, reservations), so+# every incremental run re-reads a trailing week and merge dedupes the overlap on the primary key.+COST_LOOKBACK_SECONDS = 7 * 24 * 60 * 60++EndpointKind = Literal["query", "forecast", "dimensions"]++_USAGE_DATE_INCREMENTAL_FIELD: IncrementalField = {+ "label": "usage_date",+ "type": IncrementalFieldType.Date,+ "field": "usage_date",+ "field_type": IncrementalFieldType.Date,+}+++@frozen+class AzureCostManagementEndpointConfig:+ name: str+ kind: EndpointKind+ # Merge key. Every cost row is one (scope, day, dimension) bucket, so the natural key is the+ # composite — a service name repeats on every day, and a day repeats for every service.+ primary_keys: list[str]+ # Query/forecast only: `ActualCost` bills what was charged, `AmortizedCost` spreads reservation+ # and savings-plan purchases across the term they cover.+ export_type: Optional[str] = None+ # Dimensions the query groups by, using Azure's dimension names. Each becomes a snake_cased+ # column on the row (`ServiceName` -> `service_name`).+ grouping: list[str] = field(default_factory=list)+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Only the cost queries take a server-side date window (`timeframe: Custom` + `timePeriod`), so+ # only they can sync incrementally. Forecast is forward-looking and dimensions is a catalog.+ supports_incremental: bool = False+ # `usage_date` is the day the usage was metered — it never moves once a row exists, unlike the+ # cost amount, which Azure restates.+ partition_keys: Optional[list[str]] = None+ partition_mode: Optional[PartitionMode] = None+ partition_format: Optional[PartitionFormat] = None+ default_incremental_lookback_seconds: Optional[int] = None+ description: Optional[str] = None+++def _cost_endpoint(+ name: str,+ export_type: str,+ dimension: str,+ dimension_column: str,+ description: str,+) -> AzureCostManagementEndpointConfig:+ return AzureCostManagementEndpointConfig(+ name=name,+ kind="query",+ export_type=export_type,+ grouping=[dimension],+ primary_keys=["scope", "usage_date", dimension_column],+ incremental_fields=[_USAGE_DATE_INCREMENTAL_FIELD],+ supports_incremental=True,+ partition_keys=["usage_date"],+ partition_mode="datetime",+ partition_format="month",+ default_incremental_lookback_seconds=COST_LOOKBACK_SECONDS,+ description=description,+ )+++AZURE_COST_MANAGEMENT_ENDPOINTS: dict[str, AzureCostManagementEndpointConfig] = {+ "cost_by_service": _cost_endpoint(+ name="cost_by_service",+ export_type="ActualCost",+ dimension="ServiceName",+ dimension_column="service_name",+ description="Daily actual cost per Azure service. Supports incremental sync on the usage date.",+ ),+ "cost_by_resource_group": _cost_endpoint(+ name="cost_by_resource_group",+ export_type="ActualCost",+ dimension="ResourceGroupName",+ dimension_column="resource_group_name",+ description="Daily actual cost per resource group. Supports incremental sync on the usage date.",+ ),+ "cost_by_resource": _cost_endpoint(+ name="cost_by_resource",+ export_type="ActualCost",+ dimension="ResourceId",+ dimension_column="resource_id",+ description="Daily actual cost per resource. The widest table — one row per resource per day.",+ ),+ "amortized_cost_by_service": _cost_endpoint(+ name="amortized_cost_by_service",+ export_type="AmortizedCost",+ dimension="ServiceName",+ dimension_column="service_name",+ description="Daily amortized cost per Azure service, spreading reservation and savings-plan purchases across their term.",+ ),+ # Forward-looking projection for the rest of the current window. Azure recomputes the whole+ # forecast on every call, so it is replaced wholesale each sync rather than merged forward.+ "forecast": AzureCostManagementEndpointConfig(+ name="forecast",+ kind="forecast",+ export_type="ActualCost",+ grouping=["ServiceName"],+ primary_keys=["scope", "usage_date", "service_name"],+ partition_keys=["usage_date"],+ partition_mode="datetime",+ partition_format="month",+ description="Azure's forecast of upcoming daily cost per service. Full refresh only.",+ ),+ # Catalog of the dimensions this scope can be grouped or filtered by, with each dimension's+ # observed values. Useful for building your own cost queries on top of the cost tables.+ "dimensions": AzureCostManagementEndpointConfig(+ name="dimensions",+ kind="dimensions",+ primary_keys=["scope", "name"],+ description="Dimensions available for grouping and filtering cost on this scope. Full refresh only.",+ ),+}++ENDPOINTS = tuple(AZURE_COST_MANAGEMENT_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in AZURE_COST_MANAGEMENT_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/source.pyindex 9e666384cdbe..39d7360171a0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/source.py@@ -1,13 +1,30 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.azure_cost_management.azure_cost_management import (+ AzureCostManagementResumeConfig,+ azure_cost_management_source,+ validate_credentials as validate_azure_cost_management_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.azure_cost_management.settings import (+ AZURE_COST_MANAGEMENT_ENDPOINTS,+)+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.azurecostmanagement import (AzureCostManagementSourceConfig,)@@ -15,18 +32,174 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AzureCostManagementSource(SimpleSource[AzureCostManagementSourceConfig]):+class AzureCostManagementSource(ResumableSource[AzureCostManagementSourceConfig, AzureCostManagementResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("2025-03-01",)+ default_version = "2025-03-01"+ api_docs_url = "https://learn.microsoft.com/en-us/rest/api/cost-management/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AZURECOSTMANAGEMENT+ @property+ def connection_host_fields(self) -> list[str]:+ # `tenant_id` picks the Azure AD directory the stored client secret is exchanged against+ # (a multi-tenant app registration will mint a token in another directory), and `scope`+ # picks the ARM path the resulting token is spent on. Retargeting either would let an+ # editor point a preserved secret at a directory or subscription/billing account it wasn't+ # connected to, so both must force credential re-entry.+ return ["tenant_id", "scope"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.AZURE_COST_MANAGEMENT,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="Microsoft Azure Cost Management",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Pull your daily Azure spend into the PostHog Data warehouse, broken down by service, resource group, and resource.++Register an app in Microsoft Entra ID, create a client secret for it, and give its service principal the `Cost Management Reader` role on the scope you want to sync. Then enter the directory (tenant) ID, the application (client) ID, and the secret value.++The scope is the Azure Resource Manager path to read cost for, without a leading slash — for example `subscriptions/00000000-0000-0000-0000-000000000000` for one subscription, or `providers/Microsoft.Billing/billingAccounts/1234567` for an enterprise billing account.""",iconPath="/static/services/azure_cost_management.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/azure-cost-management",+ keywords=["azure", "finops", "cloud cost", "billing"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="tenant_id",+ label="Directory (tenant) ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="00000000-0000-0000-0000-000000000000",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_id",+ label="Application (client) ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="00000000-0000-0000-0000-000000000000",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="scope",+ label="Scope",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="subscriptions/00000000-0000-0000-0000-000000000000",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="start_date",+ label="Start date (historical backfill)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="YYYY-MM-DD",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.azure_cost_management.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A wrong tenant, client id, or expired secret fails the client-credentials exchange, and+ # no amount of retrying fixes a credential.+ "400 Client Error: Bad Request for url: https://login.microsoftonline.com": "Azure AD rejected the service principal credentials. Check the directory (tenant) ID, application (client) ID, and client secret, then reconnect.",+ "401 Client Error: Unauthorized for url: https://login.microsoftonline.com": "Azure AD rejected the service principal credentials. Check the application (client) ID and client secret, then reconnect.",+ "401 Client Error: Unauthorized for url: https://management.azure.com": "Azure rejected the access token for Cost Management. Check that the app registration is still enabled, then reconnect.",+ "403 Client Error: Forbidden for url: https://management.azure.com": "The service principal cannot read Cost Management on this scope. Give it the Cost Management Reader role on the scope, then reconnect.",+ }++ def get_retryable_errors(self) -> set[str]:+ return {"Azure Cost Management error (retryable)"}++ def get_schemas(+ self,+ config: AzureCostManagementSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint_config.name,+ supports_incremental=endpoint_config.supports_incremental,+ # Azure restates a day's cost after the fact, so append would materialize a second+ # row every time an already-imported day changes — these tables are merge-only.+ supports_append=False,+ incremental_fields=endpoint_config.incremental_fields,+ description=endpoint_config.description,+ default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,+ )+ for endpoint_config in AZURE_COST_MANAGEMENT_ENDPOINTS.values()+ ]++ 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: AzureCostManagementSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_azure_cost_management_credentials(+ tenant_id=config.tenant_id,+ client_id=config.client_id,+ client_secret=config.client_secret,+ scope=config.scope,+ api_version=self.resolve_api_version(api_version),+ )++ def get_resumable_source_manager(+ self, inputs: SourceInputs+ ) -> ResumableSourceManager[AzureCostManagementResumeConfig]:+ return ResumableSourceManager[AzureCostManagementResumeConfig](inputs, AzureCostManagementResumeConfig)++ def source_for_pipeline(+ self,+ config: AzureCostManagementSourceConfig,+ resumable_source_manager: ResumableSourceManager[AzureCostManagementResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return azure_cost_management_source(+ tenant_id=config.tenant_id,+ client_id=config.client_id,+ client_secret=config.client_secret,+ scope=config.scope,+ endpoint=inputs.schema_name,+ start_date=config.start_date,+ api_version=self.resolve_api_version(inputs.api_version),+ 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/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/tests/test_azure_cost_management.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/tests/test_azure_cost_management.pynew file mode 100644index 000000000000..4aa02d29a998--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/tests/test_azure_cost_management.py@@ -0,0 +1,731 @@+from collections.abc import Iterable+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional, cast++import pytest+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.azure_cost_management.azure_cost_management import (+ LOGIN_HOST,+ MANAGEMENT_HOST,+ AzureCostManagementClient,+ AzureCostManagementResumeConfig,+ AzureCostManagementRetryableError,+ _parse_usage_date,+ _retry_after_seconds,+ _snake_case,+ _validated_next_link,+ azure_cost_management_source,+ build_query_body,+ build_windows,+ get_rows,+ normalize_scope,+ resolve_window_start,+ rows_from_dimensions,+ rows_from_query_result,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.azure_cost_management.settings import (+ AZURE_COST_MANAGEMENT_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.sync_window import SyncWindow++TRANSPORT_MODULE = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.azure_cost_management.azure_cost_management"+)+++class _FakeResponse:+ def __init__(+ self,+ status_code: int = 200,+ json_data: Any = None,+ headers: Optional[dict[str, str]] = None,+ text: str = "",+ reason: str = "",+ ) -> None:+ self.status_code = status_code+ self._json_data = json_data+ self.headers = headers or {}+ self.text = text+ self.reason = reason++ @property+ def ok(self) -> bool:+ return self.status_code < 400++ def json(self) -> Any:+ if isinstance(self._json_data, Exception):+ raise self._json_data+ return self._json_data+++class _FakeSession:+ """Serves queued responses in order and records every call the client made."""++ def __init__(self, responses: list[_FakeResponse]) -> None:+ self._responses = list(responses)+ self.calls: list[tuple[str, str, dict[str, Any]]] = []++ def _pop(self, method: str, url: str, kwargs: dict[str, Any]) -> _FakeResponse:+ self.calls.append((method, url, kwargs))+ if not self._responses:+ raise AssertionError(f"unexpected extra request: {method} {url}")+ return self._responses.pop(0)++ def post(self, url: str, **kwargs: Any) -> _FakeResponse:+ return self._pop("POST", url, kwargs)++ def get(self, url: str, **kwargs: Any) -> _FakeResponse:+ return self._pop("GET", url, kwargs)+++class _FakeResumeManager(ResumableSourceManager[AzureCostManagementResumeConfig]):+ def __init__(self, state: AzureCostManagementResumeConfig | None = None) -> None:+ self.state = state+ self.saved: list[AzureCostManagementResumeConfig] = []++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> AzureCostManagementResumeConfig | None:+ return self.state++ def save_state(self, data: AzureCostManagementResumeConfig) -> None:+ self.saved.append(data)+++def _token_response() -> _FakeResponse:+ return _FakeResponse(200, {"access_token": "access-token", "expires_in": 3599})+++def _query_response(+ rows: list[list[Any]], columns: Optional[list[str]] = None, next_link: Optional[str] = None+) -> _FakeResponse:+ return _FakeResponse(+ 200,+ {+ "properties": {+ "columns": [+ {"name": name, "type": "String"} for name in (columns or ["Cost", "UsageDate", "ServiceName"])+ ],+ "rows": rows,+ "nextLink": next_link,+ }+ },+ )+++def _client(session: _FakeSession, sleeps: Optional[list[float]] = None) -> AzureCostManagementClient:+ def _sleep(seconds: float) -> None:+ if sleeps is not None:+ sleeps.append(seconds)++ with mock.patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ return AzureCostManagementClient("tenant", "client", "secret", mock.MagicMock(), sleep=_sleep)+++def _collect(rows: Iterable[Any]) -> list[list[dict[str, Any]]]:+ return list(cast("Iterable[Any]", rows))+++class TestSnakeCase:+ @parameterized.expand(+ [+ ("ServiceName", "service_name"),+ ("ResourceGroupName", "resource_group_name"),+ ("ResourceId", "resource_id"),+ ("UsageDate", "usage_date"),+ ("Cost", "cost"),+ ("CostUSD", "cost_usd"),+ ("PreTaxCost", "pre_tax_cost"),+ ]+ )+ def test_column_names(self, azure_name: str, expected: str) -> None:+ assert _snake_case(azure_name) == expected+++class TestNormalizeScope:+ @parameterized.expand(+ [+ ("/subscriptions/abc/", "subscriptions/abc"),+ (" subscriptions/abc ", "subscriptions/abc"),+ (+ "providers/Microsoft.Billing/billingAccounts/123",+ "providers/Microsoft.Billing/billingAccounts/123",+ ),+ ]+ )+ def test_trims_to_arm_path(self, raw: str, expected: str) -> None:+ assert normalize_scope(raw) == expected++ @parameterized.expand(+ [+ ("empty", ""),+ ("only_slashes", "///"),+ # A scope carrying its own host would repoint our credentialed requests at it.+ ("absolute_url", "https://evil.example/subscriptions/abc"),+ ("protocol_relative", "//evil.example/subscriptions/abc"),+ # A `?`/`#` would push the appended Cost Management path into the query/fragment,+ # leaving the credentialed request pointed at an arbitrary ARM operation.+ ("query_delimiter", "subscriptions/abc/resources?api-version=2021-04-01"),+ ("fragment_delimiter", "subscriptions/abc/resources#"),+ ("backslash", "subscriptions\\abc"),+ ]+ )+ def test_rejects_non_path_scopes(self, _name: str, raw: str) -> None:+ with pytest.raises(ValueError):+ normalize_scope(raw)+++class TestValidatedNextLink:+ def test_accepts_arm_link(self) -> None:+ link = f"{MANAGEMENT_HOST}/subscriptions/abc/providers/Microsoft.CostManagement/query?$skiptoken=x"+ assert _validated_next_link(link) == link++ @parameterized.expand(+ [+ ("other_host", "https://evil.example/next"),+ ("lookalike_host", "https://management.azure.com.evil.example/next"),+ ("http_scheme", "http://management.azure.com/next"),+ ]+ )+ def test_rejects_off_host_link(self, _name: str, link: str) -> None:+ with pytest.raises(ValueError):+ _validated_next_link(link)+++class TestParseUsageDate:+ @parameterized.expand(+ [+ ("int_yyyymmdd", 20240115, "2024-01-15"),+ ("str_yyyymmdd", "20240115", "2024-01-15"),+ ("iso_datetime", "2024-01-15T00:00:00", "2024-01-15"),+ ("iso_datetime_zulu", "2024-01-15T00:00:00Z", "2024-01-15"),+ ("iso_date", "2024-01-15", "2024-01-15"),+ ("none", None, None),+ ("unparseable", "not-a-date", "not-a-date"),+ ]+ )+ def test_normalizes_to_iso_day(self, _name: str, raw: Any, expected: Any) -> None:+ assert _parse_usage_date(raw) == expected+++class TestRowsFromQueryResult:+ def test_zips_columns_and_rows_and_stamps_scope(self) -> None:+ payload = {+ "properties": {+ "columns": [{"name": "Cost"}, {"name": "UsageDate"}, {"name": "ServiceName"}, {"name": "Currency"}],+ "rows": [[1.5, 20240115, "Storage", "USD"], [2.5, 20240116, "Virtual Machines", "USD"]],+ "nextLink": None,+ }+ }++ rows, next_link = rows_from_query_result(payload, "subscriptions/abc")++ assert next_link is None+ assert rows == [+ {+ "cost": 1.5,+ "usage_date": "2024-01-15",+ "service_name": "Storage",+ "currency": "USD",+ "scope": "subscriptions/abc",+ },+ {+ "cost": 2.5,+ "usage_date": "2024-01-16",+ "service_name": "Virtual Machines",+ "currency": "USD",+ "scope": "subscriptions/abc",+ },+ ]++ def test_returns_next_link_when_present(self) -> None:+ payload = {"properties": {"columns": [], "rows": [], "nextLink": f"{MANAGEMENT_HOST}/next"}}+ assert rows_from_query_result(payload, "s")[1] == f"{MANAGEMENT_HOST}/next"++ @parameterized.expand([("not_a_dict", []), ("missing_properties", {}), ("null_properties", {"properties": None})])+ def test_tolerates_unexpected_payloads(self, _name: str, payload: Any) -> None:+ assert rows_from_query_result(payload, "s") == ([], None)+++class TestRowsFromDimensions:+ def test_flattens_properties(self) -> None:+ payload = {+ "value": [+ {+ "id": "/subscriptions/abc/providers/Microsoft.CostManagement/dimensions/ResourceGroupName",+ "name": "ResourceGroupName",+ "type": "Microsoft.CostManagement/dimensions",+ "properties": {+ "category": "ResourceGroupName",+ "description": "Resource group",+ "filterEnabled": True,+ "groupingEnabled": True,+ "total": 2,+ "data": ["rg-a", "rg-b"],+ },+ }+ ]+ }++ rows = rows_from_dimensions(payload, "subscriptions/abc")++ assert len(rows) == 1+ assert rows[0]["scope"] == "subscriptions/abc"+ assert rows[0]["name"] == "ResourceGroupName"+ assert rows[0]["grouping_enabled"] is True+ assert rows[0]["data"] == ["rg-a", "rg-b"]++ def test_tolerates_missing_properties(self) -> None:+ assert rows_from_dimensions({"value": [{"name": "X"}]}, "s")[0]["category"] is None+++class TestBuildWindows:+ def test_single_window_for_short_range(self) -> None:+ assert build_windows(date(2024, 1, 1), date(2024, 1, 10)) == [+ SyncWindow(start=date(2024, 1, 1), end=date(2024, 1, 10))+ ]++ def test_splits_at_the_api_max_range(self) -> None:+ windows = build_windows(date(2023, 1, 1), date(2024, 6, 30))++ assert windows == [+ SyncWindow(start=date(2023, 1, 1), end=date(2023, 12, 31)),+ SyncWindow(start=date(2024, 1, 1), end=date(2024, 6, 30)),+ ]++ def test_windows_are_contiguous_and_cover_the_range(self) -> None:+ windows = build_windows(date(2020, 1, 1), date(2024, 1, 1))++ assert windows[0].start == date(2020, 1, 1)+ assert windows[-1].end == date(2024, 1, 1)+ for earlier, later in zip(windows, windows[1:]):+ assert later.start == earlier.end + timedelta(days=1)++ def test_empty_when_start_after_end(self) -> None:+ assert build_windows(date(2024, 2, 1), date(2024, 1, 1)) == []+++class TestResolveWindowStart:+ TODAY = date(2024, 6, 1)++ def test_incremental_watermark_wins(self) -> None:+ assert resolve_window_start(True, "2024-05-20", "2020-01-01", self.TODAY) == date(+ 2024, 5, 20+ ) # the watermark day is re-pulled, since Azure restates it++ def test_future_watermark_is_clamped_to_today(self) -> None:+ assert resolve_window_start(True, "2030-01-01", None, self.TODAY) == self.TODAY++ def test_falls_back_to_configured_start_date(self) -> None:+ assert resolve_window_start(False, "2024-05-20", "2023-03-04", self.TODAY) == date(2023, 3, 4)++ def test_falls_back_to_default_history_window(self) -> None:+ assert resolve_window_start(False, None, None, self.TODAY) == self.TODAY - timedelta(days=365)++ def test_unparseable_watermark_falls_through(self) -> None:+ assert resolve_window_start(True, "garbage", "2023-03-04", self.TODAY) == date(2023, 3, 4)+++class TestBuildQueryBody:+ def test_cost_query_windows_and_sorts_ascending(self) -> None:+ body = build_query_body(AZURE_COST_MANAGEMENT_ENDPOINTS["cost_by_service"], date(2024, 1, 1), date(2024, 1, 31))++ assert body["type"] == "ActualCost"+ assert body["timeframe"] == "Custom"+ assert body["timePeriod"]["from"].startswith("2024-01-01")+ assert body["timePeriod"]["to"].startswith("2024-01-31")+ assert body["dataset"]["granularity"] == "Daily"+ assert body["dataset"]["grouping"] == [{"type": "Dimension", "name": "ServiceName"}]+ assert body["dataset"]["sorting"] == [{"direction": "Ascending", "name": "UsageDate"}]++ def test_amortized_query_uses_amortized_export_type(self) -> None:+ body = build_query_body(+ AZURE_COST_MANAGEMENT_ENDPOINTS["amortized_cost_by_service"], date(2024, 1, 1), date(2024, 1, 31)+ )+ assert body["type"] == "AmortizedCost"++ def test_forecast_excludes_actuals_and_does_not_sort(self) -> None:+ body = build_query_body(AZURE_COST_MANAGEMENT_ENDPOINTS["forecast"], date(2024, 1, 1), date(2024, 1, 31))++ assert body["includeActualCost"] is False+ assert body["includeFreshPartialCost"] is False+ assert "sorting" not in body["dataset"]+++class TestRetryAfterSeconds:+ @parameterized.expand(+ [+ ("standard", {"Retry-After": "30"}, 30.0),+ ("consumption", {"x-ms-ratelimit-microsoft.consumption-retry-after": "45"}, 45.0),+ ("client_type", {"x-ms-ratelimit-microsoft.costmanagement-clienttype-retry-after": "12"}, 12.0),+ ("entity", {"x-ms-ratelimit-microsoft.costmanagement-entity-retry-after": "7"}, 7.0),+ ("capped", {"Retry-After": "100000"}, 120.0),+ ("non_numeric", {"Retry-After": "Wed, 21 Oct 2015 07:28:00 GMT"}, None),+ ("absent", {}, None),+ ]+ )+ def test_reads_vendor_and_standard_headers(+ self, _name: str, headers: dict[str, str], expected: Optional[float]+ ) -> None:+ assert _retry_after_seconds(cast(Any, _FakeResponse(429, headers=headers))) == expected+++class TestClientMintToken:+ def test_returns_access_token(self) -> None:+ session = _FakeSession([_token_response()])+ assert _client(session).mint_token() == "access-token"+ assert session.calls[0][1].startswith(f"{LOGIN_HOST}/tenant/oauth2/v2.0/token")+ assert session.calls[0][2]["data"]["grant_type"] == "client_credentials"++ @parameterized.expand([(400,), (401,)])+ def test_credential_failure_raises_with_login_host(self, status: int) -> None:+ session = _FakeSession(+ [+ _FakeResponse(+ status,+ {"error": "invalid_client", "error_description": "Bad secret"},+ reason="Bad Request" if status == 400 else "Unauthorized",+ )+ ]+ )+ with pytest.raises(requests.HTTPError) as error:+ _client(session).mint_token()++ # The message shape is what `get_non_retryable_errors` matches on.+ assert LOGIN_HOST in str(error.value)+ assert "Bad secret" in str(error.value)++ def test_missing_access_token_raises(self) -> None:+ session = _FakeSession([_FakeResponse(200, {"token_type": "Bearer"})])+ with pytest.raises(requests.HTTPError):+ _client(session).mint_token()+++class TestClientRequest:+ def test_mints_a_token_and_sends_it_as_a_bearer(self) -> None:+ session = _FakeSession([_token_response(), _query_response([])])+ _client(session).request("POST", f"{MANAGEMENT_HOST}/q", {"a": 1})++ _method, _url, kwargs = session.calls[1]+ assert kwargs["headers"]["Authorization"] == "Bearer access-token"+ assert kwargs["headers"]["X-Ms-Command-Name"] == "PostHogDataWarehouse"+ assert kwargs["json"] == {"a": 1}++ def test_remints_once_on_401_then_succeeds(self) -> None:+ session = _FakeSession(+ [+ _token_response(),+ _FakeResponse(401, reason="Unauthorized"),+ _FakeResponse(200, {"access_token": "fresh-token"}),+ _query_response([[1, 20240101, "Storage"]]),+ ]+ )++ result = _client(session).request("POST", f"{MANAGEMENT_HOST}/q")++ assert result["properties"]["rows"] == [[1, 20240101, "Storage"]]+ assert session.calls[-1][2]["headers"]["Authorization"] == "Bearer fresh-token"++ def test_repeated_401_stops_after_one_remint(self) -> None:+ session = _FakeSession(+ [+ _token_response(),+ _FakeResponse(401, reason="Unauthorized"),+ _FakeResponse(200, {"access_token": "fresh-token"}),+ _FakeResponse(401, reason="Unauthorized"),+ ]+ )++ with pytest.raises(requests.HTTPError) as error:+ _client(session).request("POST", f"{MANAGEMENT_HOST}/q")++ assert "401 Client Error" in str(error.value)+ assert MANAGEMENT_HOST in str(error.value)++ @parameterized.expand([(429,), (500,), (503,)])+ def test_retries_transient_statuses_then_succeeds(self, status: int) -> None:+ sleeps: list[float] = []+ session = _FakeSession(+ [+ _token_response(),+ _FakeResponse(status, headers={"x-ms-ratelimit-microsoft.consumption-retry-after": "9"}),+ _query_response([]),+ ]+ )++ _client(session, sleeps).request("POST", f"{MANAGEMENT_HOST}/q")++ assert sleeps == [9.0]++ def test_exhausted_retries_raise_retryable_error(self) -> None:+ sleeps: list[float] = []+ session = _FakeSession([_token_response(), *[_FakeResponse(429) for _ in range(6)]])++ with pytest.raises(AzureCostManagementRetryableError):+ _client(session, sleeps).request("POST", f"{MANAGEMENT_HOST}/q")++ # Bounded: five sleeps then a raise, rather than an unbounded throttle loop.+ assert len(sleeps) == 5++ @parameterized.expand([(400,), (403,), (404,)])+ def test_permanent_client_errors_raise_http_error(self, status: int) -> None:+ session = _FakeSession(+ [+ _token_response(),+ _FakeResponse(status, {"error": {"code": "Denied", "message": "No access"}}, reason="Forbidden"),+ ]+ )++ with pytest.raises(requests.HTTPError) as error:+ _client(session).request("POST", f"{MANAGEMENT_HOST}/q")++ assert "No access" in str(error.value)+++class TestValidateCredentials:+ def test_valid_when_token_and_scope_probe_succeed(self) -> None:+ session = _FakeSession([_token_response(), _FakeResponse(200, {"value": []})])+ with mock.patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ assert validate_credentials("tenant", "client", "secret", "subscriptions/abc", "2025-03-01") == (True, None)++ def test_bad_scope_path_is_rejected_without_a_request(self) -> None:+ valid, message = validate_credentials("tenant", "client", "secret", "https://evil.example", "2025-03-01")++ assert valid is False+ assert message is not None++ def test_auth_failure_reports_credentials(self) -> None:+ session = _FakeSession([_FakeResponse(401, reason="Unauthorized")])+ with mock.patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ valid, message = validate_credentials("tenant", "client", "secret", "subscriptions/abc", "2025-03-01")++ assert valid is False+ assert message is not None and "Azure AD" in message++ def test_scope_failure_reports_role(self) -> None:+ session = _FakeSession([_token_response(), _FakeResponse(403, reason="Forbidden")])+ with mock.patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ valid, message = validate_credentials("tenant", "client", "secret", "subscriptions/abc", "2025-03-01")++ assert valid is False+ assert message is not None and "Cost Management Reader" in message+++def _run_rows(+ session: _FakeSession,+ endpoint: str,+ manager: _FakeResumeManager,+ start_date: str | None = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> list[list[dict[str, Any]]]:+ with mock.patch(f"{TRANSPORT_MODULE}.make_tracked_session", return_value=session):+ return _collect(+ get_rows(+ tenant_id="tenant",+ client_id="client",+ client_secret="secret",+ scope="/subscriptions/abc/",+ endpoint=endpoint,+ start_date=start_date,+ api_version="2025-03-01",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ )+++class TestGetRows:+ def setup_method(self) -> None:+ self.today = datetime.now(tz=UTC).date()++ def test_paginates_until_next_link_is_absent(self) -> None:+ next_link = f"{MANAGEMENT_HOST}/subscriptions/abc/providers/Microsoft.CostManagement/query?$skiptoken=abc"+ session = _FakeSession(+ [+ _token_response(),+ _query_response([[1.0, 20240101, "Storage"]], next_link=next_link),+ _query_response([[2.0, 20240102, "Storage"]]),+ ]+ )+ manager = _FakeResumeManager()++ batches = _run_rows(+ session, "cost_by_service", manager, start_date=(self.today - timedelta(days=2)).isoformat()+ )++ assert [len(batch) for batch in batches] == [1, 1]+ assert batches[0][0]["usage_date"] == "2024-01-01"+ # The second page is fetched from the returned link, not the base query URL.+ assert session.calls[2][1] == next_link+ # Checkpoint written after the first page is yielded, pointing at the page still to fetch.+ assert manager.saved == [+ AzureCostManagementResumeConfig(+ window_start=(self.today - timedelta(days=2)).isoformat(), next_link=next_link+ )+ ]++ def test_off_host_next_link_aborts_the_sync(self) -> None:+ session = _FakeSession(+ [+ _token_response(),+ _query_response([[1.0, 20240101, "Storage"]], next_link="https://evil.example/next"),+ ]+ )++ with pytest.raises(ValueError):+ _run_rows(+ session,+ "cost_by_service",+ _FakeResumeManager(),+ start_date=(self.today - timedelta(days=2)).isoformat(),+ )++ def test_checkpoints_between_windows(self) -> None:+ start = self.today - timedelta(days=400)+ session = _FakeSession([_token_response(), _query_response([[1.0, 20240101, "Storage"]]), _query_response([])])+ manager = _FakeResumeManager()++ _run_rows(session, "cost_by_service", manager, start_date=start.isoformat())++ expected_second_window_start = start + timedelta(days=365)+ assert manager.saved == [+ AzureCostManagementResumeConfig(window_start=expected_second_window_start.isoformat(), next_link=None)+ ]+ assert len(session.calls) == 3++ def test_resume_skips_windows_already_walked(self) -> None:+ start = self.today - timedelta(days=400)+ second_window_start = start + timedelta(days=365)+ session = _FakeSession([_token_response(), _query_response([[1.0, 20240101, "Storage"]])])+ manager = _FakeResumeManager(AzureCostManagementResumeConfig(window_start=second_window_start.isoformat()))++ _run_rows(session, "cost_by_service", manager, start_date=start.isoformat())++ # Only the un-walked window is requested.+ assert len(session.calls) == 2+ assert session.calls[1][2]["json"]["timePeriod"]["from"].startswith(second_window_start.isoformat())++ def test_resume_continues_from_the_saved_next_link(self) -> None:+ next_link = f"{MANAGEMENT_HOST}/subscriptions/abc/providers/Microsoft.CostManagement/query?$skiptoken=xyz"+ session = _FakeSession([_token_response(), _query_response([[1.0, 20240101, "Storage"]])])+ start = self.today - timedelta(days=2)+ manager = _FakeResumeManager(+ AzureCostManagementResumeConfig(window_start=start.isoformat(), next_link=next_link)+ )++ _run_rows(session, "cost_by_service", manager, start_date=start.isoformat())++ assert session.calls[1][1] == next_link++ def test_incremental_run_windows_from_the_watermark(self) -> None:+ watermark = self.today - timedelta(days=3)+ session = _FakeSession([_token_response(), _query_response([])])++ _run_rows(+ session,+ "cost_by_service",+ _FakeResumeManager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark.isoformat(),+ )++ assert session.calls[1][2]["json"]["timePeriod"]["from"].startswith(watermark.isoformat())++ def test_dimensions_is_a_single_get(self) -> None:+ session = _FakeSession(+ [_token_response(), _FakeResponse(200, {"value": [{"name": "ServiceName", "properties": {}}]})]+ )++ batches = _run_rows(session, "dimensions", _FakeResumeManager())++ assert batches == [+ [+ {+ "scope": "subscriptions/abc",+ "id": None,+ "name": "ServiceName",+ "type": None,+ "category": None,+ "description": None,+ "filter_enabled": None,+ "grouping_enabled": None,+ "usage_start": None,+ "usage_end": None,+ "total": None,+ "data": None,+ }+ ]+ ]+ assert session.calls[1][0] == "GET"+ assert "dimensions" in session.calls[1][1]++ def test_forecast_queries_a_forward_window(self) -> None:+ session = _FakeSession([_token_response(), _query_response([])])++ _run_rows(session, "forecast", _FakeResumeManager())++ method, url, kwargs = session.calls[1]+ assert method == "POST"+ assert "/forecast?" in url+ assert kwargs["json"]["timePeriod"]["from"].startswith(self.today.isoformat())+ assert kwargs["json"]["includeActualCost"] is False++ def test_empty_page_yields_nothing(self) -> None:+ session = _FakeSession([_token_response(), _query_response([])])++ assert (+ _run_rows(+ session,+ "cost_by_service",+ _FakeResumeManager(),+ start_date=(self.today - timedelta(days=2)).isoformat(),+ )+ == []+ )+++class TestAzureCostManagementSourceResponse:+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])+ def test_source_response_matches_endpoint_settings(self, endpoint: str) -> None:+ config = AZURE_COST_MANAGEMENT_ENDPOINTS[endpoint]++ response = azure_cost_management_source(+ tenant_id="tenant",+ client_id="client",+ client_secret="secret",+ scope="subscriptions/abc",+ endpoint=endpoint,+ start_date=None,+ api_version="2025-03-01",+ logger=mock.MagicMock(),+ resumable_source_manager=_FakeResumeManager(),+ )++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.partition_keys == config.partition_keys+ assert response.partition_mode == config.partition_mode+ # Windows are walked oldest-first and every query is sorted ascending on UsageDate.+ assert response.sort_mode == "asc"++ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])+ def test_primary_key_carries_the_scope_and_day(self, endpoint: str) -> None:+ # One source syncs one scope, but the scope is still keyed so a re-pointed source cannot+ # collide rows, and the day is keyed because every dimension repeats across days.+ primary_keys = AZURE_COST_MANAGEMENT_ENDPOINTS[endpoint].primary_keys++ assert "scope" in primary_keys+ assert len(primary_keys) == len(set(primary_keys))+ if endpoint != "dimensions":+ assert "usage_date" in primary_keysdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/tests/test_azure_cost_management_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/tests/test_azure_cost_management_source.pynew file mode 100644index 000000000000..a168d976d16b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/azure_cost_management/tests/test_azure_cost_management_source.py@@ -0,0 +1,257 @@+from typing import Any, Optional++import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.azure_cost_management.azure_cost_management import (+ AzureCostManagementResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.azure_cost_management.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.azure_cost_management.settings import (+ AZURE_COST_MANAGEMENT_ENDPOINTS,+ COST_LOOKBACK_SECONDS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.azure_cost_management.source import (+ AzureCostManagementSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ SourceCredentialsValidationResult,+)+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 SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.azurecostmanagement import (+ AzureCostManagementSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.azure_cost_management.source"++COST_ENDPOINTS = ("cost_by_service", "cost_by_resource_group", "cost_by_resource", "amortized_cost_by_service")+++def _source_inputs(schema_name: str = "cost_by_service", **overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": schema_name,+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestAzureCostManagementSource:+ def setup_method(self) -> None:+ self.source = AzureCostManagementSource()+ self.config = AzureCostManagementSourceConfig(+ tenant_id="tenant",+ client_id="client",+ client_secret="secret",+ scope="subscriptions/abc",+ start_date=None,+ )++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.AZURECOSTMANAGEMENT++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "AzureCostManagement"+ assert config.label == "Microsoft Azure Cost Management"+ assert config.category == DataWarehouseSourceCategory.FINANCE___ACCOUNTING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/azure-cost-management"+ assert [f.name for f in config.fields] == [+ "tenant_id",+ "client_id",+ "client_secret",+ "scope",+ "start_date",+ ]++ def test_source_is_released(self) -> None:+ # A truthy `unreleasedSource` hides the connector from users entirely.+ assert not self.source.get_source_config.unreleasedSource++ def test_client_secret_is_a_secret_password_field(self) -> None:+ field = next(f for f in self.source.get_source_config.fields if f.name == "client_secret")++ assert isinstance(field, SourceFieldInputConfig)+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ @pytest.mark.parametrize("field_name", ["tenant_id", "client_id", "scope"])+ def test_connection_fields_are_required_and_not_secret(self, field_name: str) -> None:+ field = next(f for f in self.source.get_source_config.fields if f.name == field_name)++ assert isinstance(field, SourceFieldInputConfig)+ assert field.required is True+ assert field.secret is False++ def test_start_date_is_optional(self) -> None:+ field = next(f for f in self.source.get_source_config.fields if f.name == "start_date")++ assert isinstance(field, SourceFieldInputConfig)+ assert field.required is False++ def test_connection_host_fields_force_secret_reentry_on_retarget(self) -> None:+ # `tenant_id` chooses the Azure AD directory the client secret is exchanged against and+ # `scope` chooses the ARM path the minted token is spent on, so changing either on an+ # existing source must require the secret to be re-entered rather than reusing the stored+ # one against a directory or billing scope it was never connected to.+ assert self.source.connection_host_fields == ["tenant_id", "scope"]++ def test_api_version_metadata(self) -> None:+ assert self.source.supported_versions == ("2025-03-01",)+ assert self.source.default_version == "2025-03-01"+ assert self.source.api_docs_url is not None and self.source.api_docs_url.startswith("https://")++ def test_lists_tables_without_credentials(self) -> None:+ # `get_schemas` walks a static endpoint catalog with no I/O, so public docs can render it.+ assert self.source.lists_tables_without_credentials is True+ assert {table["name"] for table in self.source.get_documented_tables()} == set(ENDPOINTS)++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1)++ assert [schema.name for schema in schemas] == list(ENDPOINTS)++ def test_get_schemas_filters_by_name(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["cost_by_service", "dimensions"])++ assert [schema.name for schema in schemas] == ["cost_by_service", "dimensions"]++ @pytest.mark.parametrize("endpoint", COST_ENDPOINTS)+ def test_cost_endpoints_sync_incrementally_on_the_usage_date(self, endpoint: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, team_id=1) if s.name == endpoint)++ assert schema.supports_incremental is True+ assert [f["field"] for f in schema.incremental_fields] == ["usage_date"]+ # Azure restates recent days, so each run re-reads a trailing window.+ assert schema.default_incremental_lookback_seconds == COST_LOOKBACK_SECONDS++ @pytest.mark.parametrize("endpoint", ["forecast", "dimensions"])+ def test_non_windowed_endpoints_are_full_refresh(self, endpoint: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, team_id=1) if s.name == endpoint)++ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ @pytest.mark.parametrize("endpoint", ENDPOINTS)+ def test_no_endpoint_supports_append(self, endpoint: str) -> None:+ # Appending a restated day would materialize a second row for it instead of updating it.+ schema = next(s for s in self.source.get_schemas(self.config, team_id=1) if s.name == endpoint)++ assert schema.supports_append is False++ @pytest.mark.parametrize(+ "observed_error",+ [+ "400 Client Error: Bad Request for url: https://login.microsoftonline.com — invalid_client",+ "401 Client Error: Unauthorized for url: https://login.microsoftonline.com",+ "401 Client Error: Unauthorized for url: https://management.azure.com",+ "403 Client Error: Forbidden for url: https://management.azure.com — no access",+ ],+ )+ def test_non_retryable_errors_match_credential_and_permission_failures(self, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "observed_error",+ [+ "Azure Cost Management error (retryable): status=429, url=https://management.azure.com/q",+ "500 Server Error for url: https://management.azure.com/q",+ ],+ )+ def test_non_retryable_errors_ignore_transient_failures(self, observed_error: str) -> None:+ assert not any(key in observed_error for key in self.source.get_non_retryable_errors())++ def test_throttle_exhaustion_is_reported_as_retryable(self) -> None:+ error = "Azure Cost Management error (retryable): status=429, url=https://management.azure.com/q"++ assert any(key in error for key in self.source.get_retryable_errors())++ @pytest.mark.parametrize("result", [(True, None), (False, "nope")])+ def test_validate_credentials_delegates_to_the_transport(self, result: SourceCredentialsValidationResult) -> None:+ with mock.patch(f"{SOURCE_MODULE}.validate_azure_cost_management_credentials", return_value=result) as probe:+ assert self.source.validate_credentials(self.config, team_id=1) == result++ assert probe.call_args.kwargs["scope"] == "subscriptions/abc"+ assert probe.call_args.kwargs["api_version"] == "2025-03-01"++ def test_get_resumable_source_manager_is_bound_to_the_resume_dataclass(self) -> None:+ manager = self.source.get_resumable_source_manager(_source_inputs())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is AzureCostManagementResumeConfig++ def test_source_for_pipeline_passes_config_and_schema_through(self) -> None:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ inputs = _source_inputs("cost_by_resource")++ with mock.patch(f"{SOURCE_MODULE}.azure_cost_management_source") as build_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = build_source.call_args.kwargs+ assert kwargs["endpoint"] == "cost_by_resource"+ assert kwargs["scope"] == "subscriptions/abc"+ assert kwargs["client_secret"] == "secret"+ assert kwargs["api_version"] == "2025-03-01"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_withholds_the_watermark_on_a_full_refresh(self) -> None:+ inputs = _source_inputs(should_use_incremental_field=False, db_incremental_field_last_value="2024-01-01")++ with mock.patch(f"{SOURCE_MODULE}.azure_cost_management_source") as build_source:+ self.source.source_for_pipeline(self.config, mock.MagicMock(spec=ResumableSourceManager), inputs)++ assert build_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_source_for_pipeline_forwards_the_watermark_on_an_incremental_run(self) -> None:+ inputs = _source_inputs(should_use_incremental_field=True, db_incremental_field_last_value="2024-01-01")++ with mock.patch(f"{SOURCE_MODULE}.azure_cost_management_source") as build_source:+ self.source.source_for_pipeline(self.config, mock.MagicMock(spec=ResumableSourceManager), inputs)++ assert build_source.call_args.kwargs["db_incremental_field_last_value"] == "2024-01-01"++ @pytest.mark.parametrize("pinned,expected", [(None, "2025-03-01"), ("2024-08-01", "2024-08-01")])+ def test_source_for_pipeline_honors_a_pinned_api_version(self, pinned: Optional[str], expected: str) -> None:+ inputs = _source_inputs(api_version=pinned)++ with mock.patch(f"{SOURCE_MODULE}.azure_cost_management_source") as build_source:+ self.source.source_for_pipeline(self.config, mock.MagicMock(spec=ResumableSourceManager), inputs)++ assert build_source.call_args.kwargs["api_version"] == expected++ @pytest.mark.parametrize("endpoint", ENDPOINTS)+ def test_canonical_descriptions_cover_every_endpoint(self, endpoint: str) -> None:+ entry = self.source.get_canonical_descriptions()[endpoint]++ assert entry["description"]+ assert str(entry["docs_url"]).startswith("https://")+ # Every column in the merge key is described, since those are the ones users join on.+ assert set(AZURE_COST_MANAGEMENT_ENDPOINTS[endpoint].primary_keys) <= set(entry["columns"])++ def test_canonical_descriptions_have_no_stale_endpoints(self) -> None:+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/azurecostmanagement.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/azurecostmanagement.pyindex d3e12d921f19..16dce806ae9a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/azurecostmanagement.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/azurecostmanagement.py@@ -6,4 +6,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AzureCostManagementSourceConfig(config.Config):- pass+ tenant_id: str+ client_id: str+ client_secret: str+ scope: str+ start_date: str | None = None