From 112305ad037daabaec54f8f89c01ecaff16bcac1 Mon Sep 17 00:00:00 2001 From: Steve Baldwin Date: Tue, 27 Oct 2026 08:13:35 +0000 Subject: [PATCH 01/12] feat(ingestion/fabric): emit notebook column lineage from code renames When code reconciliation is on, map notebook column renames onto the Spark job, including select lists built before they are applied. Native executor runs also install a missing source extra so the plugin can load. Co-authored-by: Cursor --- .../fabric-onelake/fabric-onelake_post.md | 2 +- .../src/datahub/executor/execution/runner.py | 59 ++ .../ingestion/source/fabric/onelake/config.py | 9 +- .../fabric/onelake/notebook_code_lineage.py | 742 +++++++++++++++++- .../source/fabric/onelake/notebook_jobs.py | 99 ++- .../tests/unit/executor/test_runner.py | 27 + .../test_notebook_code_lineage.py | 223 ++++++ 7 files changed, 1133 insertions(+), 28 deletions(-) diff --git a/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md b/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md index 1ab05bb78f94..541215194ca2 100644 --- a/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md +++ b/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md @@ -375,7 +375,7 @@ The caller needs `Workspace.Read.All` or `Workspace.ReadWrite.All`. `notebook_execution.enabled` (off by default, requires `include_notebooks: true`) also models each notebook as a **pipeline**: one DataFlow per notebook (subtype "Fabric Spark Pipeline"), and under it one Spark-job DataJob (subtype "Fabric Spark Job") **per table the notebook writes**. Each job carries that output table's own upstreams, so lineage renders as `input → [job] → output` — precise table-to-table edges with the notebook transformation attributed, not one job with a cross-product of every table the notebook ever read and wrote. When one output table is itself an input to another output table's job in the same notebook, the two jobs are chained **job → job**. The lineage lives on the jobs, not the notebook dataset, so the notebook's code and its lineage (process) stay cleanly separated. It emits two things from the notebook's run history over `notebook_execution.history_days` (default 7): table-level **lineage** on the per-output jobs, and a **run history** of `DataProcessInstance`s on those jobs. -**Lineage.** Fabric exposes no API that lists the tables a notebook reads or writes, and the source text hides them when paths are built at run time (e.g. `spark.read.format("delta").load(f"{source}{table}")` or `DeltaTable.forPath(spark, target)`). So the connector reads the **resolved Spark physical plans** of each run instead: for every run in the window it fetches the run's SQL executions from the Spark monitoring API (`livySessions` + the Spark History Server SQL API) and extracts the `abfss://` OneLake table paths actually read and written. Attribution is **order-aware within a run**: a notebook usually reads a table in one Spark execution and writes a derived table in a later execution whose plan references a cached relation rather than the source path, so each written table is credited with the tables read earlier in the same run (the read set resets after each write). This keeps independent, sequential pipelines precise instead of collapsing a run into a cross-product, and recovers read-then-write edges that span executions. Those paths map directly to the GUID-based dataset URNs the connector emits. Set `notebook_execution.reconcile_code: true` (off by default; requires `notebook_execution.enabled`) to narrow that plan lineage with the notebook source when it is Python: each write is kept only with the tables its dataframe actually uses, and a write that exists only in a commented-out cell is dropped. The plans still supply the resolved OneLake path, so a table loaded from a run-time path stays attached to the name in the code. With the flag off, plan lineage is emitted unchanged. Because a notebook may apply only specific cells on a given run, lineage is **accumulated across all of the notebook's runs** in the window, giving a complete picture over time. Only edges to tables ingested in the same run are kept; GUID-built URNs that do not match an ingested table, and internal Spark scratch paths (shuffle, lakehouse-warmup), are dropped. +**Lineage.** Fabric exposes no API that lists the tables a notebook reads or writes, and the source text hides them when paths are built at run time (e.g. `spark.read.format("delta").load(f"{source}{table}")` or `DeltaTable.forPath(spark, target)`). So the connector reads the **resolved Spark physical plans** of each run instead: for every run in the window it fetches the run's SQL executions from the Spark monitoring API (`livySessions` + the Spark History Server SQL API) and extracts the `abfss://` OneLake table paths actually read and written. Attribution is **order-aware within a run**: a notebook usually reads a table in one Spark execution and writes a derived table in a later execution whose plan references a cached relation rather than the source path, so each written table is credited with the tables read earlier in the same run (the read set resets after each write). This keeps independent, sequential pipelines precise instead of collapsing a run into a cross-product, and recovers read-then-write edges that span executions. Those paths map directly to the GUID-based dataset URNs the connector emits. Set `notebook_execution.reconcile_code: true` (off by default; requires `notebook_execution.enabled`) to narrow that plan lineage with the notebook source when it is Python: each write is kept only with the tables its dataframe actually uses, and a write that exists only in a commented-out cell is dropped. The same pass reads column renames — `col(src).alias(dst)`, a `{source: target}` mapping dict, `alias.*` after a join, and `df["column"]` — and emits them as column-level lineage on that write's job. The plans still supply the resolved OneLake path, so a table loaded from a run-time path stays attached to the name in the code. With the flag off, plan lineage is emitted unchanged. Because a notebook may apply only specific cells on a given run, lineage is **accumulated across all of the notebook's runs** in the window, giving a complete picture over time. Only edges to tables ingested in the same run are kept; GUID-built URNs that do not match an ingested table, and internal Spark scratch paths (shuffle, lakehouse-warmup), are dropped. **Run history.** A Fabric run executes the whole notebook (the Job Scheduler reports one status per run, not per table), so for each run in the window the connector emits a `DataProcessInstance` on each of the notebook's per-output jobs — the whole-notebook run is recorded against every job it contains, falling back to the DataFlow only when a run resolved no per-table lineage — read from the Job Scheduler `GET /workspaces/{id}/items/{itemId}/jobs/instances` API. Each instance records start/end time and the run result (success / failure / skipped). diff --git a/metadata-ingestion/src/datahub/executor/execution/runner.py b/metadata-ingestion/src/datahub/executor/execution/runner.py index d5640fbb8a6c..13230ce583d0 100644 --- a/metadata-ingestion/src/datahub/executor/execution/runner.py +++ b/metadata-ingestion/src/datahub/executor/execution/runner.py @@ -107,6 +107,64 @@ def _validate_wheel_url(url: str) -> bool: return True +def _metadata_ingestion_root() -> Optional[pathlib.Path]: + """Checkout that owns this module, when native mode is running from source.""" + candidate = pathlib.Path(__file__).resolve().parents[4] + if (candidate / "setup.py").is_file(): + return candidate + return None + + +def _plugin_module_missing(plugin: str) -> bool: + """True when the source plugin cannot be imported in this environment.""" + try: + from importlib.metadata import entry_points + + match = next( + ( + entry_point + for entry_point in entry_points( + group="datahub.ingestion.source.plugins" + ) + if entry_point.name == plugin + ), + None, + ) + if match is None: + return True + match.load() + except ModuleNotFoundError: + return True + return False + + +async def _install_native_plugin_extra( + venv_config: "VenvConfig", runner: "SubprocessRunner" +) -> None: + """Install this checkout's plugin extra into the process environment. + + Native mode runs the mounted source with the executor's own environment. + That environment is not built with every source extra, so a plugin such as + fabric-onelake fails to register (``sqlparse`` and the rest of its extra + are absent) unless we install them here. + """ + plugin = venv_config.main_plugin + if not plugin or not _plugin_module_missing(plugin): + return + root = _metadata_ingestion_root() + if root is None: + raise RuntimeError( + f"{plugin} is missing a dependency, and native mode has no " + "metadata-ingestion checkout to install it from." + ) + extras = ",".join(dict.fromkeys([plugin, *venv_config.extra_pip_plugins])) + requirement = f"{root}[{extras}]" + runner._logs.append( + f"Native environment cannot import {plugin}. Installing {requirement}\n" + ) + await runner.execute([_find_uv(), "pip", "install", "-e", requirement]) + + def _bundled_constraints_path(venv_loc: pathlib.Path) -> Optional[pathlib.Path]: """Locate datahub/constraints.txt inside an installed acryl-datahub.""" matches = list(venv_loc.glob("lib/python*/site-packages/datahub/constraints.txt")) @@ -493,6 +551,7 @@ async def setup_venv( validate_dependency_resolution_enabled(venv_config.version) if venv_config.version == VENV_VERSION_NATIVE: + await _install_native_plugin_extra(venv_config, runner) return VenvReference( venv_loc=pathlib.Path(sys.prefix), venv_config=venv_config, diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py index d6582cfbceb7..6ebc963f890c 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py @@ -107,9 +107,12 @@ class NotebookExecutionConfig(ConfigModel): description=( "Narrow Spark-plan lineage using the notebook source. Each write " "keeps only the tables its dataframe actually uses, and a write that " - "exists only in a commented-out cell is dropped. The plans still " - "supply the resolved OneLake path. Off by default, so plan lineage " - "is emitted unchanged. Requires `enabled=True`." + "exists only in a commented-out cell is dropped. Column renames in " + "that dataframe (`col(src).alias(dst)`, a `{source: target}` mapping, " + "`alias.*`, and `df[\"column\"]`) are emitted as column-level lineage " + "on the job. The plans still supply the resolved OneLake path. Off " + "by default, so plan lineage is emitted unchanged. Requires " + "`enabled=True`." ), ) diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py index 7e65b1737b06..65f387149187 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py @@ -7,15 +7,20 @@ The source text names those tables even when the path is built at run time (``f"{source}orders"``), and it shows which dataframe each write actually uses. Commented-out cells are not real reads or writes. This module recovers that -per-target source set. The caller keeps an edge only when the executed plans +per-target source set, and the column renames that dataframe applies: +``col(src).alias(dst)``, a ``{source: target}`` mapping dict, ``alias.*``, +and ``df["column"]``. The caller keeps an edge only when the executed plans also saw the same source and target, so the resolved OneLake path still comes from the run. """ +from __future__ import annotations + import ast +import copy import logging -from dataclasses import dataclass -from typing import Callable, Dict, Iterable, List, Optional, Set, Tuple +from dataclasses import dataclass, field +from typing import Callable, Dict, Iterable, List, Optional, Set, Tuple, Union from datahub.ingestion.source.fabric.onelake.notebook_spark_lineage import ( SparkTableRef, @@ -32,13 +37,23 @@ class CodeTable: schema: Optional[str] = None -def extract_notebook_code_lineage( - source: str, -) -> Optional[Dict[CodeTable, Set[CodeTable]]]: - """Map each table the notebook writes to the tables that write uses. +# downstream column -> {(upstream table, upstream column)} +ColumnLineage = Dict[str, Set[Tuple[CodeTable, str]]] + + +@dataclass +class NotebookCodeAnalysis: + """Table edges and column renames recovered from one notebook.""" + + tables: Dict[CodeTable, Set[CodeTable]] + columns: Dict[CodeTable, ColumnLineage] + + +def analyze_notebook_code(source: str) -> Optional[NotebookCodeAnalysis]: + """Recover per-write table lineage and column renames from notebook source. Returns None when ``source`` is not parseable Python, so the caller can - keep the Spark-plan lineage unchanged. An empty dict means the code parsed + keep the Spark-plan lineage unchanged. Empty mappings mean the code parsed and contains no writes. """ try: @@ -49,7 +64,31 @@ def extract_notebook_code_lineage( extractor = _Extractor() extractor.walk(tree.body) - return extractor.lineage + columns: Dict[CodeTable, ColumnLineage] = {} + for target, mapping in extractor.column_lineage.items(): + kept = { + column: {(ref.table, ref.column) for ref in refs} + for column, refs in mapping.items() + if refs + } + if kept: + columns[target] = kept + return NotebookCodeAnalysis(tables=extractor.lineage, columns=columns) + + +def extract_notebook_code_lineage( + source: str, +) -> Optional[Dict[CodeTable, Set[CodeTable]]]: + """Map each table the notebook writes to the tables that write uses. + + Returns None when ``source`` is not parseable Python, so the caller can + keep the Spark-plan lineage unchanged. An empty dict means the code parsed + and contains no writes. + """ + analysis = analyze_notebook_code(source) + if analysis is None: + return None + return analysis.tables def reconcile_spark_lineage( @@ -92,6 +131,33 @@ def reconcile_spark_lineage( return reconciled +def reconcile_column_lineage( + columns: Dict[CodeTable, ColumnLineage], + execution: Dict[SparkTableRef, Set[SparkTableRef]], + normalize: Callable[[str], str], +) -> Dict[SparkTableRef, Dict[str, Set[Tuple[SparkTableRef, str]]]]: + """Attach code column renames to the Spark refs the plans resolved. + + A rename is kept only when both tables appear in that write's executed + inputs. The column names stay as the notebook wrote them. + """ + reconciled: Dict[SparkTableRef, Dict[str, Set[Tuple[SparkTableRef, str]]]] = {} + for target, mapping in columns.items(): + outputs = _resolve(target, execution, normalize) + for output in outputs: + inputs = execution.get(output, set()) + colmap = reconciled.setdefault(output, {}) + for downstream, upstreams in mapping.items(): + resolved: Set[Tuple[SparkTableRef, str]] = set() + for code_table, column in upstreams: + for ref in _resolve(code_table, inputs, normalize): + if ref != output and column: + resolved.add((ref, column)) + if resolved: + colmap.setdefault(downstream, set()).update(resolved) + return reconciled + + def _resolve( code: CodeTable, pool: Iterable[SparkTableRef], @@ -273,12 +339,90 @@ def _tail_has_tables(expr: ast.expr, env: Dict[str, str]) -> bool: return tail is not None and "Tables" in tail +@dataclass(frozen=True) +class _ColRef: + table: CodeTable + column: str + + +@dataclass +class _Projection: + """Columns of one dataframe expression. + + ``passthrough`` is a table read whose columns flow through under their own + names. ``explicit`` is the columns a select or withColumn introduced. + ``projected`` means a select replaced the schema, so only ``explicit`` + remains. ``aliases`` are the dataframes a join can still name. + """ + + reads: Set[CodeTable] = field(default_factory=set) + passthrough: Optional[CodeTable] = None + explicit: Dict[str, Set[_ColRef]] = field(default_factory=dict) + dropped: Set[str] = field(default_factory=set) + projected: bool = False + alias: Optional[str] = None + aliases: Dict[str, _Projection] = field(default_factory=dict) + + +# Dataframe methods that keep or reshape columns. Anything else (count, show) +# is not a dataframe we can follow. +_DF_METHODS = { + "alias", + "select", + "withColumn", + "withColumnRenamed", + "drop", + "filter", + "where", + "distinct", + "dropDuplicates", + "orderBy", + "sort", + "limit", + "persist", + "cache", + "hint", + "repartition", + "coalesce", + "dropna", + "fillna", + "join", + "union", + "unionAll", + "unionByName", +} +_COLUMN_FUNCS = {"col", "column", "upper", "lower", "trim", "ltrim", "rtrim"} +_LITERAL_FUNCS = {"lit", "current_timestamp", "current_date", "now", "expr"} + + +def _clone(proj: _Projection) -> _Projection: + return _Projection( + reads=set(proj.reads), + passthrough=proj.passthrough, + explicit={column: set(refs) for column, refs in proj.explicit.items()}, + dropped=set(proj.dropped), + projected=proj.projected, + alias=proj.alias, + aliases=dict(proj.aliases), + ) + + class _Extractor: def __init__(self) -> None: self.lineage: Dict[CodeTable, Set[CodeTable]] = {} + self.column_lineage: Dict[CodeTable, Dict[str, Set[_ColRef]]] = {} self._frames: Dict[str, Set[CodeTable]] = {} self._produced: Dict[str, Set[CodeTable]] = {} self._strings: Dict[str, str] = {} + self._dicts: Dict[str, Dict[str, str]] = {} + self._lists: Dict[str, List[str]] = {} + self._col_lists: Dict[str, List[ast.expr]] = {} + self._bools: Dict[str, bool] = {} + self._projections: Dict[str, _Projection] = {} + self._exprs: Dict[str, ast.expr] = {} + self._fns: Dict[str, Union[ast.FunctionDef, ast.AsyncFunctionDef]] = {} + self._executing: Set[str] = set() + self._return_projection: Optional[_Projection] = None # function name -> (dataframe param, path param, dataframe index, path index) self._writers: Dict[str, Tuple[str, str, int, int]] = {} @@ -288,6 +432,7 @@ def walk(self, stmts: List[ast.stmt]) -> None: def _stmt(self, stmt: ast.stmt) -> None: if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)): + self._fns[stmt.name] = stmt writer = _writer_params(stmt) if writer is not None: self._writers[stmt.name] = writer @@ -312,8 +457,18 @@ def _stmt(self, stmt: ast.stmt) -> None: self._writes_in(stmt.value) return if isinstance(stmt, ast.If): - self.walk(stmt.body) - self.walk(stmt.orelse) + cond = self._eval_bool(stmt.test) + if cond is True: + self.walk(stmt.body) + elif cond is False: + self.walk(stmt.orelse) + else: + self.walk(stmt.body) + self.walk(stmt.orelse) + return + if isinstance(stmt, ast.Return) and stmt.value is not None: + self._writes_in(stmt.value) + self._return_projection = self._projection_of(stmt.value) return if isinstance(stmt, (ast.For, ast.AsyncFor, ast.While)): self.walk(stmt.body) @@ -331,17 +486,54 @@ def _stmt(self, stmt: ast.stmt) -> None: def _bind(self, name: str, value: ast.expr) -> None: reads, produced = self._collect(value) + proj = self._projection_of(value) + if proj is not None: + reads |= proj.reads tail = _eval_tail(value, self._strings) if tail is not None: self._strings[name] = tail else: self._strings.pop(name, None) + mapping = _eval_dict(value) + if mapping is None and isinstance(value, ast.Name): + mapping = self._dicts.get(value.id) + if mapping is not None: + self._dicts[name] = mapping + else: + self._dicts.pop(name, None) + values = _eval_str_list(value) + if values is None and isinstance(value, ast.Name): + values = self._lists.get(value.id) + if values is not None: + self._lists[name] = values + else: + self._lists.pop(name, None) + column_exprs = self._expand_column_exprs(value) + if column_exprs is not None: + self._col_lists[name] = column_exprs + elif isinstance(value, ast.Name) and value.id in self._col_lists: + self._col_lists[name] = self._col_lists[value.id] + else: + self._col_lists.pop(name, None) + flag = self._eval_bool(value) + if flag is not None and not isinstance(value, ast.Name): + self._bools[name] = flag + elif isinstance(value, ast.Name) and value.id in self._bools: + self._bools[name] = self._bools[value.id] + else: + self._bools.pop(name, None) if reads or produced or _rooted_in_frame(value, self._frames): self._frames[name] = reads self._produced[name] = produced else: self._frames.pop(name, None) self._produced.pop(name, None) + if proj is not None: + self._projections[name] = proj + self._exprs.pop(name, None) + else: + self._projections.pop(name, None) + self._exprs[name] = value def _writes_in(self, expr: ast.AST) -> None: if isinstance(expr, ast.Call): @@ -406,6 +598,9 @@ def _writer_args( def _add_edge(self, target: CodeTable, df_expr: ast.expr) -> None: reads, produced = self._collect(df_expr) + proj = self._projection_of(df_expr) + if proj is not None: + reads |= proj.reads sources = { source for source in reads | produced if not _same_table(source, target) } @@ -413,6 +608,461 @@ def _add_edge(self, target: CodeTable, df_expr: ast.expr) -> None: root = _root_name(df_expr) if root is not None: self._produced.setdefault(root, set()).add(target) + if proj is not None: + self._record_columns(target, proj) + + def _record_columns(self, target: CodeTable, proj: _Projection) -> None: + bucket = self.column_lineage.setdefault(target, {}) + for column, refs in proj.explicit.items(): + if column in proj.dropped: + continue + kept = {ref for ref in refs if not _same_table(ref.table, target)} + if kept: + bucket.setdefault(column, set()).update(kept) + + def _projection_of(self, expr: ast.AST) -> Optional[_Projection]: + if isinstance(expr, ast.Name): + return self._projections.get(expr.id) + if not isinstance(expr, ast.Call): + return None + called = self._call_function(expr) + if called is not None: + return called + read = _read_table(expr, self._strings) + if read is not None: + return _Projection(reads={read}, passthrough=read) + func = expr.func + if not isinstance(func, ast.Attribute) or func.attr not in _DF_METHODS: + return None + base = self._projection_of(func.value) + if base is None: + return None + return self._apply_method(base, func.attr, expr) + + def _apply_method( + self, base: _Projection, attr: str, call: ast.Call + ) -> Optional[_Projection]: + if attr in {"union", "unionAll", "unionByName"}: + return self._union(base, call) + handler = { + "alias": self._alias, + "select": self._select, + "withColumn": self._with_column, + "withColumnRenamed": self._rename_column, + "drop": self._drop, + "join": self._join, + }.get(attr) + if handler is None: + return _clone(base) + return handler(base, call) + + def _alias(self, base: _Projection, call: ast.Call) -> _Projection: + name = _eval_tail(call.args[0], self._strings) if call.args else None + if not name: + return base + cloned = _clone(base) + cloned.alias = name + return cloned + + def _select(self, base: _Projection, call: ast.Call) -> _Projection: + explicit: Dict[str, Set[_ColRef]] = {} + for arg in call.args: + for column, refs in self._eval_columns(arg, base): + explicit.setdefault(column, set()).update(refs) + reads = set(base.reads) + for refs in explicit.values(): + reads.update(ref.table for ref in refs) + return _Projection(reads=reads, explicit=explicit, projected=True) + + def _with_column(self, base: _Projection, call: ast.Call) -> _Projection: + if len(call.args) < 2: + return base + name = _eval_tail(call.args[0], self._strings) + if not name: + return base + cloned = _clone(base) + cloned.explicit[name] = self._origins_in(call.args[1], base) + cloned.dropped.discard(name) + return cloned + + def _rename_column(self, base: _Projection, call: ast.Call) -> _Projection: + if len(call.args) < 2: + return base + old = _eval_tail(call.args[0], self._strings) + new = _eval_tail(call.args[1], self._strings) + if not old or not new: + return base + cloned = _clone(base) + origins = self._lookup(base, old) + if cloned.projected: + cloned.explicit.pop(old, None) + else: + cloned.dropped.add(old) + cloned.explicit[new] = origins + cloned.dropped.discard(new) + return cloned + + def _drop(self, base: _Projection, call: ast.Call) -> _Projection: + cloned = _clone(base) + for arg in call.args: + name = _eval_tail(arg, self._strings) + if not name: + continue + if cloned.projected: + cloned.explicit.pop(name, None) + else: + cloned.dropped.add(name) + return cloned + + def _join(self, base: _Projection, call: ast.Call) -> _Projection: + if not call.args: + return base + right = self._projection_of(call.args[0]) + if right is None: + return base + return _joined(base, right) + + def _union(self, base: _Projection, call: ast.Call) -> _Projection: + if not call.args: + return base + right = self._projection_of(call.args[0]) + if right is None or not base.projected or not right.projected: + return _Projection(reads=base.reads | (right.reads if right else set())) + explicit = {column: set(refs) for column, refs in base.explicit.items()} + for column, refs in right.explicit.items(): + explicit.setdefault(column, set()).update(refs) + return _Projection( + reads=base.reads | right.reads, explicit=explicit, projected=True + ) + + def _call_function(self, call: ast.Call) -> Optional[_Projection]: + if not isinstance(call.func, ast.Name): + return None + fn = self._fns.get(call.func.id) + if fn is None or call.func.id in self._executing or not _returns_value(fn): + return None + bindings = self._capture_bindings(fn, call) + saved = self._snapshot() + self._executing.add(call.func.id) + try: + for name, captured in bindings: + self._install(name, captured) + self._return_projection = None + self.walk(fn.body) + return self._return_projection + finally: + self._executing.discard(call.func.id) + self._restore(saved) + + def _snapshot(self) -> Tuple: + return ( + dict(self._frames), + dict(self._produced), + dict(self._strings), + dict(self._dicts), + dict(self._lists), + dict(self._col_lists), + dict(self._bools), + dict(self._projections), + dict(self._exprs), + self._return_projection, + ) + + def _restore(self, snap: Tuple) -> None: + ( + self._frames, + self._produced, + self._strings, + self._dicts, + self._lists, + self._col_lists, + self._bools, + self._projections, + self._exprs, + self._return_projection, + ) = snap + + def _capture_bindings( + self, fn: Union[ast.FunctionDef, ast.AsyncFunctionDef], call: ast.Call + ) -> List[Tuple[str, Tuple[str, object]]]: + params = [arg.arg for arg in [*fn.args.posonlyargs, *fn.args.args]] + defaults: List[Optional[ast.expr]] = [None] * ( + len(params) - len(fn.args.defaults) + ) + list(fn.args.defaults) + bound: Dict[str, ast.expr] = {} + for keyword in call.keywords: + if keyword.arg: + bound[keyword.arg] = keyword.value + for index, arg in enumerate(call.args): + if index < len(params): + bound[params[index]] = arg + for name, default in zip(params, defaults, strict=False): + if name not in bound and default is not None: + bound[name] = default + return [(name, self._capture(expr)) for name, expr in bound.items()] + + def _capture(self, expr: ast.expr) -> Tuple[str, object]: + if isinstance(expr, ast.Name) and expr.id in self._projections: + return ("proj", self._projections[expr.id]) + if isinstance(expr, ast.Name) and expr.id in self._dicts: + return ("dict", self._dicts[expr.id]) + mapping = _eval_dict(expr) + if mapping is not None: + return ("dict", mapping) + if isinstance(expr, ast.Name) and expr.id in self._lists: + return ("list", self._lists[expr.id]) + values = _eval_str_list(expr) + if values is not None: + return ("list", values) + flag = self._eval_bool(expr) + if flag is not None: + return ("bool", flag) + text = _eval_tail(expr, self._strings) + if text is not None: + return ("str", text) + return ("expr", expr) + + def _install(self, name: str, captured: Tuple[str, object]) -> None: + kind, value = captured + if kind == "str" and isinstance(value, str): + self._strings[name] = value + elif kind == "bool" and isinstance(value, bool): + self._bools[name] = value + elif kind == "dict" and isinstance(value, dict): + self._dicts[name] = value + elif kind == "list" and isinstance(value, list): + self._lists[name] = value + elif kind == "proj" and isinstance(value, _Projection): + self._projections[name] = value + self._frames[name] = set(value.reads) + + def _eval_bool(self, expr: ast.AST) -> Optional[bool]: + if isinstance(expr, ast.Constant) and isinstance(expr.value, bool): + return expr.value + if isinstance(expr, ast.Name) and expr.id in self._bools: + return self._bools[expr.id] + return None + + def _eval_columns( + self, expr: ast.expr, current: _Projection + ) -> List[Tuple[str, Set[_ColRef]]]: + if isinstance(expr, ast.Starred): + return self._eval_expanded(expr.value, current) + alias = self._alias_name(expr) + if ( + alias + and isinstance(expr, ast.Call) + and isinstance(expr.func, ast.Attribute) + ): + origins = self._origins_in(expr.func.value, current) + return [(alias, origins)] + named = _named_column(expr, self._strings) + if named is not None: + return self._resolve_named(named, current) + if isinstance(expr, ast.Subscript): + ref = self._subscript(expr) + if ref is not None: + return [ref] + if isinstance(expr, ast.Constant) and isinstance(expr.value, str): + return self._resolve_named(expr.value, current) + return [] + + def _eval_expanded( + self, expr: ast.expr, current: _Projection + ) -> List[Tuple[str, Set[_ColRef]]]: + if ( + isinstance(expr, (ast.ListComp, ast.GeneratorExp)) + and len(expr.generators) == 1 + ): + bindings = self._comprehension_bindings(expr.generators[0]) + if bindings is None: + return [] + out: List[Tuple[str, Set[_ColRef]]] = [] + saved = dict(self._strings) + try: + for binding in bindings: + self._strings.update(binding) + out.extend(self._eval_columns(expr.elt, current)) + finally: + self._strings = saved + return out + if isinstance(expr, ast.IfExp): + cond = self._eval_bool(expr.test) + chosen = expr.body if cond else expr.orelse if cond is not None else None + if chosen is None: + return [] + return self._eval_expanded(chosen, current) + if isinstance(expr, (ast.List, ast.Tuple)): + out = [] + for elt in expr.elts: + out.extend(self._eval_columns(elt, current)) + return out + stored = self._expand_column_exprs(expr) + if stored: + out = [] + for elt in stored: + out.extend(self._eval_columns(elt, current)) + return out + return self._eval_columns(expr, current) + + def _expand_column_exprs(self, expr: ast.expr) -> Optional[List[ast.expr]]: + """Column expressions behind ``select(*saved_list)``. + + Notebooks often build that list as comprehensions added together + (``[col(f"p.{c}").alias(f"person_{c}") for c in person_cols] + ...``) + and only apply it later. + """ + if isinstance(expr, ast.BinOp) and isinstance(expr.op, ast.Add): + left = self._expand_column_exprs(expr.left) + right = self._expand_column_exprs(expr.right) + if left is None or right is None: + return None + return left + right + if isinstance(expr, ast.Name): + return self._col_lists.get(expr.id) + if ( + isinstance(expr, (ast.ListComp, ast.GeneratorExp)) + and len(expr.generators) == 1 + and not expr.generators[0].ifs + ): + bindings = self._comprehension_bindings(expr.generators[0]) + if bindings is None: + return None + return [_substitute_names(expr.elt, binding) for binding in bindings] + return None + + def _comprehension_bindings( + self, gen: ast.comprehension + ) -> Optional[List[Dict[str, str]]]: + if gen.ifs: + return None + mapping = self._dict_iter(gen.iter) + if ( + mapping is not None + and isinstance(gen.target, ast.Tuple) + and len(gen.target.elts) == 2 + and all(isinstance(elt, ast.Name) for elt in gen.target.elts) + ): + src, dst = gen.target.elts + assert isinstance(src, ast.Name) and isinstance(dst, ast.Name) + return [{src.id: key, dst.id: value} for key, value in mapping.items()] + if isinstance(gen.target, ast.Name) and isinstance(gen.iter, ast.Name): + values = self._lists.get(gen.iter.id) + if values is not None: + return [{gen.target.id: value} for value in values] + return None + + def _dict_iter(self, expr: ast.expr) -> Optional[Dict[str, str]]: + if ( + isinstance(expr, ast.Call) + and isinstance(expr.func, ast.Attribute) + and expr.func.attr == "items" + and isinstance(expr.func.value, ast.Name) + ): + return self._dicts.get(expr.func.value.id) + return None + + def _alias_name(self, expr: ast.expr) -> Optional[str]: + if ( + isinstance(expr, ast.Call) + and isinstance(expr.func, ast.Attribute) + and expr.func.attr == "alias" + and expr.args + ): + return _eval_tail(expr.args[0], self._strings) + return None + + def _resolve_named( + self, name: str, current: _Projection + ) -> List[Tuple[str, Set[_ColRef]]]: + if name == "*" or name.endswith(".*"): + qual = None if name == "*" else name[: -len(".*")] + proj = self._qualified(current, qual) if qual is not None else current + if proj is None or not proj.projected: + return [] + return [ + (column, set(refs)) + for column, refs in proj.explicit.items() + if column not in proj.dropped + ] + if "." in name: + qual, column = name.split(".", 1) + proj = self._qualified(current, qual) + if proj is None: + return [] + return [(column, self._lookup(proj, column))] + return [(name, self._lookup(current, name))] + + def _qualified(self, current: _Projection, qual: str) -> Optional[_Projection]: + if current.alias == qual: + return current + return current.aliases.get(qual) or self._projections.get(qual) + + def _lookup(self, proj: _Projection, column: str) -> Set[_ColRef]: + if column in proj.dropped and column not in proj.explicit: + return set() + if proj.projected or column in proj.explicit: + if column in proj.explicit: + return set(proj.explicit[column]) + if proj.projected: + return set() + if proj.passthrough is not None: + return {_ColRef(proj.passthrough, column)} + return set() + + def _subscript(self, expr: ast.Subscript) -> Optional[Tuple[str, Set[_ColRef]]]: + if not isinstance(expr.value, ast.Name): + return None + proj = self._projections.get(expr.value.id) + if proj is None: + return None + column = _eval_tail(expr.slice, self._strings) + if not column: + return None + return (column, self._lookup(proj, column)) + + def _origins_in( + self, + expr: ast.AST, + current: _Projection, + seen: Optional[Set[int]] = None, + names: Optional[Set[str]] = None, + ) -> Set[_ColRef]: + if seen is None: + seen = set() + if names is None: + names = set() + if id(expr) in seen: + return set() + seen.add(id(expr)) + if isinstance(expr, ast.Name): + if expr.id in names or expr.id in self._projections: + return set() + stored = self._exprs.get(expr.id) + if stored is None: + return set() + names.add(expr.id) + return self._origins_in(stored, current, seen, names) + if isinstance(expr, ast.Subscript): + ref = self._subscript(expr) + return set(ref[1]) if ref is not None else set() + if isinstance(expr, ast.Call) and _call_name(expr) in _LITERAL_FUNCS: + return set() + if ( + isinstance(expr, ast.Call) + and _call_name(expr) in _COLUMN_FUNCS + and expr.args + ): + named = _eval_tail(expr.args[0], self._strings) + if named and not named.endswith(".*"): + found: Set[_ColRef] = set() + for _column, refs in self._resolve_named(named, current): + found.update(refs) + return found + found = set() + for child in ast.iter_child_nodes(expr): + found.update(self._origins_in(child, current, seen, names)) + return found def _collect(self, expr: ast.AST) -> Tuple[Set[CodeTable], Set[CodeTable]]: reads: Set[CodeTable] = set() @@ -432,6 +1082,76 @@ def _collect(self, expr: ast.AST) -> Tuple[Set[CodeTable], Set[CodeTable]]: return reads, produced +def _joined(left: _Projection, right: _Projection) -> _Projection: + aliases = dict(left.aliases) + aliases.update(right.aliases) + if left.alias: + aliases[left.alias] = left + if right.alias: + aliases[right.alias] = right + return _Projection(reads=left.reads | right.reads, aliases=aliases) + + +def _returns_value(fn: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> bool: + return any( + isinstance(node, ast.Return) and node.value is not None for node in ast.walk(fn) + ) + + +def _call_name(expr: ast.Call) -> Optional[str]: + func = expr.func + if isinstance(func, ast.Attribute): + return func.attr + if isinstance(func, ast.Name): + return func.id + return None + + +def _named_column(expr: ast.expr, env: Dict[str, str]) -> Optional[str]: + """Column named by ``col("name")`` or ``F.col("name")``, before any alias.""" + if not isinstance(expr, ast.Call) or _call_name(expr) not in {"col", "column"}: + return None + if not expr.args: + return None + return _eval_tail(expr.args[0], env) + + +def _eval_dict(expr: ast.expr) -> Optional[Dict[str, str]]: + if not isinstance(expr, ast.Dict): + return None + mapping: Dict[str, str] = {} + for key, value in zip(expr.keys, expr.values, strict=False): + if not isinstance(key, ast.Constant) or not isinstance(key.value, str): + return None + if not isinstance(value, ast.Constant) or not isinstance(value.value, str): + return None + mapping[key.value] = value.value + return mapping + + +def _substitute_names(expr: ast.expr, binding: Dict[str, str]) -> ast.expr: + """Replace comprehension variables with the string they stand for.""" + + class _Sub(ast.NodeTransformer): + def visit_Name(self, node: ast.Name) -> ast.AST: + if isinstance(node.ctx, ast.Load) and node.id in binding: + return ast.copy_location(ast.Constant(value=binding[node.id]), node) + return node + + return _Sub().visit(copy.deepcopy(expr)) + + +def _eval_str_list(expr: ast.expr) -> Optional[List[str]]: + if not isinstance(expr, (ast.List, ast.Tuple)): + return None + values: List[str] = [] + for elt in expr.elts: + if not isinstance(elt, ast.Constant) or not isinstance(elt.value, str): + return None + values.append(elt.value) + return values + + def _writer_params( fn: ast.FunctionDef | ast.AsyncFunctionDef, ) -> Optional[Tuple[str, str, int, int]]: diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py index 71bbedb4d030..576627bd8c32 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py @@ -12,10 +12,11 @@ """ import logging -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone from typing import Callable, Dict, Iterable, List, Optional, Set, Tuple, Union +import datahub.emitter.mce_builder as builder from datahub.api.entities.dataprocess.dataprocess_instance import ( DataProcessInstance, InstanceRunResult, @@ -41,7 +42,8 @@ ) from datahub.ingestion.source.fabric.onelake.client import OneLakeClient from datahub.ingestion.source.fabric.onelake.notebook_code_lineage import ( - extract_notebook_code_lineage, + analyze_notebook_code, + reconcile_column_lineage, reconcile_spark_lineage, ) from datahub.ingestion.source.fabric.onelake.notebook_spark_lineage import ( @@ -52,6 +54,9 @@ from datahub.metadata.schema_classes import ( DataJobInputOutputClass, DataProcessTypeClass, + FineGrainedLineageClass, + FineGrainedLineageDownstreamTypeClass, + FineGrainedLineageUpstreamTypeClass, ) from datahub.metadata.urns import CorpUserUrn, DataFlowUrn, DataJobUrn from datahub.sdk.dataflow import DataFlow @@ -77,6 +82,14 @@ def _iso_to_millis(iso_str: str) -> int: return int(parse_iso_datetime(iso_str).timestamp() * 1000) +@dataclass +class _JobLineage: + """Resolved upstream datasets, plus column renames when the code names them.""" + + input_urns: List[str] = field(default_factory=list) + columns: Dict[str, Set[Tuple[str, str]]] = field(default_factory=dict) + + @dataclass class PendingNotebook: """A notebook deferred for process emission after all tables are ingested. @@ -182,9 +195,10 @@ def _emit_output_job( dataflow: DataFlow, workspace_key: WorkspaceKey, output: SparkTableRef, - input_urns: List[str], + resolved: _JobLineage, output_job_urns: Dict[str, str], ) -> Iterable[Union[MetadataWorkUnit, Entity]]: + input_urns = resolved.input_urns output_urn = output.to_urn( self._env, self._platform_instance, self._normalize_name ) @@ -201,6 +215,7 @@ def _emit_output_job( inputDatasets=input_urns, outputDatasets=[output_urn], inputDatajobs=input_datajobs or None, + fineGrainedLineages=self._fine_grained(output_urn, resolved.columns), ) external_url = ( @@ -248,7 +263,30 @@ def _job_id(self, output: SparkTableRef) -> str: ) return f"{output.item_id}.{schema}.{table}" - def _spark_lineage(self, nb: PendingNotebook) -> Dict[SparkTableRef, List[str]]: + def _fine_grained( + self, output_urn: str, columns: Dict[str, Set[Tuple[str, str]]] + ) -> Optional[List[FineGrainedLineageClass]]: + entries: List[FineGrainedLineageClass] = [] + for downstream, upstreams in sorted(columns.items()): + upstream_urns = sorted( + { + builder.make_schema_field_urn(dataset_urn, column) + for dataset_urn, column in upstreams + } + ) + if not upstream_urns: + continue + entries.append( + FineGrainedLineageClass( + upstreamType=FineGrainedLineageUpstreamTypeClass.FIELD_SET, + downstreamType=FineGrainedLineageDownstreamTypeClass.FIELD, + upstreams=upstream_urns, + downstreams=[builder.make_schema_field_urn(output_urn, downstream)], + ) + ) + return entries or None + + def _spark_lineage(self, nb: PendingNotebook) -> Dict[SparkTableRef, _JobLineage]: """Resolve per-output-table lineage from the executed Spark plans. Returns each written table (that was itself ingested in this run) mapped @@ -298,12 +336,16 @@ def _spark_lineage(self, nb: PendingNotebook) -> Dict[SparkTableRef, List[str]]: raw.setdefault(output, set()).update(inputs) # Plans credit every earlier read to the next write. The notebook - # source says which of those reads each write actually uses. + # source says which of those reads each write actually uses, and which + # source column each output column was renamed from. + code_columns: Dict[ + SparkTableRef, Dict[str, Set[Tuple[SparkTableRef, str]]] + ] = {} if self._reconcile_code and nb.content and nb.language in (None, "python"): - code_lineage = extract_notebook_code_lineage(nb.content) - if code_lineage: + code = analyze_notebook_code(nb.content) + if code is not None and code.tables: reconciled = reconcile_spark_lineage( - code_lineage, raw, self._normalize_name + code.tables, raw, self._normalize_name ) if reconciled: logger.debug( @@ -312,29 +354,60 @@ def _spark_lineage(self, nb: PendingNotebook) -> Dict[SparkTableRef, List[str]]: len(reconciled), ) raw = reconciled + code_columns = reconcile_column_lineage( + code.columns, raw, self._normalize_name + ) known = self._known_table_urns # Case/space variants of one output table normalize to a single URN and # job id, so merge their input sets by that URN. Otherwise each variant # emits the same job and the later emission overwrites the earlier, # dropping the inputs that were only seen under the other casing. - merged: Dict[str, Tuple[SparkTableRef, Set[SparkTableRef]]] = {} + merged: Dict[ + str, + Tuple[SparkTableRef, Set[SparkTableRef], Dict[str, Set[Tuple[str, str]]]], + ] = {} for output, inputs in raw.items(): output_urn = output.to_urn( self._env, self._platform_instance, self._normalize_name ) - _, acc = merged.setdefault(output_urn, (output, set())) + _, acc, cols = merged.setdefault(output_urn, (output, set(), {})) acc.update(inputs) + for downstream, upstreams in code_columns.get(output, {}).items(): + # Same normalization as schema fields, so a code name + # ``person_PersonParty`` matches the ingested ``person_personparty``. + resolved = cols.setdefault(self._normalize_name(downstream), set()) + for ref, column in upstreams: + dataset_urn = ref.to_urn( + self._env, self._platform_instance, self._normalize_name + ) + resolved.add((dataset_urn, self._normalize_name(column))) - lineage: Dict[SparkTableRef, List[str]] = {} - for output_urn, (output, inputs) in merged.items(): + lineage: Dict[SparkTableRef, _JobLineage] = {} + for output_urn, (output, inputs, columns) in merged.items(): if output_urn not in known: continue input_urns = { ref.to_urn(self._env, self._platform_instance, self._normalize_name) for ref in inputs } - lineage[output] = sorted(input_urns & known - {output_urn}) + kept_inputs = input_urns & known - {output_urn} + kept_columns = { + downstream: { + (dataset_urn, column) + for dataset_urn, column in upstreams + if dataset_urn in kept_inputs + } + for downstream, upstreams in columns.items() + } + lineage[output] = _JobLineage( + input_urns=sorted(kept_inputs), + columns={ + downstream: refs + for downstream, refs in kept_columns.items() + if refs + }, + ) return lineage def _emit_runs( diff --git a/metadata-ingestion/tests/unit/executor/test_runner.py b/metadata-ingestion/tests/unit/executor/test_runner.py index 11e317d0a926..d4aea15a292b 100644 --- a/metadata-ingestion/tests/unit/executor/test_runner.py +++ b/metadata-ingestion/tests/unit/executor/test_runner.py @@ -711,6 +711,33 @@ async def test_setup_venv_native_version(self, mock_runner, temp_dir): assert venv_ref.venv_config == config mock_runner.execute.assert_not_called() + async def test_setup_venv_native_installs_missing_plugin_extra( + self, mock_runner, temp_dir + ): + config = VenvConfig(version=VENV_VERSION_NATIVE, main_plugin="fabric-onelake") + checkout = temp_dir / "metadata-ingestion" + + with ( + patch( + "datahub.executor.execution.runner._plugin_module_missing", + return_value=True, + ), + patch( + "datahub.executor.execution.runner._metadata_ingestion_root", + return_value=checkout, + ), + patch( + "datahub.executor.execution.runner._find_uv", + return_value="uv", + ), + ): + venv_ref = await setup_venv(config, mock_runner, temp_dir) + + assert venv_ref.venv_loc == Path(sys.prefix) + mock_runner.execute.assert_awaited_once_with( + ["uv", "pip", "install", "-e", f"{checkout}[fabric-onelake]"] + ) + async def test_setup_venv_bundled_version_not_found(self, mock_runner, temp_dir): """Test setup with bundled version when venv doesn't exist.""" config = VenvConfig(version=VENV_VERSION_BUNDLED, main_plugin="snowflake") diff --git a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py index f27f65b18785..014cfaf76617 100644 --- a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py +++ b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py @@ -2,9 +2,11 @@ from unittest.mock import MagicMock +from datahub.emitter.mce_builder import make_schema_field_urn from datahub.ingestion.source.fabric.common.models import FabricSparkSession from datahub.ingestion.source.fabric.onelake.notebook_code_lineage import ( CodeTable, + analyze_notebook_code, extract_notebook_code_lineage, reconcile_spark_lineage, ) @@ -237,9 +239,230 @@ def test_emitter_uses_code_to_drop_unused_plan_sources() -> None: assert products.to_urn("PROD", None) not in (io.inputDatasets or []) +def _columns(source: str) -> dict[str, dict[str, set[tuple[str, str]]]]: + analysis = analyze_notebook_code(source) + assert analysis is not None + return { + target.table: { + column: {(ref.table, upstream) for ref, upstream in refs} + for column, refs in mapping.items() + } + for target, mapping in analysis.columns.items() + } + + +def test_mapping_dict_renames_columns() -> None: + source = """ +source = f"{bronze}/Tables/dbo/" +destination = f"{silver}/Tables/silver/" +column_mapping = {"ACCOUNTNUM": "AccountNum", "NAME": "Name"} +table = "customers" +raw = ( + spark.read.format("delta").load(f"{source}{table}") + .withColumn("SourceSystem", F.lit("SRC")) +) +out = raw.select( + *[F.col(src).alias(dst) for src, dst in column_mapping.items()], + F.col("SourceSystem"), +) +out.write.format("delta").save(f"{destination}silver_customers") +""" + assert _columns(source) == { + "silver_customers": { + "AccountNum": {("customers", "ACCOUNTNUM")}, + "Name": {("customers", "NAME")}, + } + } + + +def test_inline_alias_and_join_star_keep_upstream_columns() -> None: + source = """ +source = f"{bronze}/Tables/dbo/" +destination = f"{silver}/Tables/silver/" +orders = spark.read.format("delta").load(f"{source}orders").select( + col("ID").alias("OrderId"), + upper(col("CUST")).alias("CustId"), +) +customers = spark.read.format("delta").load(f"{source}customers").select( + col("ID").alias("CustId"), + col("NAME").alias("CustName"), +) +joined = orders.alias("o").join(customers.alias("c"), "CustId").select( + "o.*", + "c.CustName", +) +joined.write.format("delta").save(f"{destination}gold_orders") +""" + assert _columns(source)["gold_orders"] == { + "OrderId": {("orders", "ID")}, + "CustId": {("orders", "CUST")}, + "CustName": {("customers", "NAME")}, + } + + +def test_helper_mapping_and_dataframe_subscript() -> None: + source = """ +source = f"{bronze}/Tables/dbo/" +destination = f"{silver}/Tables/silver/" + +def load_table(table_name, column_mapping, add_metadata=False): + df = spark.read.format("delta").load(f"{source}{table_name}") + if add_metadata: + df = df.withColumn("LoadedAt", F.current_timestamp()) + return df.select( + *[F.col(src).alias(dst) for src, dst in column_mapping.items()], + *([F.col("LoadedAt")] if add_metadata else []), + ) + +party_map = {"NAME": "Name", "RECID": "PartyId"} +party = load_table("party", party_map, add_metadata=True) +customers = spark.read.format("delta").load(f"{source}customers") +named = customers.select( + F.upper(customers["accountnum"]).alias("AccountNum"), + customers["name"], +) +party.write.format("delta").save(f"{destination}silver_party") +named.write.format("delta").save(f"{destination}silver_customers") +""" + analysis = analyze_notebook_code(source) + assert analysis is not None + assert ( + CodeTable("party", "dbo") + in analysis.tables[CodeTable("silver_party", "silver")] + ) + columns = _columns(source) + assert columns["silver_party"] == { + "Name": {("party", "NAME")}, + "PartyId": {("party", "RECID")}, + } + assert "LoadedAt" not in columns["silver_party"] + assert columns["silver_customers"] == { + "AccountNum": {("customers", "accountnum")}, + "name": {("customers", "name")}, + } + + +def test_saved_select_list_prefixes_columns_from_each_source() -> None: + # dim-style notebooks build the select list first, then apply it, then + # carry those prefixed columns through alias.* to the write. + source = """ +source = f"{silver}/Tables/silver/" +destination = f"{gold}/Tables/gold/" +people = spark.read.format("delta").load(f"{source}people") +accounts = spark.read.format("delta").load(f"{source}accounts") +joined = people.alias("p").join(accounts.alias("a"), "id", "left") +person_cols = ["PersonParty"] +account_cols = ["Email"] +select_exprs = ( + [F.col(f"p.{c}").alias(f"person_{c}") for c in person_cols] + + [F.col(f"a.{c}").alias(f"account_{c}") for c in account_cols] +) +dim_user = joined.select(*select_exprs) +dim_user = dim_user.alias("du").select(F.col("du.*")) +dim_user = dim_user.withColumn("rn", F.lit(1)).drop("rn") +dim_user.write.format("delta").save(f"{destination}dim_user") +""" + assert _columns(source)["dim_user"] == { + "person_PersonParty": {("people", "PersonParty")}, + "account_Email": {("accounts", "Email")}, + } + + +def test_aliased_column_list_prefixes_the_output_name() -> None: + source = """ +source = f"{silver}/Tables/silver/" +destination = f"{gold}/Tables/gold/" +cols = ["Email"] +users = spark.read.format("delta").load(f"{source}users").alias("su") +out = users.select(*[F.col(f"su.{c}").alias(f"user_{c}") for c in cols]) +out.write.format("delta").save(f"{destination}dim_user") +""" + assert _columns(source) == {"dim_user": {"user_Email": {("users", "Email")}}} + + def test_code_reconciliation_is_off_unless_enabled() -> None: io = _emit_dim_user(reconcile_code=False) products = SparkTableRef( workspace_id=WS, item_id=LH, table="products", schema="silver" ) assert products.to_urn("PROD", None) in (io.inputDatasets or []) + assert not io.fineGrainedLineages + + +_COLUMN_NOTEBOOK = """ +source = f"{bronze}/Tables/dbo/" +destination = f"{silver}/Tables/silver/" +column_mapping = {"ACCOUNTNUM": "AccountNum", "NAME": "Name"} +table = "customers" +raw = spark.read.format("delta").load(f"{source}{table}") +out = raw.select(*[F.col(src).alias(dst) for src, dst in column_mapping.items()]) +out.write.format("delta").save(f"{destination}silver_customers") +""" + + +def test_reconciled_job_carries_column_lineage() -> None: + customers = SparkTableRef( + workspace_id=WS, item_id=LH, table="customers", schema="dbo" + ) + silver = SparkTableRef( + workspace_id=WS, item_id=LH, table="silver_customers", schema="silver" + ) + known = {ref.to_urn("PROD", None) for ref in (customers, silver)} + client = MagicMock() + client.list_notebook_spark_sessions.return_value = [ + FabricSparkSession(livy_id="livy-1", application_id="app-1", item_id=NB) + ] + client.get_spark_sql_plans.return_value = [ + _plan( + "Tables/silver/silver_customers", + ["Tables/dbo/customers/_delta_log/0.json"], + ) + ] + client.get_notebook_runs.return_value = [] + emitter = NotebookProcessEmitter( + platform_instance=None, + env="PROD", + execution_history_days=30, + report=FabricOneLakeSourceReport(), + client=client, + known_table_urns=known, + normalize_name=lambda name: name, + owners_fn=lambda _upn: None, + reconcile_code=True, + ) + jobs = [ + job + for job in emitter.emit( + [ + PendingNotebook( + workspace_id=WS, + workspace_name="analytics", + notebook_id=NB, + display_name="customers", + description=None, + owner_user_principal_name=None, + content=_COLUMN_NOTEBOOK, + language="python", + ) + ] + ) + if isinstance(job, DataJob) + ] + assert len(jobs) == 1 + io = jobs[0]._get_aspect(DataJobInputOutputClass) + assert io is not None and io.fineGrainedLineages + downstream = silver.to_urn("PROD", None) + upstream = customers.to_urn("PROD", None) + assert { + (entry.downstreams[0], tuple(sorted(entry.upstreams or []))) + for entry in io.fineGrainedLineages + } == { + ( + make_schema_field_urn(downstream, "AccountNum"), + (make_schema_field_urn(upstream, "ACCOUNTNUM"),), + ), + ( + make_schema_field_urn(downstream, "Name"), + (make_schema_field_urn(upstream, "NAME"),), + ), + } From d81c6fb4e690cdd81c1ab1ad5fdbadbd6222e7b2 Mon Sep 17 00:00:00 2001 From: Steve Baldwin Date: Tue, 27 Oct 2026 08:19:17 +0000 Subject: [PATCH 02/12] Update config.py --- .../src/datahub/ingestion/source/fabric/onelake/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py index 6ebc963f890c..b4d3da63b9b4 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py @@ -109,7 +109,7 @@ class NotebookExecutionConfig(ConfigModel): "keeps only the tables its dataframe actually uses, and a write that " "exists only in a commented-out cell is dropped. Column renames in " "that dataframe (`col(src).alias(dst)`, a `{source: target}` mapping, " - "`alias.*`, and `df[\"column\"]`) are emitted as column-level lineage " + '`alias.*`, and `df["column"]`) are emitted as column-level lineage ' "on the job. The plans still supply the resolved OneLake path. Off " "by default, so plan lineage is emitted unchanged. Requires " "`enabled=True`." From 91790df2a09ce9d6333f7fe81ff663a878f5460a Mon Sep 17 00:00:00 2001 From: Steve Baldwin Date: Tue, 27 Oct 2026 11:07:54 +0000 Subject: [PATCH 03/12] chore(executor): drop native plugin install from column lineage The installer is unrelated to notebook column lineage and can fail native runs that previously succeeded. Co-authored-by: Cursor --- .../src/datahub/executor/execution/runner.py | 59 ------------------- .../tests/unit/executor/test_runner.py | 27 --------- 2 files changed, 86 deletions(-) diff --git a/metadata-ingestion/src/datahub/executor/execution/runner.py b/metadata-ingestion/src/datahub/executor/execution/runner.py index 13230ce583d0..d5640fbb8a6c 100644 --- a/metadata-ingestion/src/datahub/executor/execution/runner.py +++ b/metadata-ingestion/src/datahub/executor/execution/runner.py @@ -107,64 +107,6 @@ def _validate_wheel_url(url: str) -> bool: return True -def _metadata_ingestion_root() -> Optional[pathlib.Path]: - """Checkout that owns this module, when native mode is running from source.""" - candidate = pathlib.Path(__file__).resolve().parents[4] - if (candidate / "setup.py").is_file(): - return candidate - return None - - -def _plugin_module_missing(plugin: str) -> bool: - """True when the source plugin cannot be imported in this environment.""" - try: - from importlib.metadata import entry_points - - match = next( - ( - entry_point - for entry_point in entry_points( - group="datahub.ingestion.source.plugins" - ) - if entry_point.name == plugin - ), - None, - ) - if match is None: - return True - match.load() - except ModuleNotFoundError: - return True - return False - - -async def _install_native_plugin_extra( - venv_config: "VenvConfig", runner: "SubprocessRunner" -) -> None: - """Install this checkout's plugin extra into the process environment. - - Native mode runs the mounted source with the executor's own environment. - That environment is not built with every source extra, so a plugin such as - fabric-onelake fails to register (``sqlparse`` and the rest of its extra - are absent) unless we install them here. - """ - plugin = venv_config.main_plugin - if not plugin or not _plugin_module_missing(plugin): - return - root = _metadata_ingestion_root() - if root is None: - raise RuntimeError( - f"{plugin} is missing a dependency, and native mode has no " - "metadata-ingestion checkout to install it from." - ) - extras = ",".join(dict.fromkeys([plugin, *venv_config.extra_pip_plugins])) - requirement = f"{root}[{extras}]" - runner._logs.append( - f"Native environment cannot import {plugin}. Installing {requirement}\n" - ) - await runner.execute([_find_uv(), "pip", "install", "-e", requirement]) - - def _bundled_constraints_path(venv_loc: pathlib.Path) -> Optional[pathlib.Path]: """Locate datahub/constraints.txt inside an installed acryl-datahub.""" matches = list(venv_loc.glob("lib/python*/site-packages/datahub/constraints.txt")) @@ -551,7 +493,6 @@ async def setup_venv( validate_dependency_resolution_enabled(venv_config.version) if venv_config.version == VENV_VERSION_NATIVE: - await _install_native_plugin_extra(venv_config, runner) return VenvReference( venv_loc=pathlib.Path(sys.prefix), venv_config=venv_config, diff --git a/metadata-ingestion/tests/unit/executor/test_runner.py b/metadata-ingestion/tests/unit/executor/test_runner.py index d4aea15a292b..11e317d0a926 100644 --- a/metadata-ingestion/tests/unit/executor/test_runner.py +++ b/metadata-ingestion/tests/unit/executor/test_runner.py @@ -711,33 +711,6 @@ async def test_setup_venv_native_version(self, mock_runner, temp_dir): assert venv_ref.venv_config == config mock_runner.execute.assert_not_called() - async def test_setup_venv_native_installs_missing_plugin_extra( - self, mock_runner, temp_dir - ): - config = VenvConfig(version=VENV_VERSION_NATIVE, main_plugin="fabric-onelake") - checkout = temp_dir / "metadata-ingestion" - - with ( - patch( - "datahub.executor.execution.runner._plugin_module_missing", - return_value=True, - ), - patch( - "datahub.executor.execution.runner._metadata_ingestion_root", - return_value=checkout, - ), - patch( - "datahub.executor.execution.runner._find_uv", - return_value="uv", - ), - ): - venv_ref = await setup_venv(config, mock_runner, temp_dir) - - assert venv_ref.venv_loc == Path(sys.prefix) - mock_runner.execute.assert_awaited_once_with( - ["uv", "pip", "install", "-e", f"{checkout}[fabric-onelake]"] - ) - async def test_setup_venv_bundled_version_not_found(self, mock_runner, temp_dir): """Test setup with bundled version when venv doesn't exist.""" config = VenvConfig(version=VENV_VERSION_BUNDLED, main_plugin="snowflake") From d80a9a605cb07c81c0e89c2b629cf244bed05eb5 Mon Sep 17 00:00:00 2001 From: Steve Baldwin Date: Tue, 27 Oct 2026 11:37:14 +0000 Subject: [PATCH 04/12] fix(ingestion/fabric): pair notebook union columns by position Spark union stacks columns by position and keeps the left-hand names. unionByName still matches columns by name. Co-authored-by: Cursor --- .../fabric/onelake/notebook_code_lineage.py | 35 ++++++++++++--- .../test_notebook_code_lineage.py | 44 +++++++++++++++++++ 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py index 65f387149187..334325fdd820 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py @@ -395,6 +395,14 @@ class _Projection: _LITERAL_FUNCS = {"lit", "current_timestamp", "current_date", "now", "expr"} +def _visible_columns(proj: _Projection) -> List[Tuple[str, Set["_ColRef"]]]: + return [ + (column, refs) + for column, refs in proj.explicit.items() + if column not in proj.dropped + ] + + def _clone(proj: _Projection) -> _Projection: return _Projection( reads=set(proj.reads), @@ -643,7 +651,7 @@ def _apply_method( self, base: _Projection, attr: str, call: ast.Call ) -> Optional[_Projection]: if attr in {"union", "unionAll", "unionByName"}: - return self._union(base, call) + return self._union(base, call, by_name=attr == "unionByName") handler = { "alias": self._alias, "select": self._select, @@ -722,15 +730,32 @@ def _join(self, base: _Projection, call: ast.Call) -> _Projection: return base return _joined(base, right) - def _union(self, base: _Projection, call: ast.Call) -> _Projection: + def _union( + self, base: _Projection, call: ast.Call, *, by_name: bool + ) -> _Projection: + """Stack two dataframes. + + ``union`` and ``unionAll`` pair columns by position and keep the left + names. ``unionByName`` pairs columns that share a name. + """ if not call.args: return base right = self._projection_of(call.args[0]) if right is None or not base.projected or not right.projected: return _Projection(reads=base.reads | (right.reads if right else set())) - explicit = {column: set(refs) for column, refs in base.explicit.items()} - for column, refs in right.explicit.items(): - explicit.setdefault(column, set()).update(refs) + left_columns = _visible_columns(base) + right_columns = _visible_columns(right) + if by_name: + explicit = {column: set(refs) for column, refs in left_columns} + for column, refs in right_columns: + explicit.setdefault(column, set()).update(refs) + else: + explicit = {} + for index, (column, refs) in enumerate(left_columns): + merged = set(refs) + if index < len(right_columns): + merged.update(right_columns[index][1]) + explicit[column] = merged return _Projection( reads=base.reads | right.reads, explicit=explicit, projected=True ) diff --git a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py index 014cfaf76617..a5dff5ee853f 100644 --- a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py +++ b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py @@ -300,6 +300,50 @@ def test_inline_alias_and_join_star_keep_upstream_columns() -> None: } +def test_union_pairs_columns_by_position() -> None: + source = """ +source = f"{bronze}/Tables/dbo/" +destination = f"{silver}/Tables/silver/" +orders = spark.read.format("delta").load(f"{source}orders").select( + col("x").alias("id"), + col("n").alias("amount"), +) +payments = spark.read.format("delta").load(f"{source}payments").select( + col("y").alias("key"), + col("m").alias("total"), +) +out = orders.union(payments) +out.write.format("delta").save(f"{destination}combined") +""" + assert _columns(source)["combined"] == { + "id": {("orders", "x"), ("payments", "y")}, + "amount": {("orders", "n"), ("payments", "m")}, + } + + +def test_union_by_name_keeps_distinct_column_names() -> None: + source = """ +source = f"{bronze}/Tables/dbo/" +destination = f"{silver}/Tables/silver/" +orders = spark.read.format("delta").load(f"{source}orders").select( + col("x").alias("id"), + col("n").alias("amount"), +) +payments = spark.read.format("delta").load(f"{source}payments").select( + col("y").alias("key"), + col("m").alias("total"), +) +out = orders.unionByName(payments) +out.write.format("delta").save(f"{destination}combined") +""" + assert _columns(source)["combined"] == { + "id": {("orders", "x")}, + "amount": {("orders", "n")}, + "key": {("payments", "y")}, + "total": {("payments", "m")}, + } + + def test_helper_mapping_and_dataframe_subscript() -> None: source = """ source = f"{bronze}/Tables/dbo/" From cf7f500c00c10ae58a70b1d71166e6fdac4d09cc Mon Sep 17 00:00:00 2001 From: Steve Baldwin Date: Tue, 27 Oct 2026 12:02:35 +0000 Subject: [PATCH 05/12] fix(ingestion/fabric): match notebook columns without regard to case Spark resolves column names case-insensitively by default and keeps the dataframe's spelling. case_sensitive_columns turns that off for sessions where Name and NAME are different columns. Co-authored-by: Cursor --- .../fabric-onelake/fabric-onelake_post.md | 2 +- .../fabric-onelake/fabric-onelake_recipe.yml | 1 + .../ingestion/source/fabric/onelake/config.py | 11 ++ .../fabric/onelake/notebook_code_lineage.py | 101 +++++++++++++----- .../source/fabric/onelake/notebook_jobs.py | 7 +- .../ingestion/source/fabric/onelake/source.py | 1 + .../tests/unit/fabric_onelake/test_config.py | 1 + .../test_notebook_code_lineage.py | 33 ++++++ 8 files changed, 131 insertions(+), 26 deletions(-) diff --git a/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md b/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md index 541215194ca2..652220188ffe 100644 --- a/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md +++ b/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md @@ -375,7 +375,7 @@ The caller needs `Workspace.Read.All` or `Workspace.ReadWrite.All`. `notebook_execution.enabled` (off by default, requires `include_notebooks: true`) also models each notebook as a **pipeline**: one DataFlow per notebook (subtype "Fabric Spark Pipeline"), and under it one Spark-job DataJob (subtype "Fabric Spark Job") **per table the notebook writes**. Each job carries that output table's own upstreams, so lineage renders as `input → [job] → output` — precise table-to-table edges with the notebook transformation attributed, not one job with a cross-product of every table the notebook ever read and wrote. When one output table is itself an input to another output table's job in the same notebook, the two jobs are chained **job → job**. The lineage lives on the jobs, not the notebook dataset, so the notebook's code and its lineage (process) stay cleanly separated. It emits two things from the notebook's run history over `notebook_execution.history_days` (default 7): table-level **lineage** on the per-output jobs, and a **run history** of `DataProcessInstance`s on those jobs. -**Lineage.** Fabric exposes no API that lists the tables a notebook reads or writes, and the source text hides them when paths are built at run time (e.g. `spark.read.format("delta").load(f"{source}{table}")` or `DeltaTable.forPath(spark, target)`). So the connector reads the **resolved Spark physical plans** of each run instead: for every run in the window it fetches the run's SQL executions from the Spark monitoring API (`livySessions` + the Spark History Server SQL API) and extracts the `abfss://` OneLake table paths actually read and written. Attribution is **order-aware within a run**: a notebook usually reads a table in one Spark execution and writes a derived table in a later execution whose plan references a cached relation rather than the source path, so each written table is credited with the tables read earlier in the same run (the read set resets after each write). This keeps independent, sequential pipelines precise instead of collapsing a run into a cross-product, and recovers read-then-write edges that span executions. Those paths map directly to the GUID-based dataset URNs the connector emits. Set `notebook_execution.reconcile_code: true` (off by default; requires `notebook_execution.enabled`) to narrow that plan lineage with the notebook source when it is Python: each write is kept only with the tables its dataframe actually uses, and a write that exists only in a commented-out cell is dropped. The same pass reads column renames — `col(src).alias(dst)`, a `{source: target}` mapping dict, `alias.*` after a join, and `df["column"]` — and emits them as column-level lineage on that write's job. The plans still supply the resolved OneLake path, so a table loaded from a run-time path stays attached to the name in the code. With the flag off, plan lineage is emitted unchanged. Because a notebook may apply only specific cells on a given run, lineage is **accumulated across all of the notebook's runs** in the window, giving a complete picture over time. Only edges to tables ingested in the same run are kept; GUID-built URNs that do not match an ingested table, and internal Spark scratch paths (shuffle, lakehouse-warmup), are dropped. +**Lineage.** Fabric exposes no API that lists the tables a notebook reads or writes, and the source text hides them when paths are built at run time (e.g. `spark.read.format("delta").load(f"{source}{table}")` or `DeltaTable.forPath(spark, target)`). So the connector reads the **resolved Spark physical plans** of each run instead: for every run in the window it fetches the run's SQL executions from the Spark monitoring API (`livySessions` + the Spark History Server SQL API) and extracts the `abfss://` OneLake table paths actually read and written. Attribution is **order-aware within a run**: a notebook usually reads a table in one Spark execution and writes a derived table in a later execution whose plan references a cached relation rather than the source path, so each written table is credited with the tables read earlier in the same run (the read set resets after each write). This keeps independent, sequential pipelines precise instead of collapsing a run into a cross-product, and recovers read-then-write edges that span executions. Those paths map directly to the GUID-based dataset URNs the connector emits. Set `notebook_execution.reconcile_code: true` (off by default; requires `notebook_execution.enabled`) to narrow that plan lineage with the notebook source when it is Python: each write is kept only with the tables its dataframe actually uses, and a write that exists only in a commented-out cell is dropped. The same pass reads column renames — `col(src).alias(dst)`, a `{source: target}` mapping dict, `alias.*` after a join, and `df["column"]` — and emits them as column-level lineage on that write's job. Column names are matched without regard to case, which is Spark's default, and the dataframe's own spelling is kept (`select("name")` still emits `NAME`). Set `notebook_execution.case_sensitive_columns: true` when the Spark session has `spark.sql.caseSensitive` enabled. The plans still supply the resolved OneLake path, so a table loaded from a run-time path stays attached to the name in the code. With the flag off, plan lineage is emitted unchanged. Because a notebook may apply only specific cells on a given run, lineage is **accumulated across all of the notebook's runs** in the window, giving a complete picture over time. Only edges to tables ingested in the same run are kept; GUID-built URNs that do not match an ingested table, and internal Spark scratch paths (shuffle, lakehouse-warmup), are dropped. **Run history.** A Fabric run executes the whole notebook (the Job Scheduler reports one status per run, not per table), so for each run in the window the connector emits a `DataProcessInstance` on each of the notebook's per-output jobs — the whole-notebook run is recorded against every job it contains, falling back to the DataFlow only when a run resolved no per-table lineage — read from the Job Scheduler `GET /workspaces/{id}/items/{itemId}/jobs/instances` API. Each instance records start/end time and the run result (success / failure / skipped). diff --git a/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_recipe.yml b/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_recipe.yml index bceb28fd86e3..1b015a075bde 100644 --- a/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_recipe.yml +++ b/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_recipe.yml @@ -89,6 +89,7 @@ source: # notebook_execution: # enabled: true # reconcile_code: false + # case_sensitive_columns: false # history_days: 7 # notebook_pattern: # allow: diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py index b4d3da63b9b4..36757965c3e8 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py @@ -115,6 +115,17 @@ class NotebookExecutionConfig(ConfigModel): "`enabled=True`." ), ) + case_sensitive_columns: bool = Field( + default=False, + description=( + "Resolve notebook column names the way a case-sensitive Spark " + 'session does. Off by default, so `select("name")` finds a column ' + 'stored as `NAME` and keeps that spelling, and `drop("name")` ' + "removes it. Set true only when the Spark session has " + "`spark.sql.caseSensitive` enabled and `Name` and `NAME` are " + "different columns. Used when `reconcile_code=True`." + ), + ) @model_validator(mode="after") def validate_reconcile_code_requires_enabled(self): diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py index 334325fdd820..4b4efead4bb9 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py @@ -49,12 +49,15 @@ class NotebookCodeAnalysis: columns: Dict[CodeTable, ColumnLineage] -def analyze_notebook_code(source: str) -> Optional[NotebookCodeAnalysis]: +def analyze_notebook_code( + source: str, *, case_sensitive_columns: bool = False +) -> Optional[NotebookCodeAnalysis]: """Recover per-write table lineage and column renames from notebook source. Returns None when ``source`` is not parseable Python, so the caller can keep the Spark-plan lineage unchanged. Empty mappings mean the code parsed - and contains no writes. + and contains no writes. Column names match without regard to case unless + ``case_sensitive_columns`` is set, and the dataframe's own spelling is kept. """ try: tree = ast.parse(_strip_magics(source)) @@ -62,7 +65,7 @@ def analyze_notebook_code(source: str) -> Optional[NotebookCodeAnalysis]: logger.debug("Notebook source is not parseable Python; skipping code lineage") return None - extractor = _Extractor() + extractor = _Extractor(case_sensitive_columns=case_sensitive_columns) extractor.walk(tree.body) columns: Dict[CodeTable, ColumnLineage] = {} for target, mapping in extractor.column_lineage.items(): @@ -395,11 +398,31 @@ class _Projection: _LITERAL_FUNCS = {"lit", "current_timestamp", "current_date", "now", "expr"} -def _visible_columns(proj: _Projection) -> List[Tuple[str, Set["_ColRef"]]]: +def _known_column( + names: Iterable[str], column: str, *, case_sensitive: bool +) -> Optional[str]: + """Return the stored spelling of ``column``. + + Spark resolves column names without regard to case unless + ``spark.sql.caseSensitive`` is on. The stored spelling is the one the + dataframe already uses. + """ + if case_sensitive: + return column if column in names else None + folded = column.casefold() + for name in names: + if name.casefold() == folded: + return name + return None + + +def _visible_columns( + proj: _Projection, *, case_sensitive: bool +) -> List[Tuple[str, Set["_ColRef"]]]: return [ (column, refs) for column, refs in proj.explicit.items() - if column not in proj.dropped + if _known_column(proj.dropped, column, case_sensitive=case_sensitive) is None ] @@ -416,7 +439,8 @@ def _clone(proj: _Projection) -> _Projection: class _Extractor: - def __init__(self) -> None: + def __init__(self, *, case_sensitive_columns: bool = False) -> None: + self._case_sensitive_columns = case_sensitive_columns self.lineage: Dict[CodeTable, Set[CodeTable]] = {} self.column_lineage: Dict[CodeTable, Dict[str, Set[_ColRef]]] = {} self._frames: Dict[str, Set[CodeTable]] = {} @@ -622,7 +646,7 @@ def _add_edge(self, target: CodeTable, df_expr: ast.expr) -> None: def _record_columns(self, target: CodeTable, proj: _Projection) -> None: bucket = self.column_lineage.setdefault(target, {}) for column, refs in proj.explicit.items(): - if column in proj.dropped: + if self._is_dropped(proj, column): continue kept = {ref for ref in refs if not _same_table(ref.table, target)} if kept: @@ -689,8 +713,11 @@ def _with_column(self, base: _Projection, call: ast.Call) -> _Projection: if not name: return base cloned = _clone(base) + existing = self._known_column(cloned.explicit, name) + if existing is not None and existing != name: + cloned.explicit.pop(existing, None) cloned.explicit[name] = self._origins_in(call.args[1], base) - cloned.dropped.discard(name) + self._undrop(cloned, name) return cloned def _rename_column(self, base: _Projection, call: ast.Call) -> _Projection: @@ -702,12 +729,16 @@ def _rename_column(self, base: _Projection, call: ast.Call) -> _Projection: return base cloned = _clone(base) origins = self._lookup(base, old) + existing = self._known_column(cloned.explicit, old) if cloned.projected: - cloned.explicit.pop(old, None) + cloned.explicit.pop(existing if existing is not None else old, None) else: - cloned.dropped.add(old) + cloned.dropped.add(existing if existing is not None else old) + replaced = self._known_column(cloned.explicit, new) + if replaced is not None and replaced != new: + cloned.explicit.pop(replaced, None) cloned.explicit[new] = origins - cloned.dropped.discard(new) + self._undrop(cloned, new) return cloned def _drop(self, base: _Projection, call: ast.Call) -> _Projection: @@ -716,10 +747,12 @@ def _drop(self, base: _Projection, call: ast.Call) -> _Projection: name = _eval_tail(arg, self._strings) if not name: continue + existing = self._known_column(cloned.explicit, name) + stored = existing if existing is not None else name if cloned.projected: - cloned.explicit.pop(name, None) + cloned.explicit.pop(stored, None) else: - cloned.dropped.add(name) + cloned.dropped.add(stored) return cloned def _join(self, base: _Projection, call: ast.Call) -> _Projection: @@ -743,12 +776,17 @@ def _union( right = self._projection_of(call.args[0]) if right is None or not base.projected or not right.projected: return _Projection(reads=base.reads | (right.reads if right else set())) - left_columns = _visible_columns(base) - right_columns = _visible_columns(right) + case_sensitive = self._case_sensitive_columns + left_columns = _visible_columns(base, case_sensitive=case_sensitive) + right_columns = _visible_columns(right, case_sensitive=case_sensitive) if by_name: explicit = {column: set(refs) for column, refs in left_columns} for column, refs in right_columns: - explicit.setdefault(column, set()).update(refs) + key = _known_column(explicit, column, case_sensitive=case_sensitive) + if key is None: + explicit[column] = set(refs) + else: + explicit[key].update(refs) else: explicit = {} for index, (column, refs) in enumerate(left_columns): @@ -1008,27 +1046,42 @@ def _resolve_named( return [ (column, set(refs)) for column, refs in proj.explicit.items() - if column not in proj.dropped + if not self._is_dropped(proj, column) ] if "." in name: qual, column = name.split(".", 1) proj = self._qualified(current, qual) if proj is None: return [] - return [(column, self._lookup(proj, column))] - return [(name, self._lookup(current, name))] + return [(self._canonical(proj, column), self._lookup(proj, column))] + return [(self._canonical(current, name), self._lookup(current, name))] def _qualified(self, current: _Projection, qual: str) -> Optional[_Projection]: if current.alias == qual: return current return current.aliases.get(qual) or self._projections.get(qual) + def _known_column(self, names: Iterable[str], column: str) -> Optional[str]: + return _known_column(names, column, case_sensitive=self._case_sensitive_columns) + + def _canonical(self, proj: _Projection, column: str) -> str: + return self._known_column(proj.explicit, column) or column + + def _is_dropped(self, proj: _Projection, column: str) -> bool: + return self._known_column(proj.dropped, column) is not None + + def _undrop(self, proj: _Projection, column: str) -> None: + dropped = self._known_column(proj.dropped, column) + if dropped is not None: + proj.dropped.discard(dropped) + def _lookup(self, proj: _Projection, column: str) -> Set[_ColRef]: - if column in proj.dropped and column not in proj.explicit: + explicit = self._known_column(proj.explicit, column) + if self._is_dropped(proj, column) and explicit is None: return set() - if proj.projected or column in proj.explicit: - if column in proj.explicit: - return set(proj.explicit[column]) + if proj.projected or explicit is not None: + if explicit is not None: + return set(proj.explicit[explicit]) if proj.projected: return set() if proj.passthrough is not None: @@ -1044,7 +1097,7 @@ def _subscript(self, expr: ast.Subscript) -> Optional[Tuple[str, Set[_ColRef]]]: column = _eval_tail(expr.slice, self._strings) if not column: return None - return (column, self._lookup(proj, column)) + return (self._canonical(proj, column), self._lookup(proj, column)) def _origins_in( self, diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py index 576627bd8c32..987fdb870b7e 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py @@ -119,6 +119,7 @@ def __init__( env: str, execution_history_days: int, reconcile_code: bool = False, + case_sensitive_columns: bool = False, report: FabricOneLakeSourceReport, client: OneLakeClient, known_table_urns: Set[str], @@ -129,6 +130,7 @@ def __init__( self._env = env self._execution_history_days = execution_history_days self._reconcile_code = reconcile_code + self._case_sensitive_columns = case_sensitive_columns self._report = report self._client = client self._known_table_urns = known_table_urns @@ -342,7 +344,10 @@ def _spark_lineage(self, nb: PendingNotebook) -> Dict[SparkTableRef, _JobLineage SparkTableRef, Dict[str, Set[Tuple[SparkTableRef, str]]] ] = {} if self._reconcile_code and nb.content and nb.language in (None, "python"): - code = analyze_notebook_code(nb.content) + code = analyze_notebook_code( + nb.content, + case_sensitive_columns=self._case_sensitive_columns, + ) if code is not None and code.tables: reconciled = reconcile_spark_lineage( code.tables, raw, self._normalize_name diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/source.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/source.py index c737c3f83e44..625cb59ffcc7 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/source.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/source.py @@ -1364,6 +1364,7 @@ def _emit_notebook_processes( env=self.config.env, execution_history_days=self.config.notebook_execution.history_days, reconcile_code=self.config.notebook_execution.reconcile_code, + case_sensitive_columns=self.config.notebook_execution.case_sensitive_columns, report=self.report, client=self.client, known_table_urns=self._notebook_known_table_urns, diff --git a/metadata-ingestion/tests/unit/fabric_onelake/test_config.py b/metadata-ingestion/tests/unit/fabric_onelake/test_config.py index d9e0d58484ed..0ece63cb5492 100644 --- a/metadata-ingestion/tests/unit/fabric_onelake/test_config.py +++ b/metadata-ingestion/tests/unit/fabric_onelake/test_config.py @@ -89,6 +89,7 @@ def test_notebook_execution_enabled_with_notebooks(self) -> None: assert config.notebook_execution.enabled assert config.notebook_execution.history_days == 7 assert not config.notebook_execution.reconcile_code + assert not config.notebook_execution.case_sensitive_columns def test_notebook_code_reconciliation_requires_execution(self) -> None: """Code reconciliation requires notebook execution to be enabled.""" diff --git a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py index a5dff5ee853f..fbd9ec083236 100644 --- a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py +++ b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py @@ -321,6 +321,39 @@ def test_union_pairs_columns_by_position() -> None: } +def test_column_match_ignores_case_and_keeps_spelling() -> None: + source = """ +source = f"{bronze}/Tables/dbo/" +destination = f"{silver}/Tables/silver/" +orders = spark.read.format("delta").load(f"{source}orders").select( + col("NAME").alias("NAME"), + col("ID").alias("ID"), +) +renamed = orders.withColumnRenamed("NAME", "Name").select("name") +kept = orders.drop("name") +renamed.write.format("delta").save(f"{destination}renamed_customers") +kept.write.format("delta").save(f"{destination}kept_customers") +""" + columns = _columns(source) + assert columns["renamed_customers"] == {"Name": {("orders", "NAME")}} + assert columns["kept_customers"] == {"ID": {("orders", "ID")}} + + +def test_case_sensitive_columns_require_an_exact_name() -> None: + source = """ +source = f"{bronze}/Tables/dbo/" +destination = f"{silver}/Tables/silver/" +orders = spark.read.format("delta").load(f"{source}orders").select( + col("NAME").alias("NAME"), +) +renamed = orders.withColumnRenamed("NAME", "Name").select("name") +renamed.write.format("delta").save(f"{destination}customers") +""" + analysis = analyze_notebook_code(source, case_sensitive_columns=True) + assert analysis is not None + assert analysis.columns == {} + + def test_union_by_name_keeps_distinct_column_names() -> None: source = """ source = f"{bronze}/Tables/dbo/" From 1f256b15980bb5dcd3c45b405f74c277c2427aff Mon Sep 17 00:00:00 2001 From: Steve Baldwin Date: Tue, 27 Oct 2026 12:06:26 +0000 Subject: [PATCH 06/12] fix(ingestion/fabric): hide notebook parameters that cannot be evaluated A function parameter shadowed a global only when its argument resolved. load(get_name()) could otherwise follow an outer table_name. Co-authored-by: Cursor --- .../fabric/onelake/notebook_code_lineage.py | 29 +++++++++++++++++++ .../test_notebook_code_lineage.py | 26 +++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py index 4b4efead4bb9..6b2cb9acf61c 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py @@ -808,6 +808,11 @@ def _call_function(self, call: ast.Call) -> Optional[_Projection]: saved = self._snapshot() self._executing.add(call.func.id) try: + # A parameter hides the outer name even when its argument cannot + # be evaluated. Otherwise ``load(get_name())`` still sees a global + # ``table_name``. + for name in _parameter_names(fn): + self._hide_binding(name) for name, captured in bindings: self._install(name, captured) self._return_projection = None @@ -899,6 +904,17 @@ def _install(self, name: str, captured: Tuple[str, object]) -> None: self._projections[name] = value self._frames[name] = set(value.reads) + def _hide_binding(self, name: str) -> None: + self._frames.pop(name, None) + self._produced.pop(name, None) + self._strings.pop(name, None) + self._dicts.pop(name, None) + self._lists.pop(name, None) + self._col_lists.pop(name, None) + self._bools.pop(name, None) + self._projections.pop(name, None) + self._exprs.pop(name, None) + def _eval_bool(self, expr: ast.AST) -> Optional[bool]: if isinstance(expr, ast.Constant) and isinstance(expr.value, bool): return expr.value @@ -1170,6 +1186,19 @@ def _joined(left: _Projection, right: _Projection) -> _Projection: return _Projection(reads=left.reads | right.reads, aliases=aliases) +def _parameter_names( + fn: Union[ast.FunctionDef, ast.AsyncFunctionDef], +) -> List[str]: + names = [ + arg.arg for arg in [*fn.args.posonlyargs, *fn.args.args, *fn.args.kwonlyargs] + ] + if fn.args.vararg is not None: + names.append(fn.args.vararg.arg) + if fn.args.kwarg is not None: + names.append(fn.args.kwarg.arg) + return names + + def _returns_value(fn: Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> bool: return any( isinstance(node, ast.Return) and node.value is not None for node in ast.walk(fn) diff --git a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py index fbd9ec083236..b06f4e0f7b44 100644 --- a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py +++ b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py @@ -419,6 +419,32 @@ def load_table(table_name, column_mapping, add_metadata=False): } +def test_unevaluated_argument_does_not_reuse_the_outer_name() -> None: + source = """ +source = f"{bronze}/Tables/dbo/" +destination = f"{silver}/Tables/silver/" +table_name = "customers" + +def load(table_name): + return spark.read.format("delta").load(f"{source}{table_name}") + +unknown = load(get_name()) +unknown.write.format("delta").save(f"{destination}from_call") +known = load(table_name) +known.write.format("delta").save(f"{destination}from_name") +""" + analysis = analyze_notebook_code(source) + assert analysis is not None + assert ( + CodeTable("customers", "dbo") + not in analysis.tables[CodeTable("from_call", "silver")] + ) + assert ( + CodeTable("customers", "dbo") + in analysis.tables[CodeTable("from_name", "silver")] + ) + + def test_saved_select_list_prefixes_columns_from_each_source() -> None: # dim-style notebooks build the select list first, then apply it, then # carry those prefixed columns through alias.* to the write. From 4907248a5c60a310bcfeffdbdca914f1f3b43963 Mon Sep 17 00:00:00 2001 From: Steve Baldwin Date: Tue, 27 Oct 2026 12:10:34 +0000 Subject: [PATCH 07/12] fix(ingestion/fabric): keep plan lineage when notebook code analysis fails A crash while walking the notebook source now stays on that notebook. Table edges from the Spark plan are kept, column lineage is skipped, and the report counts the failure. Co-authored-by: Cursor --- .../fabric/onelake/notebook_code_lineage.py | 54 +++++++++++++------ .../source/fabric/onelake/notebook_jobs.py | 24 +++++++-- .../ingestion/source/fabric/onelake/report.py | 5 ++ .../test_notebook_code_lineage.py | 39 ++++++++++++-- 4 files changed, 99 insertions(+), 23 deletions(-) diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py index 6b2cb9acf61c..9e838f4109fa 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py @@ -49,6 +49,13 @@ class NotebookCodeAnalysis: columns: Dict[CodeTable, ColumnLineage] +class NotebookCodeExtractionError(Exception): + """Notebook source could not be analyzed. + + Callers keep the Spark-plan table lineage. + """ + + def analyze_notebook_code( source: str, *, case_sensitive_columns: bool = False ) -> Optional[NotebookCodeAnalysis]: @@ -58,25 +65,36 @@ def analyze_notebook_code( keep the Spark-plan lineage unchanged. Empty mappings mean the code parsed and contains no writes. Column names match without regard to case unless ``case_sensitive_columns`` is set, and the dataframe's own spelling is kept. + Raises ``NotebookCodeExtractionError`` when analysis fails for any other + reason. """ try: tree = ast.parse(_strip_magics(source)) except SyntaxError: logger.debug("Notebook source is not parseable Python; skipping code lineage") return None + except Exception as exc: + raise NotebookCodeExtractionError( + "Failed to parse notebook source for code lineage" + ) from exc - extractor = _Extractor(case_sensitive_columns=case_sensitive_columns) - extractor.walk(tree.body) - columns: Dict[CodeTable, ColumnLineage] = {} - for target, mapping in extractor.column_lineage.items(): - kept = { - column: {(ref.table, ref.column) for ref in refs} - for column, refs in mapping.items() - if refs - } - if kept: - columns[target] = kept - return NotebookCodeAnalysis(tables=extractor.lineage, columns=columns) + try: + extractor = _Extractor(case_sensitive_columns=case_sensitive_columns) + extractor.walk(tree.body) + columns: Dict[CodeTable, ColumnLineage] = {} + for target, mapping in extractor.column_lineage.items(): + kept = { + column: {(ref.table, ref.column) for ref in refs} + for column, refs in mapping.items() + if refs + } + if kept: + columns[target] = kept + return NotebookCodeAnalysis(tables=extractor.lineage, columns=columns) + except Exception as exc: + raise NotebookCodeExtractionError( + "Failed to extract notebook code lineage" + ) from exc def extract_notebook_code_lineage( @@ -84,11 +102,15 @@ def extract_notebook_code_lineage( ) -> Optional[Dict[CodeTable, Set[CodeTable]]]: """Map each table the notebook writes to the tables that write uses. - Returns None when ``source`` is not parseable Python, so the caller can - keep the Spark-plan lineage unchanged. An empty dict means the code parsed - and contains no writes. + Returns None when ``source`` is not parseable Python or analysis fails, so + the caller can keep the Spark-plan lineage unchanged. An empty dict means + the code parsed and contains no writes. """ - analysis = analyze_notebook_code(source) + try: + analysis = analyze_notebook_code(source) + except NotebookCodeExtractionError: + logger.debug("Notebook code lineage extraction failed", exc_info=True) + return None if analysis is None: return None return analysis.tables diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py index 987fdb870b7e..d516442f0dda 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py @@ -42,6 +42,8 @@ ) from datahub.ingestion.source.fabric.onelake.client import OneLakeClient from datahub.ingestion.source.fabric.onelake.notebook_code_lineage import ( + NotebookCodeAnalysis, + NotebookCodeExtractionError, analyze_notebook_code, reconcile_column_lineage, reconcile_spark_lineage, @@ -344,10 +346,24 @@ def _spark_lineage(self, nb: PendingNotebook) -> Dict[SparkTableRef, _JobLineage SparkTableRef, Dict[str, Set[Tuple[SparkTableRef, str]]] ] = {} if self._reconcile_code and nb.content and nb.language in (None, "python"): - code = analyze_notebook_code( - nb.content, - case_sensitive_columns=self._case_sensitive_columns, - ) + code: Optional[NotebookCodeAnalysis] = None + try: + code = analyze_notebook_code( + nb.content, + case_sensitive_columns=self._case_sensitive_columns, + ) + except NotebookCodeExtractionError as exc: + self._report.report_notebook_code_lineage_failed() + self._report.warning( + title="Failed to Extract Notebook Code Lineage", + message=( + "Could not read the notebook source for lineage. " + "Keeping Spark-plan table lineage." + ), + context=f"notebook={nb.display_name}", + exc=exc, + log=False, + ) if code is not None and code.tables: reconciled = reconcile_spark_lineage( code.tables, raw, self._normalize_name diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/report.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/report.py index fcdfe50fb9f2..72de59594f28 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/report.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/report.py @@ -56,6 +56,7 @@ class FabricOneLakeSourceReport( notebook_runs_scanned: int = 0 notebook_spark_sessions_scanned: int = 0 notebook_spark_lineage_extracted: int = 0 + notebook_code_lineage_extraction_failures: int = 0 entities_profiled: int = 0 # Filtered entities @@ -170,6 +171,10 @@ def report_notebook_spark_lineage_extracted(self) -> None: """Record a notebook that produced lineage from its Spark plans.""" self.notebook_spark_lineage_extracted += 1 + def report_notebook_code_lineage_failed(self) -> None: + """Record a notebook whose source could not be read for code lineage.""" + self.notebook_code_lineage_extraction_failures += 1 + def report_view_missing_definition(self, view_name: str) -> None: """Record a view whose SQL definition was unavailable for lineage parsing.""" self.views_missing_definition.append(view_name) diff --git a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py index b06f4e0f7b44..0d9c4d8ab09e 100644 --- a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py +++ b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py @@ -1,11 +1,14 @@ """Notebook source lineage, reconciled with the tables a Spark run actually touched.""" -from unittest.mock import MagicMock +from unittest.mock import MagicMock, patch + +import pytest from datahub.emitter.mce_builder import make_schema_field_urn from datahub.ingestion.source.fabric.common.models import FabricSparkSession from datahub.ingestion.source.fabric.onelake.notebook_code_lineage import ( CodeTable, + NotebookCodeExtractionError, analyze_notebook_code, extract_notebook_code_lineage, reconcile_spark_lineage, @@ -161,7 +164,11 @@ def inputs(table: str) -> set[str]: assert all(ref.table != "dim_products" for ref in reconciled) -def _emit_dim_user(*, reconcile_code: bool) -> DataJobInputOutputClass: +def _emit_dim_user( + *, reconcile_code: bool, report: FabricOneLakeSourceReport | None = None +) -> DataJobInputOutputClass: + if report is None: + report = FabricOneLakeSourceReport() orders = SparkTableRef(workspace_id=WS, item_id=LH, table="orders", schema="silver") customers = SparkTableRef( workspace_id=WS, item_id=LH, table="customers", schema="silver" @@ -194,7 +201,7 @@ def _emit_dim_user(*, reconcile_code: bool) -> DataJobInputOutputClass: platform_instance=None, env="PROD", execution_history_days=30, - report=FabricOneLakeSourceReport(), + report=report, client=client, known_table_urns=known, normalize_name=lambda name: name, @@ -239,6 +246,32 @@ def test_emitter_uses_code_to_drop_unused_plan_sources() -> None: assert products.to_urn("PROD", None) not in (io.inputDatasets or []) +def test_code_extraction_failure_keeps_plan_table_lineage() -> None: + products = SparkTableRef( + workspace_id=WS, item_id=LH, table="products", schema="silver" + ) + report = FabricOneLakeSourceReport() + with patch( + "datahub.ingestion.source.fabric.onelake.notebook_jobs.analyze_notebook_code", + side_effect=NotebookCodeExtractionError("walk failed"), + ): + io = _emit_dim_user(reconcile_code=True, report=report) + assert report.notebook_code_lineage_extraction_failures == 1 + assert products.to_urn("PROD", None) in (io.inputDatasets or []) + assert not io.fineGrainedLineages + + +def test_walk_failure_is_an_extraction_error() -> None: + with ( + patch( + "datahub.ingestion.source.fabric.onelake.notebook_code_lineage._Extractor.walk", + side_effect=KeyError("column"), + ), + pytest.raises(NotebookCodeExtractionError), + ): + analyze_notebook_code("value = 1\n") + + def _columns(source: str) -> dict[str, dict[str, set[tuple[str, str]]]]: analysis = analyze_notebook_code(source) assert analysis is not None From 17c411df176922072c14f87f95355beb72798aee Mon Sep 17 00:00:00 2001 From: Steve Baldwin Date: Tue, 3 Nov 2026 10:15:30 +0000 Subject: [PATCH 08/12] fix(ingestion/fabric): keep notebook writes behind parameter defaults Code analysis skipped an if branch when its condition was a known boolean. A parameter cell holds only defaults that a pipeline can override, so a write in the skipped branch went missing and reconciliation then dropped the Spark plan's lineage for that table. Walk both branches again. Co-Authored-By: Claude Opus 5.5 --- .../fabric/onelake/notebook_code_lineage.py | 13 +++++-------- .../test_notebook_code_lineage.py | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py index 9e838f4109fa..5bbbe4b149e4 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py @@ -511,14 +511,11 @@ def _stmt(self, stmt: ast.stmt) -> None: self._writes_in(stmt.value) return if isinstance(stmt, ast.If): - cond = self._eval_bool(stmt.test) - if cond is True: - self.walk(stmt.body) - elif cond is False: - self.walk(stmt.orelse) - else: - self.walk(stmt.body) - self.walk(stmt.orelse) + # Walk both branches even when the condition looks constant. A + # parameter cell holds only defaults that a pipeline can override per + # run, and a write skipped here would drop the plan's edge for it. + self.walk(stmt.body) + self.walk(stmt.orelse) return if isinstance(stmt, ast.Return) and stmt.value is not None: self._writes_in(stmt.value) diff --git a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py index 0d9c4d8ab09e..a730c7f3f360 100644 --- a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py +++ b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py @@ -89,6 +89,24 @@ def test_commented_write_and_unused_load_are_absent() -> None: assert "products" not in used +def test_write_behind_a_parameter_default_is_kept() -> None: + # A pipeline can override the parameter cell, so either branch may run. + source = """ +full_load = False +df = spark.read.table("bronze_orders") +if full_load: + df.write.mode("overwrite").saveAsTable("silver_orders") +else: + df.write.mode("append").saveAsTable("silver_orders_delta") +""" + lineage = extract_notebook_code_lineage(source) + assert lineage is not None + assert {target.table for target in lineage} == { + "silver_orders", + "silver_orders_delta", + } + + def test_intermediate_write_is_a_source_of_the_next_write() -> None: source = """ source = f"{silver_path}/Tables/silver/" From bcf024c2c46a0935ca6025fa55a9be3320ae7e52 Mon Sep 17 00:00:00 2001 From: Steve Baldwin Date: Sat, 7 Nov 2026 08:44:06 +0000 Subject: [PATCH 09/12] fix(ingestion/fabric): follow notebook config loops and helper writes Notebook code lineage only resolved writes made directly in the cell, so a loop that calls a helper per config entry left the previous write's table as an input of the next one. Unroll loops over lists of table configs, resolve config fields in paths, and follow helpers that save without returning a dataframe. Co-authored-by: Cursor --- .../fabric/onelake/notebook_code_lineage.py | 170 +++++++++++++++--- .../test_notebook_code_lineage.py | 50 ++++++ 2 files changed, 198 insertions(+), 22 deletions(-) diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py index 5bbbe4b149e4..15035654ca3a 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py @@ -6,8 +6,10 @@ The source text names those tables even when the path is built at run time (``f"{source}orders"``), and it shows which dataframe each write actually uses. -Commented-out cells are not real reads or writes. This module recovers that -per-target source set, and the column renames that dataframe applies: +A loop over a list of table configs is applied once per config, and a helper +that writes without returning is still followed. Commented-out cells are not +real reads or writes. This module recovers that per-target source set, and the +column renames that dataframe applies: ``col(src).alias(dst)``, a ``{source: target}`` mapping dict, ``alias.*``, and ``df["column"]``. The caller keeps an edge only when the executed plans also saw the same source and target, so the resolved OneLake path still comes @@ -239,23 +241,30 @@ def _code_table(text: str) -> Optional[CodeTable]: return CodeTable(table=parts[-1]) -def _eval_tail(expr: ast.AST, env: Dict[str, str]) -> Optional[str]: +def _eval_tail( + expr: ast.AST, + env: Dict[str, str], + records: Optional[Dict[str, Dict[str, str]]] = None, +) -> Optional[str]: """Known suffix of a string expression. An unknown interpolation resets the suffix. ``f"{runtime}/Tables/silver/orders"`` - therefore still ends in the table name. + therefore still ends in the table name. ``config["table_name"]`` resolves + when ``records`` holds that config. """ if isinstance(expr, ast.Constant): return expr.value if isinstance(expr.value, str) else None if isinstance(expr, ast.Name): return env.get(expr.id) + if isinstance(expr, ast.Subscript): + return _record_field(expr, env, records) if isinstance(expr, ast.JoinedStr): acc = "" for part in expr.values: if isinstance(part, ast.Constant) and isinstance(part.value, str): acc += part.value elif isinstance(part, ast.FormattedValue): - inner = _eval_tail(part.value, env) + inner = _eval_tail(part.value, env, records) if inner is None: acc = "" else: @@ -264,16 +273,37 @@ def _eval_tail(expr: ast.AST, env: Dict[str, str]) -> Optional[str]: acc = "" return acc if isinstance(expr, ast.BinOp) and isinstance(expr.op, ast.Add): - right = _eval_tail(expr.right, env) + right = _eval_tail(expr.right, env, records) if right is None: return None - left = _eval_tail(expr.left, env) + left = _eval_tail(expr.left, env, records) return right if left is None else left + right return None -def _code_table_from_expr(expr: ast.expr, env: Dict[str, str]) -> Optional[CodeTable]: - tail = _eval_tail(expr, env) +def _record_field( + expr: ast.Subscript, + env: Dict[str, str], + records: Optional[Dict[str, Dict[str, str]]], +) -> Optional[str]: + if records is None or not isinstance(expr.value, ast.Name): + return None + record = records.get(expr.value.id) + if record is None: + return None + key = _eval_tail(expr.slice, env, records) + if key is None: + return None + value = record.get(key) + return value if isinstance(value, str) else None + + +def _code_table_from_expr( + expr: ast.expr, + env: Dict[str, str], + records: Optional[Dict[str, Dict[str, str]]] = None, +) -> Optional[CodeTable]: + tail = _eval_tail(expr, env, records) if tail is None or not tail.strip(): return None return _code_table(tail) @@ -322,7 +352,11 @@ def _write_receiver(expr: ast.AST) -> Optional[ast.expr]: return None -def _read_table(call: ast.Call, env: Dict[str, str]) -> Optional[CodeTable]: +def _read_table( + call: ast.Call, + env: Dict[str, str], + records: Optional[Dict[str, Dict[str, str]]] = None, +) -> Optional[CodeTable]: func = call.func if not isinstance(func, ast.Attribute) or func.attr not in { "load", @@ -337,7 +371,7 @@ def _read_table(call: ast.Call, env: Dict[str, str]) -> Optional[CodeTable]: return None if not call.args: return None - return _code_table_from_expr(call.args[0], env) + return _code_table_from_expr(call.args[0], env, records) def _same_table(left: CodeTable, right: CodeTable) -> bool: @@ -359,8 +393,12 @@ def _references_frame(expr: ast.AST, frames: Dict[str, Set[CodeTable]]) -> bool: return any(_references_frame(child, frames) for child in ast.iter_child_nodes(expr)) -def _tail_has_tables(expr: ast.expr, env: Dict[str, str]) -> bool: - tail = _eval_tail(expr, env) +def _tail_has_tables( + expr: ast.expr, + env: Dict[str, str], + records: Optional[Dict[str, Dict[str, str]]] = None, +) -> bool: + tail = _eval_tail(expr, env, records) return tail is not None and "Tables" in tail @@ -477,6 +515,9 @@ def __init__(self, *, case_sensitive_columns: bool = False) -> None: self._fns: Dict[str, Union[ast.FunctionDef, ast.AsyncFunctionDef]] = {} self._executing: Set[str] = set() self._return_projection: Optional[_Projection] = None + # Loop variable -> the config dict for the iteration being applied. + self._records: Dict[str, Dict[str, str]] = {} + self._record_lists: Dict[str, List[Dict[str, str]]] = {} # function name -> (dataframe param, path param, dataframe index, path index) self._writers: Dict[str, Tuple[str, str, int, int]] = {} @@ -521,6 +562,8 @@ def _stmt(self, stmt: ast.stmt) -> None: self._writes_in(stmt.value) self._return_projection = self._projection_of(stmt.value) return + if isinstance(stmt, ast.For) and self._unroll_for(stmt): + return if isinstance(stmt, (ast.For, ast.AsyncFor, ast.While)): self.walk(stmt.body) self.walk(stmt.orelse) @@ -540,11 +583,18 @@ def _bind(self, name: str, value: ast.expr) -> None: proj = self._projection_of(value) if proj is not None: reads |= proj.reads - tail = _eval_tail(value, self._strings) + tail = _eval_tail(value, self._strings, self._records) if tail is not None: self._strings[name] = tail else: self._strings.pop(name, None) + records = _eval_record_list(value) + if records is None and isinstance(value, ast.Name): + records = self._record_lists.get(value.id) + if records is not None: + self._record_lists[name] = records + else: + self._record_lists.pop(name, None) mapping = _eval_dict(value) if mapping is None and isinstance(value, ast.Name): mapping = self._dicts.get(value.id) @@ -586,10 +636,36 @@ def _bind(self, name: str, value: ast.expr) -> None: self._projections.pop(name, None) self._exprs[name] = value + def _unroll_for(self, stmt: ast.For) -> bool: + """Apply a loop once per config when it walks a list of table dicts. + + ``for config in configs`` otherwise runs with ``config["table_name"]`` + unknown, so every write collapses to the same unresolved path and the + Spark plan's carried-forward tables survive. + """ + if not isinstance(stmt.target, ast.Name): + return False + if isinstance(stmt.iter, ast.Name): + records = self._record_lists.get(stmt.iter.id) + else: + records = _eval_record_list(stmt.iter) + if not records: + return False + for record in records: + saved = self._snapshot() + try: + self._records[stmt.target.id] = record + self.walk(stmt.body) + finally: + self._restore(saved) + self.walk(stmt.orelse) + return True + def _writes_in(self, expr: ast.AST) -> None: if isinstance(expr, ast.Call): self._record_save(expr) self._record_writer_call(expr) + self._execute_for_side_effects(expr) for child in ast.iter_child_nodes(expr): self._writes_in(child) @@ -605,7 +681,7 @@ def _record_save(self, call: ast.Call) -> None: return if not call.args: return - target = _code_table_from_expr(call.args[0], self._strings) + target = _code_table_from_expr(call.args[0], self._strings, self._records) if target is None: return df_expr = _write_receiver(func.value) @@ -619,7 +695,7 @@ def _record_writer_call(self, call: ast.Call) -> None: df_expr, path_expr = self._writer_args(call) if df_expr is None or path_expr is None: return - target = _code_table_from_expr(path_expr, self._strings) + target = _code_table_from_expr(path_expr, self._strings, self._records) if target is None: return self._add_edge(target, df_expr) @@ -639,7 +715,9 @@ def _writer_args( path_expr: Optional[ast.expr] = None candidates = list(call.args) + [kw.value for kw in call.keywords] for arg in candidates: - if path_expr is None and _tail_has_tables(arg, self._strings): + if path_expr is None and _tail_has_tables( + arg, self._strings, self._records + ): path_expr = arg elif df_expr is None and _references_frame(arg, self._frames): df_expr = arg @@ -679,7 +757,7 @@ def _projection_of(self, expr: ast.AST) -> Optional[_Projection]: called = self._call_function(expr) if called is not None: return called - read = _read_table(expr, self._strings) + read = _read_table(expr, self._strings, self._records) if read is not None: return _Projection(reads={read}, passthrough=read) func = expr.func @@ -823,9 +901,28 @@ def _call_function(self, call: ast.Call) -> Optional[_Projection]: fn = self._fns.get(call.func.id) if fn is None or call.func.id in self._executing or not _returns_value(fn): return None + return self._run_function(fn, call) + + def _execute_for_side_effects(self, call: ast.Call) -> None: + """Follow a helper that writes and does not return its dataframe. + + ``process(table_name=...)`` saves inside the function. The call itself + is not a ``.save``, so without this walk the write is invisible and the + Spark plan keeps every earlier table. + """ + if not isinstance(call.func, ast.Name): + return + fn = self._fns.get(call.func.id) + if fn is None or call.func.id in self._executing or _returns_value(fn): + return + self._run_function(fn, call) + + def _run_function( + self, fn: Union[ast.FunctionDef, ast.AsyncFunctionDef], call: ast.Call + ) -> Optional[_Projection]: bindings = self._capture_bindings(fn, call) saved = self._snapshot() - self._executing.add(call.func.id) + self._executing.add(fn.name) try: # A parameter hides the outer name even when its argument cannot # be evaluated. Otherwise ``load(get_name())`` still sees a global @@ -838,7 +935,7 @@ def _call_function(self, call: ast.Call) -> Optional[_Projection]: self.walk(fn.body) return self._return_projection finally: - self._executing.discard(call.func.id) + self._executing.discard(fn.name) self._restore(saved) def _snapshot(self) -> Tuple: @@ -853,6 +950,8 @@ def _snapshot(self) -> Tuple: dict(self._projections), dict(self._exprs), self._return_projection, + dict(self._records), + dict(self._record_lists), ) def _restore(self, snap: Tuple) -> None: @@ -867,6 +966,8 @@ def _restore(self, snap: Tuple) -> None: self._projections, self._exprs, self._return_projection, + self._records, + self._record_lists, ) = snap def _capture_bindings( @@ -904,7 +1005,7 @@ def _capture(self, expr: ast.expr) -> Tuple[str, object]: flag = self._eval_bool(expr) if flag is not None: return ("bool", flag) - text = _eval_tail(expr, self._strings) + text = _eval_tail(expr, self._strings, self._records) if text is not None: return ("str", text) return ("expr", expr) @@ -933,6 +1034,7 @@ def _hide_binding(self, name: str) -> None: self._bools.pop(name, None) self._projections.pop(name, None) self._exprs.pop(name, None) + self._records.pop(name, None) def _eval_bool(self, expr: ast.AST) -> Optional[bool]: if isinstance(expr, ast.Constant) and isinstance(expr.value, bool): @@ -1185,7 +1287,7 @@ def _collect(self, expr: ast.AST) -> Tuple[Set[CodeTable], Set[CodeTable]]: produced.update(self._produced.get(expr.id, ())) return reads, produced if isinstance(expr, ast.Call): - read = _read_table(expr, self._strings) + read = _read_table(expr, self._strings, self._records) if read is not None: reads.add(read) for child in ast.iter_child_nodes(expr): @@ -1242,6 +1344,30 @@ def _named_column(expr: ast.expr, env: Dict[str, str]) -> Optional[str]: return _eval_tail(expr.args[0], env) +def _eval_record_list(expr: ast.expr) -> Optional[List[Dict[str, str]]]: + """List of ``{"table_name": "orders", ...}`` configs. + + Non-string fields, such as a ``select_expr`` list, are ignored. A dict + with no string fields rejects the whole list so the loop is not unrolled. + """ + if not isinstance(expr, (ast.List, ast.Tuple)): + return None + records: List[Dict[str, str]] = [] + for elt in expr.elts: + if not isinstance(elt, ast.Dict): + return None + record: Dict[str, str] = {} + for key, value in zip(elt.keys, elt.values, strict=False): + if not isinstance(key, ast.Constant) or not isinstance(key.value, str): + return None + if isinstance(value, ast.Constant) and isinstance(value.value, str): + record[key.value] = value.value + if not record: + return None + records.append(record) + return records + + def _eval_dict(expr: ast.expr) -> Optional[Dict[str, str]]: if not isinstance(expr, ast.Dict): return None diff --git a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py index a730c7f3f360..27da01469c1f 100644 --- a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py +++ b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py @@ -126,6 +126,56 @@ def test_intermediate_write_is_a_source_of_the_next_write() -> None: assert CodeTable(table="gold_mid", schema="gold") in final +def test_config_loop_keeps_each_write_on_its_own_source() -> None: + # One helper copies each config entry. The Spark plan still credits the + # previous silver table to the next write; the source text does not. + source = """ +source = f"{bronze}/Tables/dbo/" +destination = f"{silver}/Tables/silver/" + +def process_full_load_table(table_name, source, destination, select_expr): + source_path = f"{source}{table_name}" + target_table = f"{destination}silver_{table_name}" + df = spark.read.format("delta").load(source_path) + df = df.withColumn("SourceSystem", lit("SRC")) + df = df.selectExpr(*select_expr) + df.write.format("delta").mode("overwrite").save(target_table) + +configs = [ + {"table_name": "orders", "select_expr": ["id as Id"]}, + {"table_name": "customers", "select_expr": ["id as Id"]}, +] + +for config in configs: + process_full_load_table( + table_name=config["table_name"], + source=source, + destination=destination, + select_expr=config["select_expr"], + ) +""" + lineage = extract_notebook_code_lineage(source) + assert lineage is not None + assert lineage[CodeTable("silver_orders", "silver")] == {CodeTable("orders", "dbo")} + assert lineage[CodeTable("silver_customers", "silver")] == { + CodeTable("customers", "dbo") + } + + orders = SparkTableRef(WS, LH, "orders", "dbo") + customers = SparkTableRef(WS, LH, "customers", "dbo") + silver_orders = SparkTableRef(WS, LH, "silver_orders", "silver") + silver_customers = SparkTableRef(WS, LH, "silver_customers", "silver") + reconciled = reconcile_spark_lineage( + lineage, + { + silver_orders: {orders}, + silver_customers: {customers, silver_orders}, + }, + lambda name: name, + ) + assert reconciled[silver_customers] == {customers} + + def test_unparseable_source_leaves_plan_lineage_unchanged() -> None: assert extract_notebook_code_lineage("def broken(:") is None From 009d96f032604c1dc327fb8f29e9db8cf61fbc20 Mon Sep 17 00:00:00 2001 From: Steve Baldwin Date: Fri, 27 Nov 2026 11:10:15 +0000 Subject: [PATCH 10/12] feat(ingestion/fabric): attach notebook source to notebook jobs When include_notebook_source is enabled and notebook_execution is on, each notebook job carries the masked notebook source as dataTransformLogic so it shows in the job's Logic section. The language is always SQL because the GraphQL QueryLanguage enum has no UNKNOWN value and emitting it fails lineage queries. Co-authored-by: Cursor --- .../fabric-onelake/fabric-onelake_post.md | 2 +- .../ingestion/source/fabric/onelake/config.py | 4 +- .../source/fabric/onelake/notebook_jobs.py | 32 +++++++- .../ingestion/source/fabric/onelake/source.py | 1 + .../unit/fabric_onelake/test_notebook_jobs.py | 74 ++++++++++++++++++- 5 files changed, 107 insertions(+), 6 deletions(-) diff --git a/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md b/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md index 4a2e3993e7cc..12aaf7ad746e 100644 --- a/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md +++ b/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md @@ -369,7 +369,7 @@ Notebook ingestion is off by default. Set `include_notebooks: true` to ingest ea For each notebook that passes the pattern, the connector calls `POST /workspaces/{workspaceId}/notebooks/{notebookId}/getDefinition?format=fabricGitSource`. The language (`python`, `sql`, `scala`, or `r`) is stored in `language` when the content file suffix identifies it. `path` is always set. If the definition request fails, the notebook is still ingested without contents. -The notebook source is not emitted by default, because notebooks often contain connection strings, SAS tokens or keys. Set `include_notebook_source: true` to store it as the dataset view definition, so it shows on the View Definition tab. It is not repeated in custom properties, which are indexed as search keywords and cannot hold a large notebook. Before it is emitted, common credential patterns are replaced with `***`: `password=`, `AccountKey=`, `sig=` and similar assignments, bearer and basic tokens, user info in URLs, and private key blocks. Masking is best effort and cannot recognise every secret, so keep credentials in Key Vault or a secret scope rather than in notebook code. +The notebook source is not emitted by default, because notebooks often contain connection strings, SAS tokens or keys. Set `include_notebook_source: true` to store it as the dataset view definition, so it shows on the View Definition tab. When `notebook_execution` is enabled, the same source is also attached to each notebook job as its transformation logic, so it shows in the job's Logic section. The job's query language is always recorded as `SQL`, because DataHub's query language field has no PySpark, Scala or R value. It is not repeated in custom properties, which are indexed as search keywords and cannot hold a large notebook. Before it is emitted, common credential patterns are replaced with `***`: `password=`, `AccountKey=`, `sig=` and similar assignments, bearer and basic tokens, user info in URLs, and private key blocks. Masking is best effort and cannot recognise every secret, so keep credentials in Key Vault or a secret scope rather than in notebook code. The caller needs `Workspace.Read.All` or `Workspace.ReadWrite.All`. diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py index b7f8296e2419..01fabe819c03 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py @@ -351,7 +351,9 @@ class FabricOneLakeSourceConfig( default=False, description=( "Emit each notebook's source on the View Definition tab " - "(`viewProperties.viewLogic`). Off by default because notebooks often " + "(`viewProperties.viewLogic`) and, when `notebook_execution` is " + "enabled, on each notebook job's Logic section " + "(`dataTransformLogic`). Off by default because notebooks often " "hold connection strings, SAS tokens or keys. When on, common " "credential patterns (`password=`, `AccountKey=`, `sig=`, bearer " "tokens, URL user info, private keys) are masked before emitting; " diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py index d516442f0dda..974426a3d7dc 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py @@ -21,6 +21,7 @@ DataProcessInstance, InstanceRunResult, ) +from datahub.ingestion.agent.redact import scrub_text from datahub.ingestion.api.workunit import MetadataWorkUnit from datahub.ingestion.source.common.subtypes import ( DataFlowSubTypes, @@ -56,9 +57,13 @@ from datahub.metadata.schema_classes import ( DataJobInputOutputClass, DataProcessTypeClass, + DataTransformClass, + DataTransformLogicClass, FineGrainedLineageClass, FineGrainedLineageDownstreamTypeClass, FineGrainedLineageUpstreamTypeClass, + QueryLanguageClass, + QueryStatementClass, ) from datahub.metadata.urns import CorpUserUrn, DataFlowUrn, DataJobUrn from datahub.sdk.dataflow import DataFlow @@ -122,6 +127,7 @@ def __init__( execution_history_days: int, reconcile_code: bool = False, case_sensitive_columns: bool = False, + include_source: bool = False, report: FabricOneLakeSourceReport, client: OneLakeClient, known_table_urns: Set[str], @@ -133,6 +139,7 @@ def __init__( self._execution_history_days = execution_history_days self._reconcile_code = reconcile_code self._case_sensitive_columns = case_sensitive_columns + self._include_source = include_source self._report = report self._client = client self._known_table_urns = known_table_urns @@ -230,6 +237,12 @@ def _emit_output_job( if nb.language: custom_properties["language"] = nb.language + extra_aspects: List[Union[DataJobInputOutputClass, DataTransformLogicClass]] = [ + io_aspect + ] + if self._include_source and nb.content: + extra_aspects.append(self._transform_logic(nb.content)) + datajob = DataJob( name=self._job_id(output), flow=dataflow, @@ -238,7 +251,7 @@ def _emit_output_job( subtype=DataJobSubTypes.FABRIC_SPARK_JOB, external_url=external_url, custom_properties=custom_properties, - extra_aspects=[io_aspect], + extra_aspects=extra_aspects, # The SDK coerces (userPrincipalName, ownershipType) string tuples # into owner URNs at runtime; its stub only advertises urn inputs. owners=self._owners_fn(nb.owner_user_principal_name), @@ -246,6 +259,23 @@ def _emit_output_job( datajob._set_container(workspace_key) yield datajob + @staticmethod + def _transform_logic(content: str) -> DataTransformLogicClass: + # Same credential masking as the notebook dataset's viewLogic. The language + # is always SQL: the GraphQL QueryLanguage enum has no UNKNOWN value, so + # emitting it makes every lineage query that touches the job fail. Same + # workaround as the stored procedure sources. + return DataTransformLogicClass( + transforms=[ + DataTransformClass( + queryStatement=QueryStatementClass( + value=scrub_text(content, set()), + language=QueryLanguageClass.SQL, + ) + ) + ] + ) + @staticmethod def _output_label(output: SparkTableRef) -> str: return f"{output.schema}.{output.table}" if output.schema else output.table diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/source.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/source.py index 105852a85afb..6af67ec232ac 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/source.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/source.py @@ -1364,6 +1364,7 @@ def _emit_notebook_processes( execution_history_days=self.config.notebook_execution.history_days, reconcile_code=self.config.notebook_execution.reconcile_code, case_sensitive_columns=self.config.notebook_execution.case_sensitive_columns, + include_source=self.config.include_notebook_source, report=self.report, client=self.client, known_table_urns=self._notebook_known_table_urns, diff --git a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_jobs.py b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_jobs.py index c7de17163e17..708157a50d8f 100644 --- a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_jobs.py +++ b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_jobs.py @@ -19,6 +19,8 @@ from datahub.metadata.schema_classes import ( DataJobInputOutputClass, DataProcessInstanceRelationshipsClass, + DataTransformLogicClass, + QueryLanguageClass, ) from datahub.sdk.dataflow import DataFlow from datahub.sdk.datajob import DataJob @@ -198,7 +200,13 @@ def test_run_attaches_as_dpi_to_every_job_not_the_flow() -> None: assert str(flow.urn) not in templates -def _emit_with(client: MagicMock, known: Optional[Set[str]] = None) -> tuple: +def _emit_with( + client: MagicMock, + known: Optional[Set[str]] = None, + include_source: bool = False, + content: Optional[str] = None, + language: str = "python", +) -> tuple: report = FabricOneLakeSourceReport() if known is None: known = { @@ -208,6 +216,7 @@ def _emit_with(client: MagicMock, known: Optional[Set[str]] = None) -> tuple: platform_instance=None, env="PROD", execution_history_days=30, + include_source=include_source, report=report, client=client, known_table_urns=known, @@ -221,12 +230,71 @@ def _emit_with(client: MagicMock, known: Optional[Set[str]] = None) -> tuple: display_name="pipeline", description=None, owner_user_principal_name=None, - content=None, - language="python", + content=content, + language=language, ) return list(emitter.emit([nb])), report +def _plans_client() -> MagicMock: + client = MagicMock() + client.list_notebook_spark_sessions.return_value = [ + FabricSparkSession(livy_id="livy-1", application_id="app-1", item_id=NB) + ] + client.get_spark_sql_plans.return_value = [_PLAN_MID, _PLAN_FINAL] + client.get_notebook_runs.return_value = [] + return client + + +_NOTEBOOK_SOURCE = ( + 'df = spark.read.table("silver_a")\n' + 'conn = "Server=x;password=hunter2"\n' + 'df.write.saveAsTable("gold_mid")\n' +) + + +def test_jobs_carry_masked_notebook_source_when_enabled() -> None: + known = { + _ref(t, s).to_urn("PROD", None) + for t, s in ( + ("silver_a", "silver"), + ("gold_mid", "gold"), + ("gold_final", "gold"), + ) + } + emitted, _report = _emit_with( + _plans_client(), known=known, include_source=True, content=_NOTEBOOK_SOURCE + ) + jobs = [dj for dj in emitted if isinstance(dj, DataJob)] + assert len(jobs) == 2 + for job in jobs: + logic = job._get_aspect(DataTransformLogicClass) + assert logic is not None + statement = logic.transforms[0].queryStatement + assert statement is not None + assert 'saveAsTable("gold_mid")' in statement.value + assert "hunter2" not in statement.value + # GraphQL's QueryLanguage enum only has SQL; anything else breaks lineage queries. + assert statement.language == QueryLanguageClass.SQL + + +def test_jobs_omit_notebook_source_by_default() -> None: + known = { + _ref(t, s).to_urn("PROD", None) + for t, s in ( + ("silver_a", "silver"), + ("gold_mid", "gold"), + ("gold_final", "gold"), + ) + } + emitted, _report = _emit_with( + _plans_client(), known=known, content=_NOTEBOOK_SOURCE + ) + jobs = [dj for dj in emitted if isinstance(dj, DataJob)] + assert jobs + assert all(job._get_aspect(DataTransformLogicClass) is None for job in jobs) + + def test_output_not_in_catalog_produces_no_job() -> None: # The notebook writes a table that was never ingested (e.g. filtered out by # patterns), so no job/dataset is fabricated for it. From ced38f324b59a616c570f57e17a2df844cb53393 Mon Sep 17 00:00:00 2001 From: Steve Baldwin Date: Fri, 27 Nov 2026 12:17:44 +0000 Subject: [PATCH 11/12] fix(ingestion/fabric): scope notebook lineage to each notebook's own cells - Drop Spark executions whose cell code is not in the notebook, so shared sessions no longer leak one notebook's reads into another's writes - Resolve table paths built by helper functions in notebook code - Emit same-name column lineage for notebooks that copy a table unchanged - Add notebook_spark_executions_skipped report counter Co-authored-by: Cursor --- .../fabric-onelake/fabric-onelake_post.md | 2 +- .../ingestion/source/fabric/common/models.py | 13 ++ .../ingestion/source/fabric/onelake/client.py | 58 +++-- .../ingestion/source/fabric/onelake/config.py | 3 +- .../fabric/onelake/notebook_code_lineage.py | 89 +++++++- .../source/fabric/onelake/notebook_jobs.py | 107 ++++++++- .../ingestion/source/fabric/onelake/report.py | 5 + .../ingestion/source/fabric/onelake/source.py | 11 + .../test_notebook_code_lineage.py | 207 ++++++++++++++++-- .../unit/fabric_onelake/test_notebook_jobs.py | 78 ++++++- .../test_notebook_spark_lineage.py | 24 ++ 11 files changed, 549 insertions(+), 48 deletions(-) diff --git a/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md b/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md index 12aaf7ad746e..f8364834291d 100644 --- a/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md +++ b/metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md @@ -377,7 +377,7 @@ The caller needs `Workspace.Read.All` or `Workspace.ReadWrite.All`. `notebook_execution.enabled` (off by default, requires `include_notebooks: true`) also models each notebook as a **pipeline**: one DataFlow per notebook (subtype "Fabric Spark Pipeline"), and under it one Spark-job DataJob (subtype "Fabric Spark Job") **per table the notebook writes**. Each job carries that output table's own upstreams, so lineage renders as `input → [job] → output` — precise table-to-table edges with the notebook transformation attributed, not one job with a cross-product of every table the notebook ever read and wrote. When one output table is itself an input to another output table's job in the same notebook, the two jobs are chained **job → job**. The lineage lives on the jobs, not the notebook dataset, so the notebook's code and its lineage (process) stay cleanly separated. It emits two things from the notebook's run history over `notebook_execution.history_days` (default 7): table-level **lineage** on the per-output jobs, and a **run history** of `DataProcessInstance`s on those jobs. -**Lineage.** Fabric exposes no API that lists the tables a notebook reads or writes, and the source text hides them when paths are built at run time (e.g. `spark.read.format("delta").load(f"{source}{table}")` or `DeltaTable.forPath(spark, target)`). So the connector reads the **resolved Spark physical plans** of each run instead: for every run in the window it fetches the run's SQL executions from the Spark monitoring API (`livySessions` + the Spark History Server SQL API) and extracts the `abfss://` OneLake table paths actually read and written. Attribution is **order-aware within a run**: a notebook usually reads a table in one Spark execution and writes a derived table in a later execution whose plan references a cached relation rather than the source path, so each written table is credited with the tables read earlier in the same run (the read set resets after each write). This keeps independent, sequential pipelines precise instead of collapsing a run into a cross-product, and recovers read-then-write edges that span executions. Those paths map directly to the GUID-based dataset URNs the connector emits. Set `notebook_execution.reconcile_code: true` (off by default; requires `notebook_execution.enabled`) to narrow that plan lineage with the notebook source when it is Python: each write is kept only with the tables its dataframe actually uses, and a write that exists only in a commented-out cell is dropped. The same pass reads column renames — `col(src).alias(dst)`, a `{source: target}` mapping dict, `alias.*` after a join, and `df["column"]` — and emits them as column-level lineage on that write's job. Column names are matched without regard to case, which is Spark's default, and the dataframe's own spelling is kept (`select("name")` still emits `NAME`). Set `notebook_execution.case_sensitive_columns: true` when the Spark session has `spark.sql.caseSensitive` enabled. The plans still supply the resolved OneLake path, so a table loaded from a run-time path stays attached to the name in the code. With the flag off, plan lineage is emitted unchanged. Because a notebook may apply only specific cells on a given run, lineage is **accumulated across all of the notebook's runs** in the window, giving a complete picture over time. Only edges to tables ingested in the same run are kept; GUID-built URNs that do not match an ingested table, and internal Spark scratch paths (shuffle, lakehouse-warmup), are dropped. +**Lineage.** Fabric exposes no API that lists the tables a notebook reads or writes, and the source text hides them when paths are built at run time (e.g. `spark.read.format("delta").load(f"{source}{table}")` or `DeltaTable.forPath(spark, target)`). So the connector reads the **resolved Spark physical plans** of each run instead: for every run in the window it fetches the run's SQL executions from the Spark monitoring API (`livySessions` + the Spark History Server SQL API) and extracts the `abfss://` OneLake table paths actually read and written. Attribution is **order-aware within a run**: a notebook usually reads a table in one Spark execution and writes a derived table in a later execution whose plan references a cached relation rather than the source path, so each written table is credited with the tables read earlier in the same run (the read set resets after each write). This keeps independent, sequential pipelines precise instead of collapsing a run into a cross-product, and recovers read-then-write edges that span executions. Those paths map directly to the GUID-based dataset URNs the connector emits. Set `notebook_execution.reconcile_code: true` (off by default; requires `notebook_execution.enabled`) to narrow that plan lineage with the notebook source when it is Python: each write is kept only with the tables its dataframe actually uses, and a write that exists only in a commented-out cell is dropped. The same pass reads column renames — `col(src).alias(dst)`, a `{source: target}` mapping dict, `alias.*` after a join, and `df["column"]` — and emits them as column-level lineage on that write's job. A write that copies a table without a `select` (for example `df.write...save(path)` on a dataframe read from another table) also gets same-name column lineage for the columns both ingested tables share, minus any the notebook drops or renames. Column names are matched without regard to case, which is Spark's default, and the dataframe's own spelling is kept (`select("name")` still emits `NAME`). Set `notebook_execution.case_sensitive_columns: true` when the Spark session has `spark.sql.caseSensitive` enabled. The plans still supply the resolved OneLake path, so a table loaded from a run-time path stays attached to the name in the code. With the flag off, plan lineage is emitted unchanged. Because a notebook may apply only specific cells on a given run, lineage is **accumulated across all of the notebook's runs** in the window, giving a complete picture over time. Only edges to tables ingested in the same run are kept; GUID-built URNs that do not match an ingested table, and internal Spark scratch paths (shuffle, lakehouse-warmup), are dropped. **Run history.** A Fabric run executes the whole notebook (the Job Scheduler reports one status per run, not per table), so for each run in the window the connector emits a `DataProcessInstance` on each of the notebook's per-output jobs — the whole-notebook run is recorded against every job it contains, falling back to the DataFlow only when a run resolved no per-table lineage — read from the Job Scheduler `GET /workspaces/{id}/items/{itemId}/jobs/instances` API. Each instance records start/end time and the run result (success / failure / skipped). diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/common/models.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/common/models.py index 71cb815a8a98..35b3878a247f 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/common/models.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/common/models.py @@ -226,6 +226,19 @@ class FabricJobInstance: failure_reason: Optional[str] = None +@dataclass(frozen=True) +class SparkSqlExecution: + """One SQL execution in a Spark run, from the Spark History Server SQL API. + + ``description`` is the Spark job group, which holds the code of the notebook + cell that ran the statement. Notebooks that share one Spark application are + only told apart by this text. + """ + + plan: str + description: Optional[str] = None + + @dataclass class FabricSparkSession: """A Spark (Livy) session for a notebook run, from the Spark monitoring API. diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/client.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/client.py index 35ca76dfcdf7..3571e3cabd4a 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/client.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/client.py @@ -16,6 +16,7 @@ FabricJobInstance, FabricSparkSession, FabricWorkspace, + SparkSqlExecution, item_owner_user_principal_name, sensitivity_label_id, ) @@ -387,27 +388,43 @@ def get_spark_sql_plans( livy_id: str, application_id: str, ) -> List[str]: - """Return the physical plan text of each SQL execution in a Spark run. + """Return the physical plan text of each SQL execution in a Spark run.""" + return [ + execution.plan + for execution in self.get_spark_sql_executions( + workspace_id, notebook_id, livy_id, application_id + ) + ] + + def get_spark_sql_executions( + self, + workspace_id: str, + notebook_id: str, + livy_id: str, + application_id: str, + ) -> List[SparkSqlExecution]: + """Return each SQL execution in a Spark run, with the cell that ran it. Proxies the Spark History Server SQL API, whose executions carry a ``planDescription`` listing the resolved ``abfss://`` paths read and - written. The endpoint returns a bare JSON array, not a paged envelope, - and defaults to only the first 20 executions - so it must be paged - explicitly via ``offset``/``length``. Table writes typically run late - in a notebook, so a truncated fetch sees the reads but misses the - writes (hence lineage with inputs but no outputs). - - Plans are returned in chronological execution order (ascending SQL - execution ``id``). Lineage attribution is order-aware - a write is - credited with the tables read earlier in the same run - so the API's - own ordering (newest-first, and sliced across pages) must be normalized - here before the plans are consumed. + written, and a ``description`` holding the statement's job group. The + endpoint returns a bare JSON array, not a paged envelope, and defaults to + only the first 20 executions - so it must be paged explicitly via + ``offset``/``length``. Table writes typically run late in a notebook, so + a truncated fetch sees the reads but misses the writes (hence lineage + with inputs but no outputs). + + Executions are returned in chronological order (ascending SQL execution + ``id``). Lineage attribution is order-aware - a write is credited with + the tables read earlier in the same run - so the API's own ordering + (newest-first, and sliced across pages) must be normalized here before + the executions are consumed. """ endpoint = ( f"workspaces/{workspace_id}/notebooks/{notebook_id}" f"/livySessions/{livy_id}/applications/{application_id}/sql" ) - executions: List[Tuple[int, str]] = [] + executions: List[Tuple[int, SparkSqlExecution]] = [] offset = 0 while True: data = self.get( @@ -428,12 +445,23 @@ def get_spark_sql_plans( # order when absent so a plan is never silently dropped. exec_id = execution.get("id") order = exec_id if isinstance(exec_id, int) else len(executions) - executions.append((order, execution["planDescription"])) + description = execution.get("description") + executions.append( + ( + order, + SparkSqlExecution( + plan=execution["planDescription"], + description=description + if isinstance(description, str) + else None, + ), + ) + ) if len(data) < _SPARK_SQL_PAGE_SIZE: break offset += _SPARK_SQL_PAGE_SIZE executions.sort(key=lambda item: item[0]) - return [plan for _, plan in executions] + return [execution for _, execution in executions] def _is_lakehouse_schemas_enabled( self, workspace_id: str, lakehouse_id: str diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py index 01fabe819c03..c278a9fa1b4c 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/config.py @@ -110,7 +110,8 @@ class NotebookExecutionConfig(ConfigModel): "exists only in a commented-out cell is dropped. Column renames in " "that dataframe (`col(src).alias(dst)`, a `{source: target}` mapping, " '`alias.*`, and `df["column"]`) are emitted as column-level lineage ' - "on the job. The plans still supply the resolved OneLake path. Off " + "on the job, as is a table copied without a select, for the columns " + "both tables share. The plans still supply the resolved OneLake path. Off " "by default, so plan lineage is emitted unchanged. Requires " "`enabled=True`." ), diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py index 15035654ca3a..a9119110af75 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py @@ -22,7 +22,17 @@ import copy import logging from dataclasses import dataclass, field -from typing import Callable, Dict, Iterable, List, Optional, Set, Tuple, Union +from typing import ( + Callable, + Dict, + FrozenSet, + Iterable, + List, + Optional, + Set, + Tuple, + Union, +) from datahub.ingestion.source.fabric.onelake.notebook_spark_lineage import ( SparkTableRef, @@ -43,12 +53,26 @@ class CodeTable: ColumnLineage = Dict[str, Set[Tuple[CodeTable, str]]] +@dataclass(frozen=True) +class PassthroughSource: + """A write that copies ``table`` without a select. + + Every column keeps its name, except the ones the notebook dropped or + renamed. The code cannot list those columns, so the caller pairs them up + from the ingested schemas. + """ + + table: CodeTable + dropped: FrozenSet[str] = frozenset() + + @dataclass class NotebookCodeAnalysis: """Table edges and column renames recovered from one notebook.""" tables: Dict[CodeTable, Set[CodeTable]] columns: Dict[CodeTable, ColumnLineage] + passthrough: Dict[CodeTable, PassthroughSource] = field(default_factory=dict) class NotebookCodeExtractionError(Exception): @@ -92,7 +116,11 @@ def analyze_notebook_code( } if kept: columns[target] = kept - return NotebookCodeAnalysis(tables=extractor.lineage, columns=columns) + return NotebookCodeAnalysis( + tables=extractor.lineage, + columns=columns, + passthrough=extractor.passthrough_sources(), + ) except Exception as exc: raise NotebookCodeExtractionError( "Failed to extract notebook code lineage" @@ -185,6 +213,26 @@ def reconcile_column_lineage( return reconciled +def reconcile_passthrough( + passthrough: Dict[CodeTable, PassthroughSource], + execution: Dict[SparkTableRef, Set[SparkTableRef]], + normalize: Callable[[str], str], +) -> Dict[SparkTableRef, Tuple[SparkTableRef, FrozenSet[str]]]: + """Resolve each copied table to the Spark ref the plans recorded. + + Kept only when the copy's source is one of the write's executed inputs and + names exactly one table, so a name two lakehouses share is never guessed. + """ + reconciled: Dict[SparkTableRef, Tuple[SparkTableRef, FrozenSet[str]]] = {} + for target, copy_of in passthrough.items(): + for output in _resolve(target, execution, normalize): + sources = _resolve(copy_of.table, execution.get(output, set()), normalize) + sources = [ref for ref in sources if ref != output] + if len(sources) == 1: + reconciled[output] = (sources[0], copy_of.dropped) + return reconciled + + def _resolve( code: CodeTable, pool: Iterable[SparkTableRef], @@ -278,6 +326,16 @@ def _eval_tail( return None left = _eval_tail(expr.left, env, records) return right if left is None else left + right + if isinstance(expr, ast.Call) and isinstance(expr.func, ast.Name): + # Path helpers take (workspace, lakehouse, schema, table) and are often + # defined in a notebook pulled in with %run, so the body is unavailable. + # When the last two arguments resolve to names, the call addresses + # Tables//. + if len(expr.args) >= 3: + schema = _eval_tail(expr.args[-2], env, records) + table = _eval_tail(expr.args[-1], env, records) + if schema and table and "/" not in schema and "/" not in table: + return f"Tables/{schema}/{table}" return None @@ -503,6 +561,9 @@ def __init__(self, *, case_sensitive_columns: bool = False) -> None: self._case_sensitive_columns = case_sensitive_columns self.lineage: Dict[CodeTable, Set[CodeTable]] = {} self.column_lineage: Dict[CodeTable, Dict[str, Set[_ColRef]]] = {} + self._passthrough: Dict[CodeTable, PassthroughSource] = {} + # Targets written from different sources: no single source to pair with. + self._passthrough_conflicts: Set[CodeTable] = set() self._frames: Dict[str, Set[CodeTable]] = {} self._produced: Dict[str, Set[CodeTable]] = {} self._strings: Dict[str, str] = {} @@ -737,8 +798,30 @@ def _add_edge(self, target: CodeTable, df_expr: ast.expr) -> None: root = _root_name(df_expr) if root is not None: self._produced.setdefault(root, set()).add(target) - if proj is not None: + if proj is None: + self._passthrough_conflicts.add(target) + else: self._record_columns(target, proj) + self._record_passthrough(target, proj) + + def passthrough_sources(self) -> Dict[CodeTable, PassthroughSource]: + return { + target: source + for target, source in self._passthrough.items() + if target not in self._passthrough_conflicts + } + + def _record_passthrough(self, target: CodeTable, proj: _Projection) -> None: + if proj.projected or proj.passthrough is None: + self._passthrough_conflicts.add(target) + return + if _same_table(proj.passthrough, target): + return + source = PassthroughSource( + table=proj.passthrough, dropped=frozenset(proj.dropped) + ) + if self._passthrough.setdefault(target, source) != source: + self._passthrough_conflicts.add(target) def _record_columns(self, target: CodeTable, proj: _Projection) -> None: bucket = self.column_lineage.setdefault(target, {}) diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py index 974426a3d7dc..e3ff94248cbd 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py @@ -12,9 +12,20 @@ """ import logging +import re from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone -from typing import Callable, Dict, Iterable, List, Optional, Set, Tuple, Union +from typing import ( + Callable, + Dict, + FrozenSet, + Iterable, + List, + Optional, + Set, + Tuple, + Union, +) import datahub.emitter.mce_builder as builder from datahub.api.entities.dataprocess.dataprocess_instance import ( @@ -31,6 +42,7 @@ from datahub.ingestion.source.fabric.common.models import ( FabricJobInstance, ItemJobStatus, + SparkSqlExecution, WorkspaceKey, ) from datahub.ingestion.source.fabric.common.urn_generator import ( @@ -47,6 +59,7 @@ NotebookCodeExtractionError, analyze_notebook_code, reconcile_column_lineage, + reconcile_passthrough, reconcile_spark_lineage, ) from datahub.ingestion.source.fabric.onelake.notebook_spark_lineage import ( @@ -89,6 +102,25 @@ def _iso_to_millis(iso_str: str) -> int: return int(parse_iso_datetime(iso_str).timestamp() * 1000) +# Spark prefixes each job group with "Job group for statement N:". The statement +# number is per application, so it cannot identify a notebook; the code can. +_JOB_GROUP_PREFIX = re.compile(r"^\s*Job group for statement \d+:\s*") +# Enough of a cell to be specific, short enough to survive Spark truncating +# long job groups. +_CELL_MATCH_CHARS = 40 + + +def _normalize_code(text: str) -> str: + return re.sub(r"\s+", " ", text).strip() + + +def _cell_code(description: Optional[str]) -> Optional[str]: + if not description: + return None + code = _normalize_code(_JOB_GROUP_PREFIX.sub("", description, count=1)) + return code or None + + @dataclass class _JobLineage: """Resolved upstream datasets, plus column renames when the code names them.""" @@ -133,6 +165,7 @@ def __init__( known_table_urns: Set[str], normalize_name: Callable[[str], str], owners_fn: OwnersFn, + table_columns: Optional[Dict[str, List[str]]] = None, ) -> None: self._platform_instance = platform_instance self._env = env @@ -143,6 +176,7 @@ def __init__( self._report = report self._client = client self._known_table_urns = known_table_urns + self._table_columns = table_columns or {} # Same name normalization the source applied when registering ingested # tables, so Spark-plan URNs match the known set regardless of case. self._normalize_name = normalize_name @@ -297,6 +331,40 @@ def _job_id(self, output: SparkTableRef) -> str: ) return f"{output.item_id}.{schema}.{table}" + def _add_copied_columns( + self, + output_urn: str, + copied: Tuple[SparkTableRef, FrozenSet[str]], + columns: Dict[str, Set[Tuple[str, str]]], + ) -> None: + """Pair the columns a notebook copies unchanged, by name. + + The code only says the table was copied, so the names come from the + schemas ingested for both tables. Columns the code already traced + (renamed or computed) keep that lineage. + """ + source, dropped = copied + source_urn = source.to_urn( + self._env, self._platform_instance, self._normalize_name + ) + source_columns = self._table_columns.get(source_urn) + output_columns = self._table_columns.get(output_urn) + if not source_columns or not output_columns: + return + fold = ( + (lambda name: name) + if self._case_sensitive_columns + else (lambda name: name.casefold()) + ) + source_by_name = {fold(name): name for name in source_columns} + skipped = {fold(self._normalize_name(name)) for name in dropped} + traced = {fold(name) for name in columns} + for column in output_columns: + key = fold(column) + if key in skipped or key in traced or key not in source_by_name: + continue + columns[column] = {(source_urn, source_by_name[key])} + def _fine_grained( self, output_urn: str, columns: Dict[str, Set[Tuple[str, str]]] ) -> Optional[List[FineGrainedLineageClass]]: @@ -320,6 +388,31 @@ def _fine_grained( ) return entries or None + def _own_executions( + self, nb: PendingNotebook, executions: List[SparkSqlExecution] + ) -> List[SparkSqlExecution]: + """Keep the executions that ran this notebook's cells. + + Notebooks run in one Spark application (for example a pipeline run) share + a single SQL sequence, and lineage credits each write with the reads before + it. Without this filter, one notebook's write inherits every other + notebook's reads and writes. Each execution's job group holds the code of + the cell that ran it, so an execution is this notebook's when that code + appears in the notebook. Executions without a job group cannot be placed, + so they are kept as before. + """ + if not nb.content: + return executions + notebook_text = _normalize_code(nb.content) + own: List[SparkSqlExecution] = [] + for execution in executions: + code = _cell_code(execution.description) + if code is None or code[:_CELL_MATCH_CHARS] in notebook_text: + own.append(execution) + else: + self._report.report_notebook_spark_execution_skipped() + return own + def _spark_lineage(self, nb: PendingNotebook) -> Dict[SparkTableRef, _JobLineage]: """Resolve per-output-table lineage from the executed Spark plans. @@ -351,7 +444,7 @@ def _spark_lineage(self, nb: PendingNotebook) -> Dict[SparkTableRef, _JobLineage for session in sessions: self._report.report_notebook_spark_session_scanned() try: - plans = self._client.get_spark_sql_plans( + executions = self._client.get_spark_sql_executions( nb.workspace_id, nb.notebook_id, session.livy_id, @@ -366,7 +459,8 @@ def _spark_lineage(self, nb: PendingNotebook) -> Dict[SparkTableRef, _JobLineage log=False, ) continue - for output, inputs in extract_spark_lineage(plans).items(): + own = self._own_executions(nb, executions) + for output, inputs in extract_spark_lineage([e.plan for e in own]).items(): raw.setdefault(output, set()).update(inputs) # Plans credit every earlier read to the next write. The notebook @@ -375,6 +469,7 @@ def _spark_lineage(self, nb: PendingNotebook) -> Dict[SparkTableRef, _JobLineage code_columns: Dict[ SparkTableRef, Dict[str, Set[Tuple[SparkTableRef, str]]] ] = {} + code_copies: Dict[SparkTableRef, Tuple[SparkTableRef, FrozenSet[str]]] = {} if self._reconcile_code and nb.content and nb.language in (None, "python"): code: Optional[NotebookCodeAnalysis] = None try: @@ -408,6 +503,9 @@ def _spark_lineage(self, nb: PendingNotebook) -> Dict[SparkTableRef, _JobLineage code_columns = reconcile_column_lineage( code.columns, raw, self._normalize_name ) + code_copies = reconcile_passthrough( + code.passthrough, raw, self._normalize_name + ) known = self._known_table_urns # Case/space variants of one output table normalize to a single URN and @@ -433,6 +531,9 @@ def _spark_lineage(self, nb: PendingNotebook) -> Dict[SparkTableRef, _JobLineage self._env, self._platform_instance, self._normalize_name ) resolved.add((dataset_urn, self._normalize_name(column))) + copied = code_copies.get(output) + if copied is not None: + self._add_copied_columns(output_urn, copied, cols) lineage: Dict[SparkTableRef, _JobLineage] = {} for output_urn, (output, inputs, columns) in merged.items(): diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/report.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/report.py index 72de59594f28..fdba509095a9 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/report.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/report.py @@ -55,6 +55,7 @@ class FabricOneLakeSourceReport( notebooks_scanned: int = 0 notebook_runs_scanned: int = 0 notebook_spark_sessions_scanned: int = 0 + notebook_spark_executions_skipped: int = 0 notebook_spark_lineage_extracted: int = 0 notebook_code_lineage_extraction_failures: int = 0 entities_profiled: int = 0 @@ -167,6 +168,10 @@ def report_notebook_spark_session_scanned(self) -> None: """Increment Spark sessions inspected for plan-based lineage.""" self.notebook_spark_sessions_scanned += 1 + def report_notebook_spark_execution_skipped(self) -> None: + """Count a Spark SQL execution that ran another notebook's cell.""" + self.notebook_spark_executions_skipped += 1 + def report_notebook_spark_lineage_extracted(self) -> None: """Record a notebook that produced lineage from its Spark plans.""" self.notebook_spark_lineage_extracted += 1 diff --git a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/source.py b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/source.py index 6af67ec232ac..5df7f5a1121d 100644 --- a/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/source.py +++ b/metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/source.py @@ -309,6 +309,9 @@ def __init__(self, config: FabricOneLakeSourceConfig, ctx: PipelineContext): # notebooks deferred until every workspace is scanned, so cross-workspace # table references resolve against the full set. self._notebook_known_table_urns: set[str] = set() + # Column names per ingested table URN, as they appear in schema fields, + # so a notebook that copies a table can be given column lineage. + self._notebook_table_columns: dict[str, list[str]] = {} self._pending_notebooks: list[PendingNotebook] = [] self.report.sql_aggregator = self.aggregator.report @@ -354,6 +357,7 @@ def _register_notebook_table( item_id: str, schema_name: str, table_name: str, + columns: list[FabricColumn], ) -> None: # Record the GUID-based URN of every ingested table so a notebook's # Spark-plan lineage can validate its GUID-built URNs against the set and @@ -369,6 +373,10 @@ def _register_notebook_table( platform_instance=self.config.platform_instance, ) self._notebook_known_table_urns.add(urn) + if columns: + self._notebook_table_columns[urn] = [ + self._norm(col.name) for col in columns + ] def _owners( self, @@ -1099,6 +1107,7 @@ def _process_item_tables( item_id, schema_name, table.name, + columns, ) except Exception as e: @@ -1368,6 +1377,7 @@ def _emit_notebook_processes( report=self.report, client=self.client, known_table_urns=self._notebook_known_table_urns, + table_columns=self._notebook_table_columns, normalize_name=self._norm, owners_fn=self._owners, ) @@ -1635,6 +1645,7 @@ def _process_item_views( item_id, schema_name, view.name, + columns, ) def _create_view_dataset( diff --git a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py index 27da01469c1f..bf5c651c3a32 100644 --- a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py +++ b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py @@ -5,7 +5,10 @@ import pytest from datahub.emitter.mce_builder import make_schema_field_urn -from datahub.ingestion.source.fabric.common.models import FabricSparkSession +from datahub.ingestion.source.fabric.common.models import ( + FabricSparkSession, + SparkSqlExecution, +) from datahub.ingestion.source.fabric.onelake.notebook_code_lineage import ( CodeTable, NotebookCodeExtractionError, @@ -25,6 +28,11 @@ from datahub.metadata.schema_classes import DataJobInputOutputClass from datahub.sdk.datajob import DataJob + +def _executions(plans: list) -> list: + return [SparkSqlExecution(plan=plan) for plan in plans] + + WS = "11111111-1111-1111-1111-111111111111" LH = "22222222-2222-2222-2222-222222222222" NB = "33333333-3333-3333-3333-333333333333" @@ -254,16 +262,18 @@ def _emit_dim_user( client.list_notebook_spark_sessions.return_value = [ FabricSparkSession(livy_id="livy-1", application_id="app-1", item_id=NB) ] - client.get_spark_sql_plans.return_value = [ - _plan( - "Tables/gold/dim_user", - [ - "Tables/silver/orders/_delta_log/0.json", - "Tables/silver/customers/_delta_log/0.json", - "Tables/silver/products/_delta_log/0.json", - ], - ) - ] + client.get_spark_sql_executions.return_value = _executions( + [ + _plan( + "Tables/gold/dim_user", + [ + "Tables/silver/orders/_delta_log/0.json", + "Tables/silver/customers/_delta_log/0.json", + "Tables/silver/products/_delta_log/0.json", + ], + ) + ] + ) client.get_notebook_runs.return_value = [] emitter = NotebookProcessEmitter( platform_instance=None, @@ -616,12 +626,14 @@ def test_reconciled_job_carries_column_lineage() -> None: client.list_notebook_spark_sessions.return_value = [ FabricSparkSession(livy_id="livy-1", application_id="app-1", item_id=NB) ] - client.get_spark_sql_plans.return_value = [ - _plan( - "Tables/silver/silver_customers", - ["Tables/dbo/customers/_delta_log/0.json"], - ) - ] + client.get_spark_sql_executions.return_value = _executions( + [ + _plan( + "Tables/silver/silver_customers", + ["Tables/dbo/customers/_delta_log/0.json"], + ) + ] + ) client.get_notebook_runs.return_value = [] emitter = NotebookProcessEmitter( platform_instance=None, @@ -670,3 +682,164 @@ def test_reconciled_job_carries_column_lineage() -> None: (make_schema_field_urn(upstream, "NAME"),), ), } + + +# Paths come from a helper defined in a notebook pulled in with %run, so the +# analyzer cannot read its body. The last two arguments name the table. +_HELPER_PATH_WRITE = """ +%run common_helpers + +workspace_id = env.getVariable('workspace_id') +lakehouse_id = env.getVariable('silver_lakehouse_id') +target_schema = 'dbo' +target_table = 'orders' +source_path = build_path(workspace_id, lakehouse_id, 'raw', 'orders_feed') +target_path = build_path(workspace_id, lakehouse_id, target_schema, target_table) +df = spark.read.format('delta').load(source_path) +df.write.format('delta').mode('overwrite').save(target_path) +""" + + +def test_helper_built_path_resolves_to_schema_and_table() -> None: + analysis = analyze_notebook_code(_HELPER_PATH_WRITE) + assert analysis is not None + assert analysis.tables == { + CodeTable(table="orders", schema="dbo"): { + CodeTable(table="orders_feed", schema="raw") + } + } + + +def test_reconcile_drops_outputs_the_helper_path_does_not_write() -> None: + # Spark plans from a shared session also report another notebook's write to + # dim.orders. This notebook writes only dbo.orders, so that edge is dropped. + analysis = analyze_notebook_code(_HELPER_PATH_WRITE) + assert analysis is not None + execution = { + SparkTableRef(workspace_id=WS, item_id=LH, table="orders", schema="dbo"): { + SparkTableRef( + workspace_id=WS, item_id=LH, table="orders_feed", schema="raw" + ) + }, + SparkTableRef(workspace_id=WS, item_id=LH, table="orders", schema="dim"): { + SparkTableRef(workspace_id=WS, item_id=LH, table="orders", schema="dbo") + }, + } + reconciled = reconcile_spark_lineage(analysis.tables, execution, str.lower) + assert list(reconciled) == [ + SparkTableRef(workspace_id=WS, item_id=LH, table="orders", schema="dbo") + ] + + +_COPY = """ +src = spark.read.format('delta').load('Tables/silver/orders') +src.write.format('delta').mode('overwrite').save('Tables/gold/orders_copy') +""" +_COPY_DROPPING = """ +src = spark.read.format('delta').load('Tables/silver/orders') +src.drop('legacy').write.format('delta').mode('overwrite').save('Tables/gold/orders_copy') +""" +_COPY_SELECTING = """ +src = spark.read.format('delta').load('Tables/silver/orders') +src.select('id').write.format('delta').mode('overwrite').save('Tables/gold/orders_copy') +""" +_SILVER_ORDERS = CodeTable(table="orders", schema="silver") +_GOLD_COPY = CodeTable(table="orders_copy", schema="gold") + + +def test_unprojected_write_is_recorded_as_a_copy() -> None: + analysis = analyze_notebook_code(_COPY) + assert analysis is not None + copied = analysis.passthrough[_GOLD_COPY] + assert copied.table == _SILVER_ORDERS + assert not copied.dropped + + +def test_dropped_columns_are_not_part_of_the_copy() -> None: + analysis = analyze_notebook_code(_COPY_DROPPING) + assert analysis is not None + assert analysis.passthrough[_GOLD_COPY].dropped == {"legacy"} + + +def test_select_is_not_a_copy() -> None: + analysis = analyze_notebook_code(_COPY_SELECTING) + assert analysis is not None + assert _GOLD_COPY not in analysis.passthrough + + +def _emit_copy( + content: str, table_columns: dict[str, list[str]] +) -> tuple[str, str, list]: + source = SparkTableRef(workspace_id=WS, item_id=LH, table="orders", schema="silver") + target = SparkTableRef( + workspace_id=WS, item_id=LH, table="orders_copy", schema="gold" + ) + source_urn, target_urn = source.to_urn("PROD", None), target.to_urn("PROD", None) + client = MagicMock() + client.list_notebook_spark_sessions.return_value = [ + FabricSparkSession(livy_id="livy-1", application_id="app-1", item_id=NB) + ] + client.get_spark_sql_executions.return_value = _executions( + [_plan("Tables/gold/orders_copy", ["Tables/silver/orders/_delta_log/0.json"])] + ) + client.get_notebook_runs.return_value = [] + emitter = NotebookProcessEmitter( + platform_instance=None, + env="PROD", + execution_history_days=30, + report=FabricOneLakeSourceReport(), + client=client, + known_table_urns={source_urn, target_urn}, + normalize_name=lambda name: name, + owners_fn=lambda _upn: None, + reconcile_code=True, + table_columns={ + source_urn: table_columns["source"], + target_urn: table_columns["target"], + }, + ) + emitted = list( + emitter.emit( + [ + PendingNotebook( + workspace_id=WS, + workspace_name="analytics", + notebook_id=NB, + display_name="copy", + description=None, + owner_user_principal_name=None, + content=content, + language="python", + ) + ] + ) + ) + io = next(job for job in emitted if isinstance(job, DataJob))._get_aspect( + DataJobInputOutputClass + ) + assert io is not None + return source_urn, target_urn, io.fineGrainedLineages or [] + + +def test_copied_table_gets_same_name_column_lineage() -> None: + source_urn, target_urn, fine_grained = _emit_copy( + _COPY_DROPPING, + {"source": ["id", "Name", "legacy"], "target": ["id", "name", "load_ts"]}, + ) + # Names match without regard to case, the dropped column is left out, and a + # target column the source lacks stays unmapped. + assert { + (tuple(entry.upstreams or []), tuple(entry.downstreams or [])) + for entry in fine_grained + } == { + ( + (make_schema_field_urn(source_urn, column),), + (make_schema_field_urn(target_urn, target),), + ) + for column, target in (("id", "id"), ("Name", "name")) + } + + +def test_copy_without_ingested_schemas_has_no_column_lineage() -> None: + _, _, fine_grained = _emit_copy(_COPY, {"source": ["id"], "target": []}) + assert fine_grained == [] diff --git a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_jobs.py b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_jobs.py index 708157a50d8f..b6b64a547448 100644 --- a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_jobs.py +++ b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_jobs.py @@ -9,6 +9,7 @@ FabricJobInstance, FabricSparkSession, ItemJobStatus, + SparkSqlExecution, ) from datahub.ingestion.source.fabric.onelake.notebook_jobs import ( NotebookProcessEmitter, @@ -25,6 +26,11 @@ from datahub.sdk.dataflow import DataFlow from datahub.sdk.datajob import DataJob + +def _executions(plans: list) -> list: + return [SparkSqlExecution(plan=plan) for plan in plans] + + WS = "11111111-1111-1111-1111-111111111111" LH = "22222222-2222-2222-2222-222222222222" NB = "33333333-3333-3333-3333-333333333333" @@ -65,7 +71,7 @@ def _emit() -> list: client.list_notebook_spark_sessions.return_value = [ FabricSparkSession(livy_id="livy-1", application_id="app-1", item_id=NB) ] - client.get_spark_sql_plans.return_value = [_PLAN_MID, _PLAN_FINAL] + client.get_spark_sql_executions.return_value = _executions([_PLAN_MID, _PLAN_FINAL]) client.get_notebook_runs.return_value = [ FabricJobInstance( id="run-1", @@ -143,7 +149,9 @@ def _emit_case_variants() -> list: client.list_notebook_spark_sessions.return_value = [ FabricSparkSession(livy_id="livy-1", application_id="app-1", item_id=NB) ] - client.get_spark_sql_plans.return_value = [_PLAN_UPPER, _PLAN_LOWER] + client.get_spark_sql_executions.return_value = _executions( + [_PLAN_UPPER, _PLAN_LOWER] + ) client.get_notebook_runs.return_value = [] emitter = NotebookProcessEmitter( @@ -241,7 +249,7 @@ def _plans_client() -> MagicMock: client.list_notebook_spark_sessions.return_value = [ FabricSparkSession(livy_id="livy-1", application_id="app-1", item_id=NB) ] - client.get_spark_sql_plans.return_value = [_PLAN_MID, _PLAN_FINAL] + client.get_spark_sql_executions.return_value = _executions([_PLAN_MID, _PLAN_FINAL]) client.get_notebook_runs.return_value = [] return client @@ -302,14 +310,16 @@ def test_output_not_in_catalog_produces_no_job() -> None: client.list_notebook_spark_sessions.return_value = [ FabricSparkSession(livy_id="livy-1", application_id="app-1", item_id=NB) ] - client.get_spark_sql_plans.return_value = [ - f"""== Physical Plan == + client.get_spark_sql_executions.return_value = _executions( + [ + f"""== Physical Plan == (1) SaveIntoDataSourceCommand Arguments: [path={_onelake("Tables/gold/orphan")}], Overwrite (2) Scan json Location: InMemoryFileIndex[{_onelake("Tables/gold/gold_mid/_delta_log/0.json")}] """ - ] + ] + ) client.get_notebook_runs.return_value = [] emitted, _report = _emit_with(client) @@ -337,7 +347,7 @@ def test_schemaless_output_job_id_matches_the_dbo_dataset_urn() -> None: client.list_notebook_spark_sessions.return_value = [ FabricSparkSession(livy_id="livy-1", application_id="app-1", item_id=NB) ] - client.get_spark_sql_plans.return_value = [_PLAN_SCHEMALESS] + client.get_spark_sql_executions.return_value = _executions([_PLAN_SCHEMALESS]) client.get_notebook_runs.return_value = [] emitted, _report = _emit_with(client, known=known) @@ -411,7 +421,7 @@ def test_runs_fall_back_to_the_dataflow_when_no_lineage_resolves() -> None: client.list_notebook_spark_sessions.return_value = [ FabricSparkSession(livy_id="livy-1", application_id="app-1", item_id=NB) ] - client.get_spark_sql_plans.side_effect = RuntimeError("history expired") + client.get_spark_sql_executions.side_effect = RuntimeError("history expired") client.get_notebook_runs.return_value = [ FabricJobInstance( id="run-1", @@ -435,3 +445,55 @@ def test_runs_fall_back_to_the_dataflow_when_no_lineage_resolves() -> None: and isinstance(wu.metadata.aspect, DataProcessInstanceRelationshipsClass) } assert templates == {str(flow.urn)} + + +_FINAL_CELL = "gold_final_df = spark.read.format('delta').load(gold_mid_path)" + + +def test_other_notebooks_executions_in_a_shared_session_are_dropped() -> None: + # Both notebooks ran in one Spark application. The first execution is another + # notebook's cell, so its read of silver_a must not reach gold_final's write. + client = MagicMock() + client.list_notebook_spark_sessions.return_value = [ + FabricSparkSession(livy_id="livy-1", application_id="app-1", item_id=NB) + ] + client.get_spark_sql_executions.return_value = [ + SparkSqlExecution( + plan=_PLAN_MID, + description="Job group for statement 1: silver_only = load_silver()", + ), + SparkSqlExecution( + plan=_PLAN_FINAL, + description=f"Job group for statement 2: {_FINAL_CELL}", + ), + ] + client.get_notebook_runs.return_value = [] + + emitted, report = _emit_with(client, content=_FINAL_CELL + "\n") + + jobs = {dj.urn.job_id: dj for dj in emitted if isinstance(dj, DataJob)} + assert set(jobs) == {f"{LH}.gold.gold_final"} + io = jobs[f"{LH}.gold.gold_final"]._get_aspect(DataJobInputOutputClass) + assert io is not None + assert all("silver_a" not in urn for urn in io.inputDatasets) + assert report.notebook_spark_executions_skipped == 1 + + +def test_executions_without_a_cell_description_are_kept() -> None: + client = MagicMock() + client.list_notebook_spark_sessions.return_value = [ + FabricSparkSession(livy_id="livy-1", application_id="app-1", item_id=NB) + ] + client.get_spark_sql_executions.return_value = [ + SparkSqlExecution(plan=_PLAN_MID), + SparkSqlExecution(plan=_PLAN_FINAL), + ] + client.get_notebook_runs.return_value = [] + + emitted, report = _emit_with(client, content=_FINAL_CELL + "\n") + + assert {dj.urn.job_id for dj in emitted if isinstance(dj, DataJob)} == { + f"{LH}.gold.gold_mid", + f"{LH}.gold.gold_final", + } + assert report.notebook_spark_executions_skipped == 0 diff --git a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_spark_lineage.py b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_spark_lineage.py index 02558e9fd578..003629df6008 100644 --- a/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_spark_lineage.py +++ b/metadata-ingestion/tests/unit/fabric_onelake/test_notebook_spark_lineage.py @@ -3,6 +3,7 @@ from datetime import datetime, timezone from unittest.mock import MagicMock +from datahub.ingestion.source.fabric.common.models import SparkSqlExecution from datahub.ingestion.source.fabric.common.urn_generator import make_onelake_urn from datahub.ingestion.source.fabric.onelake.client import ( _SPARK_SQL_PAGE_SIZE, @@ -282,6 +283,29 @@ def test_get_spark_sql_plans_extracts_plan_descriptions() -> None: assert plans == ["== Physical Plan ==\nA", "== Physical Plan ==\nB"] +def test_get_spark_sql_executions_keeps_the_cell_description() -> None: + client = OneLakeClient.__new__(OneLakeClient) + client.get = MagicMock( # type: ignore[method-assign] + return_value=_response( + [ + { + "id": 0, + "planDescription": "A", + "description": "Job group for statement 1: x = 1", + }, + {"id": 1, "planDescription": "B"}, + ] + ) + ) + + executions = client.get_spark_sql_executions("ws-1", "nb-1", "livy-1", "app-1") + + assert executions == [ + SparkSqlExecution(plan="A", description="Job group for statement 1: x = 1"), + SparkSqlExecution(plan="B", description=None), + ] + + def test_get_spark_sql_plans_orders_by_execution_id() -> None: # The SQL API returns executions newest-first; order-aware lineage needs them # chronological, so the client must sort by execution id ascending. From c5db198ad5ca605326f565140fee36505e7c8da5 Mon Sep 17 00:00:00 2001 From: Steve Baldwin Date: Fri, 27 Nov 2026 12:28:59 +0000 Subject: [PATCH 12/12] chore(ingestion): regenerate constraints.txt for uv 0.13.10 marker format uv 0.13.10 writes environment markers in a simplified form, so the checkLockFile comparison failed on hf-xet, ibm-db, ibm-db-sa and win-precise-time. Versions are unchanged. Co-Authored-By: Claude Opus 5.5 --- metadata-ingestion/constraints.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/metadata-ingestion/constraints.txt b/metadata-ingestion/constraints.txt index 1f73b63accfc..b5247f5d4ef4 100644 --- a/metadata-ingestion/constraints.txt +++ b/metadata-ingestion/constraints.txt @@ -562,7 +562,7 @@ hdbcli==2.27.24 ; python_full_version >= '3.11' and python_full_version < '3.14' # via # acryl-datahub # sqlalchemy-hana -hf-xet==1.6.0 ; (python_full_version >= '3.11' and python_full_version < '3.14' and platform_machine == 'AMD64') or (python_full_version >= '3.11' and python_full_version < '3.14' and platform_machine == 'aarch64') or (python_full_version >= '3.11' and python_full_version < '3.14' and platform_machine == 'amd64') or (python_full_version >= '3.11' and python_full_version < '3.14' and platform_machine == 'arm64') or (python_full_version >= '3.11' and python_full_version < '3.14' and platform_machine == 'x86_64') +hf-xet==1.6.0 ; python_full_version >= '3.11' and python_full_version < '3.14' and (platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64') # via huggingface-hub html5lib==1.1 ; python_full_version >= '3.11' and python_full_version < '3.14' # via unstructured @@ -598,9 +598,9 @@ humanize==4.15.0 ; python_full_version >= '3.11' and python_full_version < '3.14 # via dlt hypothesis==6.152.7 ; python_full_version >= '3.11' and python_full_version < '3.14' # via acryl-datahub -ibm-db==3.2.8 ; (python_full_version >= '3.11' and python_full_version < '3.14' and platform_machine == 'x86_64') or (python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform == 'darwin') +ibm-db==3.2.8 ; python_full_version >= '3.11' and python_full_version < '3.14' and (platform_machine == 'x86_64' or sys_platform == 'darwin') # via ibm-db-sa -ibm-db-sa==0.4.4 ; (python_full_version >= '3.11' and python_full_version < '3.14' and platform_machine == 'x86_64') or (python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform == 'darwin') +ibm-db-sa==0.4.4 ; python_full_version >= '3.11' and python_full_version < '3.14' and (platform_machine == 'x86_64' or sys_platform == 'darwin') # via acryl-datahub id==1.5.0 ; python_full_version >= '3.11' and python_full_version < '3.14' # via twine @@ -1733,7 +1733,7 @@ werkzeug==3.1.6 ; python_full_version >= '3.11' and python_full_version < '3.14' # flask # moto # pytest-httpserver -win-precise-time==1.4.2 ; (python_full_version >= '3.11' and python_full_version < '3.13' and os_name == 'nt' and platform_machine != 'arm64') or (python_full_version >= '3.11' and python_full_version < '3.13' and os_name == 'nt' and sys_platform != 'darwin') +win-precise-time==1.4.2 ; python_full_version >= '3.11' and python_full_version < '3.13' and os_name == 'nt' # via dlt win32-setctime==1.2.0 ; python_full_version >= '3.11' and python_full_version < '3.14' and sys_platform == 'win32' # via loguru