Skip to content

: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.

feat(data-warehouse): implement power_bi_admin source (#73765)

Tom Owers1aa46e2dd0e1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 00b468932587..57dab28f03ff 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -516,6 +516,7 @@ the row lists both.
| postgres | DB protocol | psycopg | ➖ |
| postmark | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| postscript | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| power_bi_admin | HTTP | requests | ✅ |
| prefect_cloud | HTTP | requests | ✅ |
| pretix | HTTP | requests | ✅ |
| printify | HTTP | requests | ✅ |
@@ -1245,7 +1246,6 @@ doesn't conflict with concurrent PRs.
- podium
- polygon
- poplar
-- power_bi_admin
- practicepanther
- preset
- prestashop
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/powerbiadmin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/powerbiadmin.py
index 5f00aecf3f0f..8ca7877e285b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/powerbiadmin.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/powerbiadmin.py
@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class PowerBiAdminSourceConfig(config.Config):
- pass
+ tenant_id: str
+ client_id: str
+ client_secret: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/canonical_descriptions.py
new file mode 100644
index 000000000000..6c1ae845e2de
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/canonical_descriptions.py
@@ -0,0 +1,156 @@
+"""Canonical, documentation-sourced descriptions for Power BI admin endpoints and columns.
+
+Sourced from the official Power BI Admin REST API reference
+(https://learn.microsoft.com/en-us/rest/api/power-bi/admin). Keyed by the endpoint names in
+`settings.py` `POWER_BI_ADMIN_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,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "activity_events": {
+ "description": "A single tenant audit event, such as viewing a report, exporting data, or changing a workspace.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/power-bi/admin/get-activity-events",
+ "columns": {
+ "Id": "Unique identifier for the activity event.",
+ "RecordType": "Numeric audit record type of the event.",
+ "CreationTime": "UTC time the activity happened.",
+ "Operation": "Name of the operation performed, for example ViewReport or ExportReport.",
+ "OrganizationId": "Identifier of the Entra ID tenant the event belongs to.",
+ "UserType": "Type of user that performed the activity.",
+ "UserKey": "Stable internal key of the user that performed the activity.",
+ "UserId": "Email address or service principal identifier of the user that performed the activity.",
+ "ClientIP": "IP address the request came from.",
+ "UserAgent": "User agent string of the client that made the request.",
+ "Activity": "Friendly name of the activity performed.",
+ "IsSuccess": "Whether the operation completed successfully.",
+ "RequestId": "Identifier of the request that produced the event.",
+ "ActivityId": "Identifier correlating events from the same user action.",
+ "ItemName": "Name of the item the activity was performed on.",
+ "WorkSpaceName": "Name of the workspace the item belongs to.",
+ "WorkspaceId": "Identifier of the workspace the item belongs to.",
+ "ObjectId": "Identifier of the object the activity targeted.",
+ "DatasetName": "Name of the semantic model involved in the activity.",
+ "DatasetId": "Identifier of the semantic model involved in the activity.",
+ "ReportName": "Name of the report involved in the activity.",
+ "ReportId": "Identifier of the report involved in the activity.",
+ "ReportType": "Type of report involved in the activity, for example PowerBIReport or PaginatedReport.",
+ "CapacityId": "Identifier of the capacity serving the item.",
+ "CapacityName": "Name of the capacity serving the item.",
+ "DistributionMethod": "How the content was distributed, for example via an app or shared directly.",
+ "ConsumptionMethod": "How the content was consumed, for example Power BI Web or Power BI Mobile.",
+ "SharingAction": "Sharing action performed, for shared-link and permission events.",
+ "SharingInformation": "Details of who the item was shared with and at what permission level.",
+ "ExportEventStartDateTimeParameter": "Start time of an export job, for export activity events.",
+ "ExportEventEndDateTimeParameter": "End time of an export job, for export activity events.",
+ },
+ },
+ "groups": {
+ "description": "A Power BI or Fabric workspace in the tenant, including personal and orphaned workspaces.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/power-bi/admin/groups-get-groups-as-admin",
+ "columns": {
+ "id": "Unique identifier for the workspace.",
+ "name": "Name of the workspace.",
+ "description": "Description of the workspace.",
+ "type": "Workspace type, for example Workspace, PersonalGroup, or Group.",
+ "state": "Current state of the workspace, for example Active, Deleted, or Orphaned.",
+ "isOnDedicatedCapacity": "Whether the workspace runs on a dedicated Premium or Fabric capacity.",
+ "capacityId": "Identifier of the capacity the workspace is assigned to.",
+ "capacityMigrationStatus": "Migration status of the workspace towards a new capacity.",
+ "isReadOnly": "Whether the workspace is read-only.",
+ "hasWorkspaceLevelSettings": "Whether the workspace has workspace-level settings applied.",
+ "pipelineId": "Identifier of the deployment pipeline the workspace belongs to.",
+ "defaultDatasetStorageFormat": "Default storage format for semantic models in the workspace.",
+ "logAnalyticsWorkspace": "Azure Log Analytics workspace the workspace sends logs to.",
+ },
+ },
+ "datasets": {
+ "description": "A semantic model (dataset) in the tenant.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/power-bi/admin/datasets-get-datasets-as-admin",
+ "columns": {
+ "id": "Unique identifier for the semantic model.",
+ "name": "Name of the semantic model.",
+ "description": "Description of the semantic model.",
+ "webUrl": "Web URL of the semantic model.",
+ "configuredBy": "User that configured the semantic model.",
+ "createdDate": "Date and time the semantic model was created.",
+ "contentProviderType": "Content provider type of the semantic model.",
+ "workspaceId": "Identifier of the workspace the semantic model belongs to.",
+ "isRefreshable": "Whether the semantic model can be refreshed.",
+ "isEffectiveIdentityRequired": "Whether the semantic model requires an effective identity for embedding.",
+ "isEffectiveIdentityRolesRequired": "Whether row-level security roles are required for embedding.",
+ "isOnPremGatewayRequired": "Whether the semantic model needs an on-premises data gateway.",
+ "targetStorageMode": "Storage mode of the semantic model, for example Abf or PremiumFiles.",
+ "upstreamDataflows": "Dataflows the semantic model gets data from.",
+ "upstreamDatasets": "Semantic models this semantic model gets data from.",
+ "users": "Semantic model user access rights, when requested.",
+ },
+ },
+ "reports": {
+ "description": "A report in the tenant, including reports in personal workspaces.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/power-bi/admin/reports-get-reports-as-admin",
+ "columns": {
+ "id": "Unique identifier for the report.",
+ "name": "Name of the report.",
+ "description": "Description of the report.",
+ "reportType": "Type of report, for example PowerBIReport or PaginatedReport.",
+ "webUrl": "Web URL of the report.",
+ "embedUrl": "Embed URL of the report.",
+ "datasetId": "Identifier of the semantic model the report is built on.",
+ "workspaceId": "Identifier of the workspace the report belongs to.",
+ "createdBy": "User that created the report.",
+ "createdDateTime": "Date and time the report was created.",
+ "modifiedBy": "User that last modified the report.",
+ "modifiedDateTime": "Date and time the report was last modified.",
+ "appId": "Identifier of the app the report is distributed through.",
+ "isOwnedByMe": "Whether the report is owned by the calling identity.",
+ "users": "Report user access rights, when requested.",
+ },
+ },
+ "dashboards": {
+ "description": "A dashboard in the tenant, including dashboards in personal workspaces.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/power-bi/admin/dashboards-get-dashboards-as-admin",
+ "columns": {
+ "id": "Unique identifier for the dashboard.",
+ "displayName": "Display name of the dashboard.",
+ "webUrl": "Web URL of the dashboard.",
+ "embedUrl": "Embed URL of the dashboard.",
+ "isReadOnly": "Whether the dashboard is read-only.",
+ "workspaceId": "Identifier of the workspace the dashboard belongs to.",
+ "appId": "Identifier of the app the dashboard is distributed through.",
+ "users": "Dashboard user access rights, when requested.",
+ },
+ },
+ "dataflows": {
+ "description": "A dataflow in the tenant.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/power-bi/admin/dataflows-get-dataflows-as-admin",
+ "columns": {
+ "objectId": "Unique identifier for the dataflow.",
+ "name": "Name of the dataflow.",
+ "description": "Description of the dataflow.",
+ "modelUrl": "URL of the dataflow definition file.",
+ "configuredBy": "User that configured the dataflow.",
+ "workspaceId": "Identifier of the workspace the dataflow belongs to.",
+ "modifiedBy": "User that last modified the dataflow.",
+ "modifiedDateTime": "Date and time the dataflow was last modified.",
+ "users": "Dataflow user access rights, when requested.",
+ },
+ },
+ "capacities": {
+ "description": "A Power BI Premium or Fabric capacity assigned to the tenant.",
+ "docs_url": "https://learn.microsoft.com/en-us/rest/api/power-bi/admin/get-capacities-as-admin",
+ "columns": {
+ "id": "Unique identifier for the capacity.",
+ "displayName": "Display name of the capacity.",
+ "sku": "SKU of the capacity, for example P1 or F64.",
+ "state": "Current state of the capacity, for example Active or Suspended.",
+ "region": "Azure region the capacity runs in.",
+ "admins": "Users configured as capacity administrators.",
+ "capacityUserAccessRight": "Access right the calling identity has on the capacity.",
+ "tenantKeyId": "Identifier of the encryption key assigned to the capacity.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/power_bi_admin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/power_bi_admin.py
new file mode 100644
index 000000000000..7c6f6050438c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/power_bi_admin.py
@@ -0,0 +1,400 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+
+import requests
+import structlog
+from structlog.types import FilteringBoundLogger
+
+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.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.power_bi_admin.settings import (
+ ACTIVITY_EVENTS_ENDPOINT,
+ ACTIVITY_EVENTS_RETENTION_DAYS,
+ BASE_URL,
+ LOGIN_BASE_URL,
+ MAX_CONTINUATION_PAGES,
+ MAX_ODATA_PAGES,
+ ODATA_PAGE_SIZE,
+ POWER_BI_ADMIN_ENDPOINTS,
+ TOKEN_SCOPE,
+)
+
+REQUEST_TIMEOUT_SECONDS = 120
+VALIDATE_TIMEOUT_SECONDS = 30
+
+_module_logger: FilteringBoundLogger = structlog.get_logger(__name__)
+
+ADMIN_API_DENIED_ERROR = (
+ "Power BI denied access to the admin APIs. Enable service principal access to the read-only "
+ "admin APIs in the Fabric admin portal and grant the app Tenant.Read.All."
+)
+
+
[email protected](frozen=True)
+class PowerBiAdminResumeConfig:
+ """Cursor for whichever endpoint the job is walking.
+
+ Activity events walk one UTC day at a time, with `continuation_token` holding the
+ mid-day cursor. Inventory endpoints walk an OData `$skip` offset. Both live in one
+ dataclass, and the manager is namespaced per endpoint so the formats never mix.
+ """
+
+ next_day: Optional[str] = None
+ continuation_token: Optional[str] = None
+ skip: Optional[int] = None
+
+
+def _coerce_date(value: Any) -> Optional[date]:
+ if isinstance(value, datetime):
+ return value.astimezone(UTC).date() if value.tzinfo else value.date()
+ if isinstance(value, date):
+ return value
+ if isinstance(value, str):
+ stripped = value.strip()
+ if not stripped:
+ return None
+ try:
+ # Power BI stamps activity events as `2026-07-25T07:55:15Z`; `fromisoformat`
+ # handles the trailing Z from Python 3.11 on.
+ return datetime.fromisoformat(stripped).date()
+ except ValueError:
+ return None
+ return None
+
+
+def _parse_creation_time(value: Any) -> Optional[datetime]:
+ if isinstance(value, datetime):
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+ if not isinstance(value, str) or not value.strip():
+ return None
+ try:
+ parsed = datetime.fromisoformat(value.strip())
+ except ValueError:
+ return None
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+
+
+def _normalize_activity_event(row: dict[str, Any]) -> dict[str, Any]:
+ """Type `CreationTime` as a real datetime so it works as a cursor and partition key."""
+ parsed = _parse_creation_time(row.get("CreationTime"))
+ if parsed is not None:
+ row["CreationTime"] = parsed
+ return row
+
+
+class PowerBiAdminClient:
+ """Minimal Power BI admin API client: mints an Entra ID token and issues GETs.
+
+ Access tokens last about an hour, so a long sync re-mints on the first 401 rather than
+ failing the job.
+ """
+
+ def __init__(
+ self,
+ tenant_id: str,
+ client_id: str,
+ client_secret: str,
+ logger: FilteringBoundLogger,
+ ) -> None:
+ self._tenant_id = tenant_id.strip()
+ self._client_id = client_id.strip()
+ self._client_secret = client_secret
+ self._logger = logger
+ self._session = make_tracked_session(redact_values=(client_secret,))
+ self._token: Optional[str] = None
+
+ @property
+ def token_url(self) -> str:
+ return f"{LOGIN_BASE_URL}/{self._tenant_id}/oauth2/v2.0/token"
+
+ def mint_token(self) -> str:
+ response = self._session.post(
+ self.token_url,
+ data={
+ "grant_type": "client_credentials",
+ "client_id": self._client_id,
+ "client_secret": self._client_secret,
+ "scope": TOKEN_SCOPE,
+ },
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ response.raise_for_status()
+ token = response.json().get("access_token")
+ if not token:
+ raise ValueError("Entra ID did not return an access token for the service principal")
+ self._token = token
+ return token
+
+ def get(self, path: str, params: Optional[dict[str, str]] = None, timeout: int = REQUEST_TIMEOUT_SECONDS) -> Any:
+ url = f"{BASE_URL}{path}"
+ if self._token is None:
+ self.mint_token()
+
+ def _do() -> requests.Response:
+ return self._session.get(
+ url,
+ params=params,
+ headers={"Authorization": f"Bearer {self._token}"},
+ timeout=timeout,
+ )
+
+ response = _do()
+ # Tokens expire mid-sync; re-mint once before treating a 401 as a real denial.
+ if response.status_code == 401:
+ self.mint_token()
+ response = _do()
+
+ if not response.ok:
+ self._logger.error(
+ f"Power BI admin API error: status={response.status_code}, body={response.text[:500]}, url={url}"
+ )
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _activity_event_pages(
+ client: PowerBiAdminClient,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PowerBiAdminResumeConfig],
+ start_day: date,
+ end_day: date,
+ resume_token: Optional[str],
+) -> Iterator[list[dict[str, Any]]]:
+ day = start_day
+ continuation_token = resume_token
+
+ while day <= end_day:
+ pages = 0
+ seen_tokens: set[str] = set()
+
+ while True:
+ if continuation_token:
+ params = {"continuationToken": f"'{continuation_token}'"}
+ else:
+ # The API requires both bounds inside one UTC day, single-quoted.
+ params = {
+ "startDateTime": f"'{day.isoformat()}T00:00:00'",
+ "endDateTime": f"'{day.isoformat()}T23:59:59'",
+ }
+
+ body = client.get("/activityevents", params=params)
+ rows = body.get("activityEventEntities") or []
+ if rows:
+ yield [_normalize_activity_event(row) for row in rows]
+
+ continuation_token = body.get("continuationToken")
+ pages += 1
+
+ # A page can come back empty and still carry a token, so termination is
+ # "token gone", never "no rows".
+ if not continuation_token:
+ break
+
+ if continuation_token in seen_tokens:
+ logger.warning(f"Power BI admin: repeated continuation token for {day.isoformat()}, stopping the day")
+ continuation_token = None
+ break
+ seen_tokens.add(continuation_token)
+
+ if pages >= MAX_CONTINUATION_PAGES:
+ logger.warning(
+ f"Power BI admin: hit the {MAX_CONTINUATION_PAGES}-page cap for {day.isoformat()}, "
+ "the rest of the day is skipped"
+ )
+ continuation_token = None
+ break
+
+ # Save mid-day so a heartbeat timeout resumes inside the day rather than
+ # refetching it. Saved after yielding, so a crash re-yields the last page and
+ # merge dedupes on `Id`.
+ resumable_source_manager.save_state(
+ PowerBiAdminResumeConfig(next_day=day.isoformat(), continuation_token=continuation_token)
+ )
+
+ day += timedelta(days=1)
+ resumable_source_manager.save_state(PowerBiAdminResumeConfig(next_day=day.isoformat()))
+
+
+def _odata_pages(
+ client: PowerBiAdminClient,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PowerBiAdminResumeConfig],
+ endpoint: str,
+ start_skip: int,
+) -> Iterator[list[dict[str, Any]]]:
+ config = POWER_BI_ADMIN_ENDPOINTS[endpoint]
+ skip = start_skip
+
+ for page in range(MAX_ODATA_PAGES):
+ params = {"$top": str(ODATA_PAGE_SIZE), "$skip": str(skip)}
+ body = client.get(config.path, params=params)
+ rows = body.get(config.data_key) or []
+ if rows:
+ yield rows
+
+ if len(rows) < ODATA_PAGE_SIZE:
+ return
+
+ skip += len(rows)
+ resumable_source_manager.save_state(PowerBiAdminResumeConfig(skip=skip))
+
+ if page == MAX_ODATA_PAGES - 1:
+ logger.warning(f"Power BI admin: hit the {MAX_ODATA_PAGES}-page cap for {endpoint}, later rows are skipped")
+
+
+def _single_page(client: PowerBiAdminClient, endpoint: str) -> Iterator[list[dict[str, Any]]]:
+ config = POWER_BI_ADMIN_ENDPOINTS[endpoint]
+ body = client.get(config.path)
+ rows = body.get(config.data_key) or []
+ if rows:
+ yield rows
+
+
[email protected](frozen=True)
+class _ActivityEventWindow:
+ """Result of resolving the activity-events sync window: which UTC days to
+ walk and, if resuming mid-day, the continuation token to restart from."""
+
+ start_day: date
+ end_day: date
+ resume_token: Optional[str]
+
+
+def _activity_event_window(
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ resume: Optional[PowerBiAdminResumeConfig],
+ logger: FilteringBoundLogger,
+) -> _ActivityEventWindow:
+ today = datetime.now(UTC).date()
+ earliest = today - timedelta(days=ACTIVITY_EVENTS_RETENTION_DAYS - 1)
+ start = earliest
+
+ if should_use_incremental_field:
+ last_value = _coerce_date(db_incremental_field_last_value)
+ if last_value is not None:
+ # Restart at the watermark's own day, not the day after: a day is only fully
+ # fetched once we move past it, and merge dedupes on `Id`. This also means the
+ # order of events inside a day never matters.
+ start = max(start, last_value)
+
+ resume_token: Optional[str] = None
+ if resume is not None:
+ resumed = _coerce_date(resume.next_day)
+ if resumed is not None:
+ start = max(resumed, earliest)
+ # A mid-day token is only valid for the day it was issued against.
+ if resumed >= earliest:
+ resume_token = resume.continuation_token
+ logger.debug(f"Power BI admin: resuming activity events from {start.isoformat()}")
+
+ return _ActivityEventWindow(start_day=start, end_day=today, resume_token=resume_token)
+
+
+def _get_rows(
+ tenant_id: str,
+ client_id: str,
+ client_secret: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PowerBiAdminResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ config = POWER_BI_ADMIN_ENDPOINTS[endpoint]
+ client = PowerBiAdminClient(tenant_id, client_id, client_secret, logger)
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if endpoint == ACTIVITY_EVENTS_ENDPOINT:
+ window = _activity_event_window(should_use_incremental_field, db_incremental_field_last_value, resume, logger)
+ yield from _activity_event_pages(
+ client, logger, resumable_source_manager, window.start_day, window.end_day, window.resume_token
+ )
+ return
+
+ if not config.supports_odata_paging:
+ yield from _single_page(client, endpoint)
+ return
+
+ start_skip = resume.skip if resume is not None and resume.skip is not None else 0
+ yield from _odata_pages(client, logger, resumable_source_manager, endpoint, start_skip)
+
+
+def power_bi_admin_source(
+ tenant_id: str,
+ client_id: str,
+ client_secret: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PowerBiAdminResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = POWER_BI_ADMIN_ENDPOINTS[endpoint]
+ has_datetime_partition = config.partition_key is not None
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _get_rows(
+ tenant_id=tenant_id,
+ client_id=client_id,
+ client_secret=client_secret,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if has_datetime_partition else None,
+ partition_format="month" if has_datetime_partition else None,
+ partition_keys=[config.partition_key] if config.partition_key is not None else None,
+ # Days are walked oldest-first, and each day is refetched from its start, so the
+ # watermark only ever moves forward.
+ sort_mode="asc",
+ )
+
+
+def validate_credentials(
+ tenant_id: str,
+ client_id: str,
+ client_secret: str,
+) -> tuple[bool, Optional[str]]:
+ if not tenant_id.strip():
+ return False, "Enter the directory (tenant) ID of your Entra ID tenant."
+
+ client = PowerBiAdminClient(tenant_id, client_id, client_secret, _module_logger)
+
+ try:
+ client.mint_token()
+ except requests.HTTPError as e:
+ status = e.response.status_code if e.response is not None else None
+ if status in (400, 401):
+ return (
+ False,
+ "Entra ID rejected the service principal. Check the tenant ID, application (client) ID, "
+ "and client secret.",
+ )
+ return False, f"Could not get a token from Entra ID (status {status})."
+ except Exception as e:
+ return False, f"Could not reach Entra ID ({e}). Please retry."
+
+ try:
+ client.get("/groups", params={"$top": "1"}, timeout=VALIDATE_TIMEOUT_SECONDS)
+ except requests.HTTPError as e:
+ status = e.response.status_code if e.response is not None else None
+ # Every table here needs the same tenant-wide admin grant, so a denial is a blocking
+ # misconfiguration rather than one missing per-table scope.
+ if status in (401, 403):
+ return False, ADMIN_API_DENIED_ERROR
+ return False, f"The Power BI admin API returned an unexpected status ({status})."
+ except Exception as e:
+ return False, f"Could not reach the Power BI admin API ({e}). Please retry."
+
+ return True, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/settings.py
new file mode 100644
index 000000000000..976c88b39477
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/settings.py
@@ -0,0 +1,103 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+# Single global host — Power BI resolves tenant data residency server-side.
+BASE_URL = "https://api.powerbi.com/v1.0/myorg/admin"
+# Entra ID (Azure AD) token endpoint; the tenant id is interpolated into the path.
+LOGIN_BASE_URL = "https://login.microsoftonline.com"
+# Client-credentials scope for the Power BI / Fabric REST API.
+TOKEN_SCOPE = "https://analysis.windows.net/powerbi/api/.default"
+
+# Activity events are only retained for a rolling window, and each request must cover a
+# single UTC day. Warehousing them past this window is the point of the table, so the first
+# sync can only reach as far back as the API still serves.
+ACTIVITY_EVENTS_RETENTION_DAYS = 28
+
+# `$top` ceiling documented for the AsAdmin inventory list endpoints.
+ODATA_PAGE_SIZE = 5000
+
+# Hard caps so a misbehaving continuation token or an `$skip` walk that never shortens
+# can't spin forever. Both are far above any realistic tenant.
+MAX_CONTINUATION_PAGES = 2000
+MAX_ODATA_PAGES = 200
+
+ACTIVITY_EVENTS_ENDPOINT = "activity_events"
+
+
+@dataclass(frozen=True)
+class PowerBiAdminEndpointConfig:
+ name: str
+ # Path under BASE_URL.
+ path: str
+ primary_keys: list[str]
+ description: str
+ # Response key the rows live under.
+ data_key: str = "value"
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable datetime column for datetime partitioning (None = no datetime partitioning).
+ partition_key: Optional[str] = None
+ # OData `$top`/`$skip` paging. Activity events use continuation tokens instead, and
+ # `capacities` returns the whole tenant list in one response.
+ supports_odata_paging: bool = True
+
+
+POWER_BI_ADMIN_ENDPOINTS: dict[str, PowerBiAdminEndpointConfig] = {
+ ACTIVITY_EVENTS_ENDPOINT: PowerBiAdminEndpointConfig(
+ name=ACTIVITY_EVENTS_ENDPOINT,
+ path="/activityevents",
+ primary_keys=["Id"],
+ description="Tenant audit events (views, edits, exports, shares) for Power BI and Fabric items",
+ data_key="activityEventEntities",
+ # `CreationTime` is when the event happened and never changes, so it is safe as both
+ # the cursor and the partition key.
+ incremental_fields=[incremental_field("CreationTime")],
+ partition_key="CreationTime",
+ supports_odata_paging=False,
+ ),
+ "groups": PowerBiAdminEndpointConfig(
+ name="groups",
+ path="/groups",
+ primary_keys=["id"],
+ description="Every workspace in the tenant, including personal and orphaned workspaces",
+ ),
+ "datasets": PowerBiAdminEndpointConfig(
+ name="datasets",
+ path="/datasets",
+ primary_keys=["id"],
+ description="Every semantic model (dataset) in the tenant",
+ ),
+ "reports": PowerBiAdminEndpointConfig(
+ name="reports",
+ path="/reports",
+ primary_keys=["id"],
+ description="Every report in the tenant",
+ ),
+ "dashboards": PowerBiAdminEndpointConfig(
+ name="dashboards",
+ path="/dashboards",
+ primary_keys=["id"],
+ description="Every dashboard in the tenant",
+ ),
+ "dataflows": PowerBiAdminEndpointConfig(
+ name="dataflows",
+ path="/dataflows",
+ primary_keys=["objectId"],
+ description="Every dataflow in the tenant",
+ ),
+ "capacities": PowerBiAdminEndpointConfig(
+ name="capacities",
+ path="/capacities",
+ primary_keys=["id"],
+ description="Premium and Fabric capacities assigned to the tenant",
+ supports_odata_paging=False,
+ ),
+}
+
+ENDPOINTS = tuple(POWER_BI_ADMIN_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in POWER_BI_ADMIN_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/source.py
index 749c58d87e38..faa60bb8636a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/source.py
@@ -1,32 +1,186 @@
-from typing import cast
+from typing import Optional, cast
from 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.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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.powerbiadmin import (
PowerBiAdminSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.power_bi_admin.power_bi_admin import (
+ ADMIN_API_DENIED_ERROR,
+ PowerBiAdminResumeConfig,
+ power_bi_admin_source,
+ validate_credentials as validate_power_bi_admin_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.power_bi_admin.settings import (
+ ACTIVITY_EVENTS_RETENTION_DAYS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ POWER_BI_ADMIN_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PowerBiAdminSource(SimpleSource[PowerBiAdminSourceConfig]):
+class PowerBiAdminSource(ResumableSource[PowerBiAdminSourceConfig, PowerBiAdminResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ # `v1.0` is a fixed segment of the admin API base path, not a version the tenant chooses.
+ api_docs_url = "https://learn.microsoft.com/en-us/rest/api/power-bi/admin"
+
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `tenant_id` selects which Entra directory the service principal's credentials are
+ # sent to. Without listing it here, an editor could repoint a preserved client_secret
+ # at a different tenant the same multi-tenant app registration happens to be in.
+ return ["tenant_id"]
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.POWERBIADMIN
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ ADMIN_API_DENIED_ERROR: None,
+ "400 Client Error: Bad Request for url: https://login.microsoftonline.com": (
+ "Entra ID rejected the service principal. Check the tenant ID, application (client) ID, "
+ "and client secret."
+ ),
+ "401 Client Error: Unauthorized for url: https://login.microsoftonline.com": (
+ "Entra ID rejected the service principal credentials. Generate a new client secret and reconnect."
+ ),
+ "401 Client Error: Unauthorized for url: https://api.powerbi.com": ADMIN_API_DENIED_ERROR,
+ "403 Client Error: Forbidden for url: https://api.powerbi.com": ADMIN_API_DENIED_ERROR,
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.power_bi_admin.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: PowerBiAdminSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ # Only activity events carry a server-side time filter; the AsAdmin inventory lists
+ # have no updated-since parameter, so they stay full refresh.
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ descriptions={name: endpoint.description for name, endpoint in POWER_BI_ADMIN_ENDPOINTS.items()},
+ )
+
+ def validate_credentials(
+ self,
+ config: PowerBiAdminSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_power_bi_admin_credentials(
+ tenant_id=config.tenant_id,
+ client_id=config.client_id,
+ client_secret=config.client_secret,
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PowerBiAdminResumeConfig]:
+ # Activity events persist a day/continuation cursor while inventory tables persist an
+ # OData offset, so each endpoint keeps its state in its own Redis slot.
+ return ResumableSourceManager[PowerBiAdminResumeConfig](inputs, PowerBiAdminResumeConfig).with_namespace(
+ inputs.schema_name
+ )
+
+ def source_for_pipeline(
+ self,
+ config: PowerBiAdminSourceConfig,
+ resumable_source_manager: ResumableSourceManager[PowerBiAdminResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return power_bi_admin_source(
+ tenant_id=config.tenant_id,
+ client_id=config.client_id,
+ client_secret=config.client_secret,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.POWER_BI_ADMIN,
category=DataWarehouseSourceCategory.ANALYTICS,
- label="Microsoft (Power BI / Fabric)",
+ label="Power BI admin",
+ keywords=["power bi", "powerbi", "fabric", "microsoft"],
+ caption=(
+ "Sync tenant-wide Power BI and Fabric governance data: the audit log of views, edits, exports "
+ "and shares, plus the workspace, semantic model, report, dashboard, dataflow, and capacity "
+ "inventories.\n\n"
+ "Create an Entra ID app registration, add a client secret, and put the app in a security group "
+ "that is allowed to use the read-only admin APIs in the Fabric admin portal. The app must not "
+ "have any admin-consent Power BI permissions set on it. Then enter the directory (tenant) ID, "
+ "application (client) ID, and client secret below.\n\n"
+ f"Power BI only serves activity events for the last {ACTIVITY_EVENTS_RETENTION_DAYS} days, so the "
+ "first sync starts there and everything after that builds up in your warehouse."
+ ),
+ docsUrl="https://posthog.com/docs/cdp/sources/power-bi-admin",
iconPath="/static/services/power_bi_admin.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ 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,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/tests/test_power_bi_admin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/tests/test_power_bi_admin.py
new file mode 100644
index 000000000000..353f90777b32
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/tests/test_power_bi_admin.py
@@ -0,0 +1,496 @@
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from typing import Any, Optional, cast
+
+from freezegun import freeze_time
+from unittest import mock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.power_bi_admin.power_bi_admin import (
+ ADMIN_API_DENIED_ERROR,
+ PowerBiAdminClient,
+ PowerBiAdminResumeConfig,
+ _coerce_date,
+ _get_rows,
+ _parse_creation_time,
+ power_bi_admin_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.power_bi_admin.settings import (
+ ACTIVITY_EVENTS_ENDPOINT,
+ ODATA_PAGE_SIZE,
+ POWER_BI_ADMIN_ENDPOINTS,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.power_bi_admin.power_bi_admin"
+
+TENANT_ID = "11111111-1111-1111-1111-111111111111"
+CLIENT_ID = "22222222-2222-2222-2222-222222222222"
+CLIENT_SECRET = "super-secret"
+
+
+def _response(status: int = 200, json_body: Any = None, text: str = "") -> mock.MagicMock:
+ response = mock.MagicMock(spec=requests.Response)
+ response.status_code = status
+ response.ok = 200 <= status < 300
+ response.text = text
+ response.json.return_value = json_body if json_body is not None else {}
+ if not response.ok:
+ error = requests.HTTPError(f"{status} Client Error", response=response)
+ response.raise_for_status.side_effect = error
+ else:
+ response.raise_for_status.return_value = None
+ return response
+
+
+def _token_response(token: str = "token-1") -> mock.MagicMock:
+ return _response(200, {"access_token": token, "expires_in": 3599})
+
+
+def _session(get_responses: list[mock.MagicMock], post_responses: Optional[list[mock.MagicMock]] = None) -> Any:
+ session = mock.MagicMock(spec=requests.Session)
+ session.get.side_effect = get_responses
+ session.post.side_effect = post_responses if post_responses is not None else [_token_response()]
+ return session
+
+
+def _manager(resume_state: Optional[PowerBiAdminResumeConfig] = None) -> Any:
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _run(
+ endpoint: str,
+ session: Any,
+ manager: Optional[Any] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> list[list[dict[str, Any]]]:
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ return list(
+ _get_rows(
+ tenant_id=TENANT_ID,
+ client_id=CLIENT_ID,
+ client_secret=CLIENT_SECRET,
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager if manager is not None else _manager(),
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+ )
+
+
+def _activity_params(session: Any) -> list[dict[str, str]]:
+ return [call.kwargs["params"] for call in session.get.call_args_list]
+
+
+def _event(event_id: str, creation_time: str = "2026-07-20T10:00:00Z") -> dict[str, Any]:
+ return {"Id": event_id, "Operation": "ViewReport", "CreationTime": creation_time}
+
+
+class TestHelpers:
+ @parameterized.expand(
+ [
+ ("none", None, None),
+ ("empty", " ", None),
+ ("garbage", "not-a-date", None),
+ ("iso_datetime_z", "2026-07-20T10:00:00Z", "2026-07-20"),
+ ("iso_datetime_naive", "2026-07-20T10:00:00", "2026-07-20"),
+ ("iso_date", "2026-07-20", "2026-07-20"),
+ ]
+ )
+ def test_coerce_date(self, _name: str, value: Any, expected: Optional[str]) -> None:
+ result = _coerce_date(value)
+ assert (result.isoformat() if result else None) == expected
+
+ def test_coerce_date_from_aware_datetime_uses_utc_day(self) -> None:
+ # 00:30 on the 21st in UTC+2 is still the 20th in UTC, which is the day the API windows on.
+ value = datetime.fromisoformat("2026-07-21T00:30:00+02:00")
+ result = _coerce_date(value)
+ assert result is not None and result.isoformat() == "2026-07-20"
+
+ @parameterized.expand(
+ [
+ ("none", None, None),
+ ("empty", "", None),
+ ("garbage", "nope", None),
+ ("with_z", "2026-07-20T10:00:00Z", "2026-07-20T10:00:00+00:00"),
+ ("naive_gets_utc", "2026-07-20T10:00:00", "2026-07-20T10:00:00+00:00"),
+ ]
+ )
+ def test_parse_creation_time(self, _name: str, value: Any, expected: Optional[str]) -> None:
+ result = _parse_creation_time(value)
+ assert (result.isoformat() if result else None) == expected
+
+
+class TestPowerBiAdminClient:
+ def test_mint_token_posts_client_credentials(self) -> None:
+ session = _session([], [_token_response("abc")])
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ client = PowerBiAdminClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, mock.MagicMock())
+ assert client.mint_token() == "abc"
+
+ assert client.token_url == f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token"
+ body = session.post.call_args.kwargs["data"]
+ assert body["grant_type"] == "client_credentials"
+ assert body["scope"] == "https://analysis.windows.net/powerbi/api/.default"
+ assert body["client_secret"] == CLIENT_SECRET
+
+ def test_mint_token_raises_when_no_token_returned(self) -> None:
+ session = _session([], [_response(200, {"token_type": "Bearer"})])
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ client = PowerBiAdminClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, mock.MagicMock())
+ try:
+ client.mint_token()
+ except ValueError as e:
+ assert "access token" in str(e)
+ else:
+ raise AssertionError("expected a ValueError when Entra ID returns no access token")
+
+ def test_secret_is_redacted_in_the_tracked_session(self) -> None:
+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:
+ PowerBiAdminClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, mock.MagicMock())
+
+ assert make_session.call_args.kwargs["redact_values"] == (CLIENT_SECRET,)
+
+ def test_expired_token_is_reminted_once_then_the_call_succeeds(self) -> None:
+ session = _session(
+ [_response(401, text="expired"), _response(200, {"value": [{"id": "g1"}]})],
+ [_token_response("first"), _token_response("second")],
+ )
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ client = PowerBiAdminClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, mock.MagicMock())
+ body = client.get("/groups")
+
+ assert body == {"value": [{"id": "g1"}]}
+ assert session.post.call_count == 2
+ assert session.get.call_args_list[0].kwargs["headers"]["Authorization"] == "Bearer first"
+ assert session.get.call_args_list[1].kwargs["headers"]["Authorization"] == "Bearer second"
+
+ def test_persistent_401_is_raised_after_the_remint(self) -> None:
+ session = _session(
+ [_response(401, text="denied"), _response(401, text="denied")],
+ [_token_response("first"), _token_response("second")],
+ )
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ client = PowerBiAdminClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET, mock.MagicMock())
+ try:
+ client.get("/groups")
+ except requests.HTTPError:
+ pass
+ else:
+ raise AssertionError("expected the second 401 to raise")
+
+ assert session.get.call_count == 2
+
+
+@freeze_time("2026-07-26T12:00:00Z")
+class TestActivityEvents:
+ def test_full_refresh_walks_the_whole_retention_window_one_day_per_request(self) -> None:
+ session = _session([_response(200, {"activityEventEntities": []}) for _ in range(28)])
+
+ batches = _run(ACTIVITY_EVENTS_ENDPOINT, session)
+
+ assert batches == []
+ params = _activity_params(session)
+ assert len(params) == 28
+ assert params[0]["startDateTime"] == "'2026-06-29T00:00:00'"
+ assert params[0]["endDateTime"] == "'2026-06-29T23:59:59'"
+ assert params[-1]["startDateTime"] == "'2026-07-26T00:00:00'"
+
+ def test_incremental_restarts_at_the_watermark_day(self) -> None:
+ session = _session([_response(200, {"activityEventEntities": [_event("e1")]}) for _ in range(3)])
+
+ batches = _run(
+ ACTIVITY_EVENTS_ENDPOINT,
+ session,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-07-24T18:00:00Z",
+ )
+
+ assert len(batches) == 3
+ assert [p["startDateTime"] for p in _activity_params(session)] == [
+ "'2026-07-24T00:00:00'",
+ "'2026-07-25T00:00:00'",
+ "'2026-07-26T00:00:00'",
+ ]
+
+ def test_incremental_watermark_older_than_retention_is_clamped(self) -> None:
+ session = _session([_response(200, {"activityEventEntities": []}) for _ in range(28)])
+
+ _run(
+ ACTIVITY_EVENTS_ENDPOINT,
+ session,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-01-01T00:00:00Z",
+ )
+
+ assert _activity_params(session)[0]["startDateTime"] == "'2026-06-29T00:00:00'"
+
+ def test_creation_time_is_typed_as_a_datetime(self) -> None:
+ session = _session(
+ [_response(200, {"activityEventEntities": [_event("e1", "2026-07-26T09:15:00Z")]})]
+ + [_response(200, {"activityEventEntities": []}) for _ in range(27)]
+ )
+
+ batches = _run(ACTIVITY_EVENTS_ENDPOINT, session)
+
+ assert batches[0][0]["CreationTime"] == datetime(2026, 7, 26, 9, 15, tzinfo=UTC)
+
+ def test_continuation_token_loop_ends_on_a_missing_token_not_on_empty_rows(self) -> None:
+ session = _session(
+ [
+ _response(200, {"activityEventEntities": [_event("e1")], "continuationToken": "t1"}),
+ # Empty page that still carries a token: the loop must keep going.
+ _response(200, {"activityEventEntities": [], "continuationToken": "t2"}),
+ _response(200, {"activityEventEntities": [_event("e2")]}),
+ ]
+ + [_response(200, {"activityEventEntities": []}) for _ in range(27)]
+ )
+
+ batches = _run(ACTIVITY_EVENTS_ENDPOINT, session)
+
+ assert [row["Id"] for batch in batches for row in batch] == ["e1", "e2"]
+ params = _activity_params(session)
+ assert params[1] == {"continuationToken": "'t1'"}
+ assert params[2] == {"continuationToken": "'t2'"}
+ # After the day drained, the next request windows the following day again.
+ assert "startDateTime" in params[3]
+
+ def test_repeated_continuation_token_stops_the_day_instead_of_looping(self) -> None:
+ session = _session(
+ [_response(200, {"activityEventEntities": [_event("e1")], "continuationToken": "same"}) for _ in range(2)]
+ + [_response(200, {"activityEventEntities": []}) for _ in range(27)]
+ )
+
+ batches = _run(ACTIVITY_EVENTS_ENDPOINT, session)
+
+ assert len(batches) == 2
+ # 2 pages of the first day + one windowed request for each of the 27 remaining days.
+ assert session.get.call_count == 29
+
+ def test_state_is_saved_after_each_page_and_after_each_day(self) -> None:
+ manager = _manager()
+ session = _session(
+ [
+ _response(200, {"activityEventEntities": [_event("e1")], "continuationToken": "t1"}),
+ _response(200, {"activityEventEntities": [_event("e2")]}),
+ ]
+ + [_response(200, {"activityEventEntities": []}) for _ in range(27)]
+ )
+
+ _run(ACTIVITY_EVENTS_ENDPOINT, session, manager=manager)
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved[0] == PowerBiAdminResumeConfig(next_day="2026-06-29", continuation_token="t1")
+ assert saved[1] == PowerBiAdminResumeConfig(next_day="2026-06-30")
+ assert saved[-1] == PowerBiAdminResumeConfig(next_day="2026-07-27")
+
+ def test_resume_starts_from_the_saved_day_and_continuation_token(self) -> None:
+ manager = _manager(PowerBiAdminResumeConfig(next_day="2026-07-25", continuation_token="saved-token"))
+ session = _session([_response(200, {"activityEventEntities": [_event("e1")]}) for _ in range(2)])
+
+ batches = _run(ACTIVITY_EVENTS_ENDPOINT, session, manager=manager)
+
+ assert len(batches) == 2
+ params = _activity_params(session)
+ assert params[0] == {"continuationToken": "'saved-token'"}
+ assert params[1]["startDateTime"] == "'2026-07-26T00:00:00'"
+
+ def test_resume_takes_precedence_over_the_incremental_watermark(self) -> None:
+ manager = _manager(PowerBiAdminResumeConfig(next_day="2026-07-26"))
+ session = _session([_response(200, {"activityEventEntities": []})])
+
+ _run(
+ ACTIVITY_EVENTS_ENDPOINT,
+ session,
+ manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-07-01T00:00:00Z",
+ )
+
+ assert _activity_params(session)[0]["startDateTime"] == "'2026-07-26T00:00:00'"
+
+ def test_stale_resume_day_drops_its_continuation_token(self) -> None:
+ # A token issued before the retention window rolled over is no longer valid, so the
+ # clamped day must be re-windowed rather than resumed from the token.
+ manager = _manager(PowerBiAdminResumeConfig(next_day="2024-01-01", continuation_token="stale"))
+ session = _session([_response(200, {"activityEventEntities": []}) for _ in range(28)])
+
+ _run(ACTIVITY_EVENTS_ENDPOINT, session, manager=manager)
+
+ assert _activity_params(session)[0]["startDateTime"] == "'2026-06-29T00:00:00'"
+
+
+class TestInventoryEndpoints:
+ @parameterized.expand([("groups",), ("datasets",), ("reports",), ("dashboards",), ("dataflows",)])
+ def test_short_page_terminates_the_odata_walk(self, endpoint: str) -> None:
+ session = _session([_response(200, {"value": [{"id": "a"}, {"id": "b"}]})])
+
+ batches = _run(endpoint, session)
+
+ assert batches == [[{"id": "a"}, {"id": "b"}]]
+ assert session.get.call_count == 1
+ params = session.get.call_args.kwargs["params"]
+ assert params == {"$top": str(ODATA_PAGE_SIZE), "$skip": "0"}
+
+ def test_full_page_advances_skip_until_a_short_page(self) -> None:
+ full_page = [{"id": str(i)} for i in range(ODATA_PAGE_SIZE)]
+ manager = _manager()
+ session = _session([_response(200, {"value": full_page}), _response(200, {"value": [{"id": "last"}]})])
+
+ batches = _run("groups", session, manager=manager)
+
+ assert len(batches) == 2
+ assert [call.kwargs["params"]["$skip"] for call in session.get.call_args_list] == ["0", str(ODATA_PAGE_SIZE)]
+ assert manager.save_state.call_args_list[0].args[0] == PowerBiAdminResumeConfig(skip=ODATA_PAGE_SIZE)
+
+ def test_resume_starts_from_the_saved_skip(self) -> None:
+ manager = _manager(PowerBiAdminResumeConfig(skip=10000))
+ session = _session([_response(200, {"value": [{"id": "a"}]})])
+
+ _run("groups", session, manager=manager)
+
+ assert session.get.call_args.kwargs["params"]["$skip"] == "10000"
+
+ def test_capacities_is_a_single_unpaged_request(self) -> None:
+ session = _session([_response(200, {"value": [{"id": "c1"}]})])
+
+ batches = _run("capacities", session)
+
+ assert batches == [[{"id": "c1"}]]
+ assert session.get.call_args.kwargs["params"] is None
+
+ def test_empty_response_yields_nothing(self) -> None:
+ session = _session([_response(200, {"value": []})])
+
+ assert _run("groups", session) == []
+
+
+class TestSourceResponse:
+ @parameterized.expand([(name,) for name in POWER_BI_ADMIN_ENDPOINTS])
+ def test_response_carries_the_endpoint_primary_keys(self, endpoint: str) -> None:
+ response = power_bi_admin_source(
+ tenant_id=TENANT_ID,
+ client_id=CLIENT_ID,
+ client_secret=CLIENT_SECRET,
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == POWER_BI_ADMIN_ENDPOINTS[endpoint].primary_keys
+ assert response.sort_mode == "asc"
+
+ def test_activity_events_partition_on_creation_time(self) -> None:
+ response = power_bi_admin_source(
+ tenant_id=TENANT_ID,
+ client_id=CLIENT_ID,
+ client_secret=CLIENT_SECRET,
+ endpoint=ACTIVITY_EVENTS_ENDPOINT,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["CreationTime"]
+
+ def test_inventory_endpoints_have_no_datetime_partitioning(self) -> None:
+ response = power_bi_admin_source(
+ tenant_id=TENANT_ID,
+ client_id=CLIENT_ID,
+ client_secret=CLIENT_SECRET,
+ endpoint="groups",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_items_is_lazy_and_iterates_the_endpoint(self) -> None:
+ session = _session([_response(200, {"value": [{"id": "g1"}]})])
+ response = power_bi_admin_source(
+ tenant_id=TENANT_ID,
+ client_id=CLIENT_ID,
+ client_secret=CLIENT_SECRET,
+ endpoint="groups",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+
+ assert session.get.call_count == 0
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ batches = list(cast("Iterable[Any]", response.items()))
+
+ assert batches == [[{"id": "g1"}]]
+
+
+class TestValidateCredentials:
+ def test_valid_credentials_probe_the_admin_groups_endpoint(self) -> None:
+ session = _session([_response(200, {"value": [{"id": "g1"}]})])
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials(TENANT_ID, CLIENT_ID, CLIENT_SECRET)
+
+ assert (is_valid, message) == (True, None)
+ assert session.get.call_args.kwargs["params"] == {"$top": "1"}
+
+ def test_blank_tenant_id_fails_without_a_request(self) -> None:
+ session = _session([])
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials(" ", CLIENT_ID, CLIENT_SECRET)
+
+ assert is_valid is False
+ assert message is not None and "tenant" in message.lower()
+ assert session.post.call_count == 0
+
+ @parameterized.expand([(400,), (401,)])
+ def test_rejected_token_reports_bad_service_principal(self, status: int) -> None:
+ session = _session([], [_response(status, text="invalid_client")])
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials(TENANT_ID, CLIENT_ID, CLIENT_SECRET)
+
+ assert is_valid is False
+ assert message is not None and "client secret" in message
+
+ @parameterized.expand([(401,), (403,)])
+ def test_denied_admin_api_reports_the_tenant_grant(self, status: int) -> None:
+ # A 401 gets one re-mint before it is treated as a denial, so both attempts fail here.
+ session = _session(
+ [_response(status, text="denied"), _response(status, text="denied")],
+ [_token_response("a"), _token_response("b")],
+ )
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials(TENANT_ID, CLIENT_ID, CLIENT_SECRET)
+
+ assert (is_valid, message) == (False, ADMIN_API_DENIED_ERROR)
+
+ def test_unexpected_admin_api_status_is_reported_with_the_status(self) -> None:
+ session = _session([_response(500, text="boom")])
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials(TENANT_ID, CLIENT_ID, CLIENT_SECRET)
+
+ assert is_valid is False
+ assert message is not None and "500" in message
+
+ def test_network_failure_asks_for_a_retry(self) -> None:
+ session = mock.MagicMock(spec=requests.Session)
+ session.post.side_effect = requests.ConnectionError("no route to host")
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ is_valid, message = validate_credentials(TENANT_ID, CLIENT_ID, CLIENT_SECRET)
+
+ assert is_valid is False
+ assert message is not None and "retry" in message.lower()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/tests/test_power_bi_admin_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/tests/test_power_bi_admin_source.py
new file mode 100644
index 000000000000..ee0bd9ec9e8c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/power_bi_admin/tests/test_power_bi_admin_source.py
@@ -0,0 +1,194 @@
+from types import SimpleNamespace
+from typing import cast
+
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
+
+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.powerbiadmin import (
+ PowerBiAdminSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.power_bi_admin.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.power_bi_admin.power_bi_admin import (
+ ADMIN_API_DENIED_ERROR,
+ PowerBiAdminResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.power_bi_admin.settings import (
+ ACTIVITY_EVENTS_ENDPOINT,
+ ENDPOINTS,
+ POWER_BI_ADMIN_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.power_bi_admin.source import PowerBiAdminSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.power_bi_admin.source"
+
+TENANT_ID = "11111111-1111-1111-1111-111111111111"
+CLIENT_ID = "22222222-2222-2222-2222-222222222222"
+CLIENT_SECRET = "super-secret"
+
+
+def _inputs(
+ schema_name: str = ACTIVITY_EVENTS_ENDPOINT,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: object = None,
+) -> SourceInputs:
+ return cast(
+ SourceInputs,
+ SimpleNamespace(
+ schema_name=schema_name,
+ schema_id="schema-1",
+ source_id="source-1",
+ team_id=123,
+ job_id="job-1",
+ logger=mock.MagicMock(),
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field="CreationTime" if should_use_incremental_field else None,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ )
+
+
+class TestPowerBiAdminSource:
+ def setup_method(self) -> None:
+ self.source = PowerBiAdminSource()
+ self.team_id = 123
+ self.config = PowerBiAdminSourceConfig(tenant_id=TENANT_ID, client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.POWERBIADMIN
+
+ def test_tenant_id_is_a_connection_host_field(self) -> None:
+ # Retargeting the tenant ID must force re-entry of the client secret — without this an
+ # editor could repoint a preserved secret at another Entra directory.
+ assert self.source.connection_host_fields == ["tenant_id"]
+
+ def test_get_source_config_is_released_in_alpha(self) -> None:
+ config = self.source.get_source_config
+
+ assert not config.unreleasedSource
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.name.value == "PowerBiAdmin"
+ assert config.category == DataWarehouseSourceCategory.ANALYTICS
+ assert config.iconPath == "/static/services/power_bi_admin.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/power-bi-admin"
+
+ def test_config_asks_the_customer_for_the_service_principal(self) -> None:
+ fields_by_name = {field.name: field for field in self.source.get_source_config.fields}
+
+ assert set(fields_by_name) == {"tenant_id", "client_id", "client_secret"}
+ for field in fields_by_name.values():
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.required is True
+
+ secret = fields_by_name["client_secret"]
+ assert isinstance(secret, SourceFieldInputConfig)
+ assert secret.secret is True
+ assert secret.type.value == "password"
+ assert cast(SourceFieldInputConfig, fields_by_name["tenant_id"]).secret is False
+
+ def test_get_schemas_returns_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ for schema in schemas:
+ assert schema.description == POWER_BI_ADMIN_ENDPOINTS[schema.name].description
+
+ def test_only_activity_events_support_incremental(self) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ activity = schemas[ACTIVITY_EVENTS_ENDPOINT]
+ assert activity.supports_incremental is True
+ assert {field["field"] for field in activity.incremental_fields} == {"CreationTime"}
+
+ for name, schema in schemas.items():
+ if name == ACTIVITY_EVENTS_ENDPOINT:
+ continue
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["groups"])
+ assert [schema.name for schema in schemas] == ["groups"]
+
+ def test_non_retryable_errors_cover_token_and_admin_denials(self) -> None:
+ errors = self.source.get_non_retryable_errors()
+
+ assert ADMIN_API_DENIED_ERROR in errors
+ assert errors["403 Client Error: Forbidden for url: https://api.powerbi.com"] == ADMIN_API_DENIED_ERROR
+ assert "401 Client Error: Unauthorized for url: https://login.microsoftonline.com" in errors
+
+ @parameterized.expand([(True, None), (False, "nope")])
+ @mock.patch(f"{MODULE}.validate_power_bi_admin_credentials")
+ def test_validate_credentials_plumbs_the_service_principal(
+ self, expected_valid: bool, expected_message: str | None, mock_validate: mock.MagicMock
+ ) -> None:
+ mock_validate.return_value = (expected_valid, expected_message)
+
+ assert self.source.validate_credentials(self.config, self.team_id) == (expected_valid, expected_message)
+ mock_validate.assert_called_once_with(tenant_id=TENANT_ID, client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
+
+ def test_resumable_manager_is_namespaced_per_schema(self) -> None:
+ manager = self.source.get_resumable_source_manager(_inputs(schema_name="groups"))
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is PowerBiAdminResumeConfig
+ # Activity-event day cursors and OData offsets must not share a Redis slot.
+ assert manager._key.endswith(":groups")
+
+ @mock.patch(f"{MODULE}.power_bi_admin_source")
+ def test_source_for_pipeline_plumbs_inputs(self, mock_source: mock.MagicMock) -> None:
+ mock_source.return_value = SimpleNamespace(name=ACTIVITY_EVENTS_ENDPOINT)
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ inputs = _inputs(should_use_incremental_field=True, db_incremental_field_last_value="2026-07-20T00:00:00Z")
+
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once_with(
+ tenant_id=TENANT_ID,
+ client_id=CLIENT_ID,
+ client_secret=CLIENT_SECRET,
+ endpoint=ACTIVITY_EVENTS_ENDPOINT,
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-07-20T00:00:00Z",
+ )
+ assert response is mock_source.return_value
+
+ @mock.patch(f"{MODULE}.power_bi_admin_source")
+ def test_source_for_pipeline_drops_last_value_on_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ mock_source.return_value = SimpleNamespace(name="groups")
+ inputs = _inputs(
+ schema_name="groups", should_use_incremental_field=False, db_incremental_field_last_value="2026-07-20"
+ )
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(spec=ResumableSourceManager), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+
+ assert descriptions is CANONICAL_DESCRIPTIONS
+ assert set(descriptions) == set(ENDPOINTS)
+ for name, entry in descriptions.items():
+ assert entry["description"]
+ assert entry["docs_url"].startswith("https://learn.microsoft.com/")
+ # Every primary key must be documented, since that is the column users join on.
+ assert set(POWER_BI_ADMIN_ENDPOINTS[name].primary_keys) <= set(entry["columns"])
+
+ def test_documented_tables_render_without_credentials(self) -> None:
+ tables = self.source.get_documented_tables()
+
+ assert {table["name"] for table in tables} == set(ENDPOINTS)
+ for table in tables:
+ assert table["description"]
+ activity = next(table for table in tables if table["name"] == ACTIVITY_EVENTS_ENDPOINT)
+ assert "Incremental" in activity["sync_methods"]