Skip to content
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion metadata-ingestion/docs/sources/powerbi/powerbi_pre.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ If the principal only has the `Viewer` role on a workspace, the dataset listing

No Microsoft Entra application permissions need to change: both API families are authorized through the tenant settings and workspace roles above. The application requests a second token audience (`https://api.fabric.microsoft.com/.default`) in addition to the Power BI one.

What `workspace_apis` mode ingests: workspaces, dashboards, tiles, reports, report pages, datasets with tables, columns, measures and their descriptions, M expressions, table and column lineage (including DirectLake lineage to Fabric Lakehouses and Warehouses), paginated-report dataset bindings, and owners derived from workspace roles.
What `workspace_apis` mode ingests: workspaces, dashboards, tiles, reports, report pages, datasets with tables, columns, measures and their descriptions, M expressions, table and column lineage (including DirectLake lineage to Fabric Lakehouses and Warehouses), paginated-report dataset bindings, and owners derived from workspace roles. With `extract_report_field_usage` enabled, a Power BI report (not a paginated report, which never gets field usage or filters) whose definition is fetched and parsed gets, on each page chart, the model fields its visuals read, and its report-level and page-level filters as `filters` / `filterCount` properties on the report and its pages, with the filtered fields added to the page's `inputFields`; a report whose definition is refused or cannot be parsed gets neither its filters nor their fields. `filters` holds at most 50 entries: `filterCount` is the full count and `filtersTruncated: true` marks a shortened list. A rendered condition is cut to 500 characters and lists at most 20 `In` values, and a condition shape the connector does not recognize is kept as its raw JSON cut to 200 characters, so `filters` is a summary, not the complete filter definition. A filter's rendered condition includes the literal values it compares against (for example the selected categories or thresholds), so treat these properties as potentially containing business data.

In both metadata API modes a calculated column (one defined by a DAX expression) gets no column-level edge to the upstream table. In `workspace_apis` mode or with `enrich_from_item_definitions`, column lineage additionally follows each column's TMDL `sourceColumn`, so a field renamed in the model still points at the right column of the upstream table; a calculated table always gets table-level lineage from the model tables its DAX reads, and a measure that reads columns of other tables always gets column-level edges from them. Set `extract_dax_reference_lineage: true` to also derive lineage from the rest of the DAX: a calculated column gets column-level edges from the columns and measures its expression reads, and a measure that references another measure gets an edge from it. Edges are only emitted to tables and fields that exist in the parsed model. A DAX reference that does not resolve is counted in the report and surfaced as a `DAX Reference Not Resolved` warning. DAX is only read from TMDL definitions, so this applies to `workspace_apis` mode or `enrich_from_item_definitions`; without the flag only the table-qualified references of measures and the tables read by calculated tables are checked. Enabling the flag makes the connector write `upstreamLineage` on tables that previously had none (for example a measures-only table whose measures read each other), which replaces any upstreams authored for those tables in the UI. The flag requires `extract_column_level_lineage`.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,12 @@ class Constant:
REFRESH_SCHEDULE_PROPERTY_PREFIX = "refreshSchedule."
VISUAL_COUNT = "visualCount"
VISUAL_TYPES = "visualTypes"
FILTERS = "filters"
FILTER_COUNT = "filterCount"
FILTERS_TRUNCATED = "filtersTruncated"
FILTER_SCOPE = "scope"
FILTER_TARGET = "target"
FILTER_CONDITION = "condition"
TOP = "$top"
# Scan-API column types reproduced for TMDL-sourced columns
COLUMN_TYPE_DATA = "Data"
Expand Down Expand Up @@ -444,6 +450,9 @@ class PowerBiDashboardSourceReport(StaleEntityRemovalSourceReport):
report_definitions_parsed: int = 0
report_definitions_failed: int = 0
report_definition_parts_failed: int = 0
report_filters_parsed: int = 0
report_filters_failed: int = 0
report_filters_truncated: int = 0
report_pages_unmatched: int = 0
report_field_references_resolved: int = 0
report_field_references_unresolved: int = 0
Expand Down Expand Up @@ -1130,7 +1139,13 @@ class PowerBiDashboardSourceConfig(
default=False,
description="Read each report's definition to record which model columns and "
"measures its visuals use, emitted as `inputFields` on the page charts together "
"with visual counts and types. Adds one Fabric getDefinition call per report. "
"with visual counts and types. Report-level and page-level filters are included "
"as a `filters` property (a JSON-encoded list of name, type, target field and "
"condition) plus `filterCount` on the report and its page charts; the fields a "
"page filter reads join that page's `inputFields`, and the fields a report "
"filter reads join every page's. Note that a filter's condition includes the "
"literal values it compares against, which may be business data. "
"Adds one Fabric getDefinition call per report. "
"Requires `extract_reports`, `extract_dataset_schema` and either "
"`metadata_api_mode: workspace_apis` or `enrich_from_item_definitions`.",
)
Expand Down
53 changes: 50 additions & 3 deletions metadata-ingestion/src/datahub/ingestion/source/powerbi/powerbi.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
)
from datahub.ingestion.api.incremental_lineage_helper import (
convert_dashboard_info_to_patch,
dashboard_info_patch_builder,
)
from datahub.ingestion.api.source import (
CapabilityReport,
Expand Down Expand Up @@ -145,6 +146,14 @@
# Logger instance
logger = logging.getLogger(__name__)

# Most filters serialized into the `filters` custom property of a report or page.
MAX_FILTERS_IN_PROPERTY = 50
FILTER_PROPERTY_KEYS = (
Constant.FILTERS,
Constant.FILTER_COUNT,
Constant.FILTERS_TRUNCATED,
)


def _truncate(value: Optional[str]) -> Optional[str]:
if value is None or len(value) <= Constant.REFRESH_ERROR_MAX_LENGTH:
Expand Down Expand Up @@ -2306,6 +2315,25 @@ def to_datahub_work_units(
# Return set of work_unit
return deduplicate_list(work_units, lambda wu: wu.id)

def _filter_properties(
self, filters: List[powerbi_data_classes.ReportFilter]
) -> Dict[str, str]:
"""Report or page filters as `filters` (a JSON list) and `filterCount`
custom properties; empty when the report declares none. The list is
capped so a filter-heavy report cannot bloat the aspect; `filterCount`
still reports the full number."""
if not filters:
return {}
kept = filters[:MAX_FILTERS_IN_PROPERTY]
properties = {
Constant.FILTERS: json.dumps([f.to_dict() for f in kept]),
Constant.FILTER_COUNT: str(len(filters)),
}
if len(kept) < len(filters):
properties[Constant.FILTERS_TRUNCATED] = "true"
self.__reporter.report_filters_truncated += len(filters) - len(kept)
return properties
Comment thread
brock-acryl marked this conversation as resolved.
Resolved

def _page_input_fields_mcp(
self,
page: powerbi_data_classes.Page,
Expand Down Expand Up @@ -2405,6 +2433,7 @@ def to_chart_mcps(
custom_properties[Constant.VISUAL_COUNT] = str(page.visual_count)
if page.visual_types:
custom_properties[Constant.VISUAL_TYPES] = ", ".join(page.visual_types)
custom_properties.update(self._filter_properties(page.filters))

# Create chartInfo mcp
# Set chartUrl only if tile is created from Report
Expand Down Expand Up @@ -2512,6 +2541,7 @@ def report_to_dashboard(
lastModified=ChangeAuditStamps(),
dashboardUrl=report.webUrl,
datasetEdges=dataset_edges,
customProperties=self._filter_properties(report.filters),
)

info_mcp = MetadataChangeProposalWrapper(
Expand Down Expand Up @@ -2628,6 +2658,7 @@ def report_to_datahub_work_units(
# Paginated (RDL) reports without a shared dataset get their lineage
# solely from this fallback path.
dataset_urns.update(self.paginated_report_datasource_urns(report))
# Sorted so the emitted patch (and the golden files) are deterministic.
dataset_edges = [
EdgeClass(destinationUrn=dataset_urn)
for dataset_urn in sorted(dataset_urns)
Expand Down Expand Up @@ -3079,14 +3110,30 @@ def _get_dashboard_patch_work_unit(
work_unit.get_aspect_of_type(DashboardInfoClass)
)

if dashboard_info_aspect and self.source_config.patch_metadata:
if not (dashboard_info_aspect and self.source_config.patch_metadata):
return work_unit
if not self.source_config.extract_report_field_usage:
return convert_dashboard_info_to_patch(
work_unit.get_urn(),
dashboard_info_aspect,
work_unit.metadata.systemMetadata,
)
else:
return work_unit
# The patch only adds custom properties, so filter keys this run does
# not emit (the report lost its filters, or fell under the cap) would
# otherwise stay from an earlier run.
patch = dashboard_info_patch_builder(
work_unit.get_urn(),
dashboard_info_aspect,
work_unit.metadata.systemMetadata,
)
emitted = dashboard_info_aspect.customProperties or {}
for key in FILTER_PROPERTY_KEYS:
if key not in emitted:
patch.remove_custom_property(key)
Comment thread
brock-acryl marked this conversation as resolved.
Resolved
mcp = next(iter(patch.build()))
return MetadataWorkUnit(
id=MetadataWorkUnit.generate_workunit_id(mcp), mcp_raw=mcp
)

def get_excluded_workunit_processors(self):
# For modified_since, stale removal is handled per-workspace in get_workunits_internal()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,50 @@ class PageFieldReference:
field: str
kind: FieldReferenceKind

@property
def label(self) -> str:
"""``Table[Column]`` for a column, ``[Measure]`` for a measure (the
DAX spelling, so measures are not tied to their home table)."""
if self.kind == "measure":
return f"[{self.field}]"
return f"{self.table}[{self.field}]"


FilterScope = Literal["report", "page", "visual"]


@dataclass(frozen=True)
class ReportFilter:
"""A filter declared on a report, a page or a visual in the report
definition.

`target` is the field the filter is declared on (None when the definition
names none); `fields` is every model field the filter reads, the target
first, so a TopN's ordering measure counts as lineage too. `condition` is
a human-readable rendering when the condition's shape is simple, otherwise
the raw condition JSON (truncated); None when no condition is declared.
"""

scope: FilterScope
name: str
filter_type: Optional[str]
target: Optional[PageFieldReference]
fields: List[PageFieldReference]
condition: Optional[str]

def to_dict(self) -> Dict[str, str]:
result: Dict[str, str] = {
Constant.FILTER_SCOPE: self.scope,
Constant.NAME: self.name,
}
if self.filter_type:
result[Constant.TYPE] = self.filter_type
if self.target is not None:
result[Constant.FILTER_TARGET] = self.target.label
if self.condition:
result[Constant.FILTER_CONDITION] = self.condition
return result


@dataclass
class Page:
Expand All @@ -498,6 +542,7 @@ class Page:
field_references: List[PageFieldReference] = field(default_factory=list)
visual_count: Optional[int] = None
visual_types: List[str] = field(default_factory=list)
filters: List[ReportFilter] = field(default_factory=list)

def get_urn_part(self):
return f"pages.{self.id}"
Expand Down Expand Up @@ -609,6 +654,8 @@ class Report:
tags: List[str]
# Only populated for paginated reports without a shared dataset_id.
datasources: List["ReportDatasource"] = field(default_factory=list)
# Report-level filters; populated only when extract_report_field_usage is enabled.
filters: List[ReportFilter] = field(default_factory=list)

def get_urn_part(self):
return Report.get_urn_part_by_id(self.id)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1422,7 +1422,7 @@ def _fill_report_field_usage(self, workspace: Workspace, report: Report) -> None
self.reporter.report_definitions_failed += 1
self.reporter.warning(
title="Report Definition Not Parsed",
message="The report definition could not be parsed; the report keeps its pages but has no visual field usage.",
message="The report definition could not be parsed; the report keeps its pages but has no visual field usage or filters.",
context=context,
exc=e,
)
Expand All @@ -1436,6 +1436,15 @@ def _fill_report_field_usage(self, workspace: Workspace, report: Report) -> None
message="Some parts of the report definition were not valid JSON; the visuals they describe are missing from the page's inputFields.",
context=f"{context}, parts={failed_parts}",
)
if parsed.failed_filters:
self.reporter.report_filters_failed += len(parsed.failed_filters)
self.reporter.warning(
title="Report Filter Not Parsed",
message="Some report or page filters in the report definition could not be read; they are missing from the `filters` properties and the page's inputFields.",
context=f"{context}, filters={parsed.failed_filters}",
)
report.filters = parsed.filters
self.reporter.report_filters_parsed += len(parsed.filters)
for page in report.pages:
parsed_page: Optional[ParsedPage] = parsed.pages.get(page.name)
if parsed_page is None and page.displayName:
Expand All @@ -1447,10 +1456,14 @@ def _fill_report_field_usage(self, workspace: Workspace, report: Report) -> None
page.name,
report.id,
)
# Report-level filters apply to every page, matched or not.
page.field_references = parsed.report_filter_field_refs()
continue
page.visual_count = len(parsed_page.visuals)
page.visual_types = parsed_page.visual_types
page.field_references = parsed_page.field_refs
page.filters = parsed_page.filters
Comment thread
brock-acryl marked this conversation as resolved.
Resolved
self.reporter.report_filters_parsed += len(parsed_page.filters)
page.field_references = parsed.page_field_refs(parsed_page)
Comment thread
brock-acryl marked this conversation as resolved.
Resolved

def _fabric_artifacts_from_items(
self, workspace: Workspace, items: List[FabricItem]
Expand Down
Loading