Skip to content

feat(ingestion/fabric): emit notebook column lineage from code renames - #20720

Open
steve751 wants to merge 13 commits into
feat/fabric-notebook-view-definitionfrom
feat/fabric-notebook-column-lineage
Open

steve751 wants to merge 13 commits into
feat/fabric-notebook-view-definitionfrom
feat/fabric-notebook-column-lineage

Conversation

@steve751

@steve751 steve751 commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • When notebook_execution.reconcile_code is on, Python notebook column renames are emitted as column-level lineage on the Spark job that writes each table.
  • Covers col(src).alias(dst), {source: target} mapping dicts, alias.*, df["column"], and select lists built before they are applied (select(*select_exprs)). Literal columns are omitted. An edge is kept only when both tables were resolved by the Spark plan and ingested in the same run.
  • Column names use the same normalization as schema fields, so a code name such as person_PersonParty matches person_personparty when convert_urns_to_lowercase is on.

Column lineage is stored on the job's dataJobInputOutput.fineGrainedLineages, not on the dataset upstreamLineage aspect.

Test plan

  • pytest metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py metadata-ingestion/tests/unit/fabric_onelake/test_notebook_jobs.py
  • Ingest a notebook with include_notebooks: true, notebook_execution.enabled: true, and reconcile_code: true
  • On the Spark job, confirm inputOutput.fineGrainedLineages links each output field to its upstream field
  • Confirm reconcile_code: false still emits table lineage and no column edges
  • With convert_urns_to_lowercase: true, confirm field paths match the lowercased schema fields

steve751 and others added 2 commits October 27, 2026 08:13
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 <cursoragent@cursor.com>
@github-actions github-actions Bot added the ingestion PR or Issue related to the ingestion of metadata label Oct 27, 2026
@codecov

codecov Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

❌ 7 Tests Failed:

Tests completed Failed Passed Skipped
23805 7 23798 84
View the top 3 failed test(s) by shortest run time
tests.integration.grafana.test_grafana::test_grafana_ingest
Stack Traces | 0.548s run time
docker_compose_runner = <function docker_compose_runner.<locals>.run at 0x7f92ab5ce160>
test_resources_dir = PosixPath('.../tests/integration/grafana')

    @pytest.fixture(scope="module")
    def loaded_grafana(docker_compose_runner, test_resources_dir):
        with docker_compose_runner(
            test_resources_dir / "docker-compose.yml", "grafana"
        ) as docker_services:
            wait_for_port(docker_services, "postgres", 5432, timeout=90)
    
            def check_prometheus_ready():
                try:
                    prometheus_port = docker_services.port_for("prometheus", 9090)
                    response = requests.get(
                        f"http://localhost:{prometheus_port}/-/ready", timeout=5
                    )
                    return response.status_code == 200
                except (requests.exceptions.RequestException, Exception):
                    return False
    
            wait_for_port(
                docker_services,
                "prometheus",
                9090,
                timeout=90,
                checker=check_prometheus_ready,
            )
>           wait_for_port(docker_services, "grafana", 3000, timeout=180)

.../integration/grafana/test_grafana.py:161: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
.../datahub/testing/docker_utils.py:65: in wait_for_port
    docker_services.wait_until_responsive(
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = Services(_docker_compose=DockerComposeExecutor(_compose_command='docker compose --parallel -1', _compose_files=[PosixP...ion/grafana/docker-compose.yml')], _compose_project_name='pytest5630-grafana'), _services={'prometheus': {9090: 9090}})
check = <function wait_for_port.<locals>.<lambda> at 0x7f92ab5cee80>
timeout = 180, pause = 0.5, clock = <built-in function perf_counter>

    def wait_until_responsive(
        self,
        check: Any,
        timeout: float,
        pause: float,
        clock: Any = timeit.default_timer,
    ) -> None:
        """Wait until a service is responsive."""
    
        ref = clock()
        now = ref
        while (now - ref) < timeout:
            if check():
                return
            time.sleep(pause)
            now = clock()
    
>       raise Exception("Timeout reached while waiting on service!")
E       Exception: Timeout reached while waiting on service!

venv/lib/python3.11.../site-packages/pytest_docker/plugin.py:120: Exception
tests.integration.ldap.test_ldap::test_ldap_memberof_ingest
Stack Traces | 0.993s run time
docker_compose_runner = <function docker_compose_runner.<locals>.run at 0x7f80a1685c60>
pytestconfig = <_pytest.config.Config object at 0x7f814bec4590>
tmp_path = PosixPath('.../pytest-of-runner/pytest-0/test_ldap_memberof_ingest0')
mock_time = None

    @pytest.mark.integration
    def test_ldap_memberof_ingest(docker_compose_runner, pytestconfig, tmp_path, mock_time):
        test_resources_dir = pytestconfig.rootpath / "tests/integration/ldap"
    
>       with docker_compose_runner(
            test_resources_dir / "docker-compose.yml", "ldap"
        ) as docker_services:

.../integration/ldap/test_ldap.py:62: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
.../hostedtoolcache/Python/3.11.18.../x64/lib/python3.11/contextlib.py:137: in __enter__
    return next(self.gen)
           ^^^^^^^^^^^^^^
.../datahub/testing/docker_utils.py:255: in run
    compose.execute(command)
venv/lib/python3.11....../site-packages/pytest_docker/plugin.py:140: in execute
    return execute(command, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

command = 'docker compose --parallel -1 -f ".../integration/ldap/docker-compose.yml" -p "pytest5621-ldap" up --build --wait'
success_codes = (0,), ignore_stderr = False

    def execute(command: str, success_codes: Iterable[int] = (0,), ignore_stderr: bool = False) -> Union[bytes, Any]:
        """Run a shell command."""
        try:
            stderr_pipe = subprocess.DEVNULL if ignore_stderr else subprocess.STDOUT
            output = subprocess.check_output(command, stderr=stderr_pipe, shell=True)
            status = 0
        except subprocess.CalledProcessError as error:
            output = error.output or b""
            status = error.returncode
            command = error.cmd
    
        if status not in success_codes:
>           raise Exception(
                'Command {} returned {}: """{}""".'.format(command, status, output.decode("utf-8"))
            )
E           Exception: Command docker compose --parallel -1 -f ".../integration/ldap/docker-compose.yml" -p "pytest5621-ldap" up --build --wait returned 1: """time="2026-11-27T12:38:15Z" level=warning msg=".../integration/ldap/docker-compose.yml: the attribute `version` is obsolete, it will be ignored, please remove it to avoid potential confusion"
E            Network pytest5621-ldap_default  Creating
E            Network pytest5621-ldap_default  Created
E            Container test-openldap  Creating
E            Container test-openldap  Created
E            Container test-openldap  Starting
E            Container test-openldap  Started
E            Container test-openldap  Waiting
E           container test-openldap exited (1)
E           """.

venv/lib/python3.11....../site-packages/pytest_docker/plugin.py:37: Exception
tests.integration.ldap.test_ldap::test_ldap_ingest_with_email_as_username
Stack Traces | 1.08s run time
docker_compose_runner = <function docker_compose_runner.<locals>.run at 0x7f80a1685c60>
pytestconfig = <_pytest.config.Config object at 0x7f814bec4590>
tmp_path = PosixPath('.../pytest-of-runner/pytest-0/test_ldap_ingest_with_email_as0')
mock_time = None

    @pytest.mark.integration
    def test_ldap_ingest_with_email_as_username(
        docker_compose_runner, pytestconfig, tmp_path, mock_time
    ):
        test_resources_dir = pytestconfig.rootpath / "tests/integration/ldap"
    
>       with docker_compose_runner(
            test_resources_dir / "docker-compose.yml", "ldap"
        ) as docker_services:

.../integration/ldap/test_ldap.py:113: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
.../hostedtoolcache/Python/3.11.18.../x64/lib/python3.11/contextlib.py:137: in __enter__
    return next(self.gen)
           ^^^^^^^^^^^^^^
.../datahub/testing/docker_utils.py:255: in run
    compose.execute(command)
venv/lib/python3.11....../site-packages/pytest_docker/plugin.py:140: in execute
    return execute(command, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

command = 'docker compose --parallel -1 -f ".../integration/ldap/docker-compose.yml" -p "pytest5621-ldap" up --build --wait'
success_codes = (0,), ignore_stderr = False

    def execute(command: str, success_codes: Iterable[int] = (0,), ignore_stderr: bool = False) -> Union[bytes, Any]:
        """Run a shell command."""
        try:
            stderr_pipe = subprocess.DEVNULL if ignore_stderr else subprocess.STDOUT
            output = subprocess.check_output(command, stderr=stderr_pipe, shell=True)
            status = 0
        except subprocess.CalledProcessError as error:
            output = error.output or b""
            status = error.returncode
            command = error.cmd
    
        if status not in success_codes:
>           raise Exception(
                'Command {} returned {}: """{}""".'.format(command, status, output.decode("utf-8"))
            )
E           Exception: Command docker compose --parallel -1 -f ".../integration/ldap/docker-compose.yml" -p "pytest5621-ldap" up --build --wait returned 1: """time="2026-11-27T12:38:16Z" level=warning msg=".../integration/ldap/docker-compose.yml: the attribute `version` is obsolete, it will be ignored, please remove it to avoid potential confusion"
E            Network pytest5621-ldap_default  Creating
E            Network pytest5621-ldap_default  Created
E            Container test-openldap  Creating
E            Container test-openldap  Created
E            Container test-openldap  Starting
E            Container test-openldap  Started
E            Container test-openldap  Waiting
E           container test-openldap exited (1)
E           """.

venv/lib/python3.11....../site-packages/pytest_docker/plugin.py:37: Exception
tests.integration.ldap.test_ldap_stateful::test_ldap_stateful
Stack Traces | 2.75s run time
docker_compose_runner = <function docker_compose_runner.<locals>.run at 0x7f80a0fab7e0>
pytestconfig = <_pytest.config.Config object at 0x7f814bec4590>
tmp_path = PosixPath('.../pytest-of-runner/pytest-0/test_ldap_stateful0')
mock_time = None
mock_datahub_graph = <MagicMock spec='DataHubGraph' id='140190427894416'>

    @time_machine.travel(FROZEN_TIME, tick=False)
    @pytest.mark.integration
    def test_ldap_stateful(
        docker_compose_runner, pytestconfig, tmp_path, mock_time, mock_datahub_graph
    ):
        golden_file_name: str = "ldap_mces_golden_stateful.json"
        output_file_name: str = "ldap_mces_stateful.json"
    
        golden_file_deleted_name: str = "ldap_mces_golden_deleted_stateful.json"
        output_file_deleted_name: str = "ldap_mces_deleted_stateful.json"
    
        golden_file_group: str = "ldap_mces_golden_group_stateful.json"
        output_file_group: str = "ldap_mces_group_stateful.json"
    
        golden_file_delete_group: str = "ldap_mces_golden_deleted_group_stateful.json"
        output_file_delete_group: str = "ldap_mces_deleted_group_stateful.json"
    
        filter1: str = "(|(cn=Bart Simpson)(cn=Homer Simpson))"
        filter2: str = "(|(cn=Bart Simpson))"
        filter3: str = "(&(objectClass=top)(|(cn=HR Department)(cn=Finance Department)))"
        filter4: str = "(&(objectClass=top)(|(cn=HR Department)))"
    
>       pipeline_run1 = ldap_ingest_common(
            docker_compose_runner,
            pytestconfig,
            tmp_path,
            golden_file_name,
            output_file_name,
            filter1,
            mock_datahub_graph,
        )

.../integration/ldap/test_ldap_stateful.py:114: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
.../integration/ldap/test_ldap_stateful.py:32: in ldap_ingest_common
    with docker_compose_runner(
.../hostedtoolcache/Python/3.11.18.../x64/lib/python3.11/contextlib.py:137: in __enter__
    return next(self.gen)
           ^^^^^^^^^^^^^^
.../datahub/testing/docker_utils.py:255: in run
    compose.execute(command)
venv/lib/python3.11....../site-packages/pytest_docker/plugin.py:140: in execute
    return execute(command, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

command = 'docker compose --parallel -1 -f ".../integration/ldap/docker-compose.yml" -p "pytest5621-ldap" up --build --wait'
success_codes = (0,), ignore_stderr = False

    def execute(command: str, success_codes: Iterable[int] = (0,), ignore_stderr: bool = False) -> Union[bytes, Any]:
        """Run a shell command."""
        try:
            stderr_pipe = subprocess.DEVNULL if ignore_stderr else subprocess.STDOUT
            output = subprocess.check_output(command, stderr=stderr_pipe, shell=True)
            status = 0
        except subprocess.CalledProcessError as error:
            output = error.output or b""
            status = error.returncode
            command = error.cmd
    
        if status not in success_codes:
>           raise Exception(
                'Command {} returned {}: """{}""".'.format(command, status, output.decode("utf-8"))
            )
E           Exception: Command docker compose --parallel -1 -f ".../integration/ldap/docker-compose.yml" -p "pytest5621-ldap" up --build --wait returned 1: """time="2026-11-27T12:38:17Z" level=warning msg=".../integration/ldap/docker-compose.yml: the attribute `version` is obsolete, it will be ignored, please remove it to avoid potential confusion"
E            openldap Pulling 
E            e254ced0d9d1 Pulling fs layer 
E            ff19393aeaeb Pulling fs layer 
E            5eab64f96e79 Pulling fs layer 
E            dd3d44a45162 Pulling fs layer 
E            9ba5236abc11 Pulling fs layer 
E            4d6d087a846e Pulling fs layer 
E            33d5df67cfc0 Pulling fs layer 
E            adcf0b927145 Pulling fs layer 
E            adcf0b927145 Download complete 
E            ff19393aeaeb Downloading [==========================>                        ]  2.097MB/3.946MB
E            e254ced0d9d1 Download complete 
E            5eab64f96e79 Download complete 
E            dd3d44a45162 Download complete 
E            9ba5236abc11 Downloading [=========================>                         ]  2.097MB/4.18MB
E            4d6d087a846e Download complete 
E            33d5df67cfc0 Download complete 
E            ff19393aeaeb Download complete 
E            9ba5236abc11 Download complete 
E            ff19393aeaeb Extracting 1 s
E            ff19393aeaeb Extracting 1 s
E            dd3d44a45162 Extracting 1 s
E            ff19393aeaeb Pull complete 
E            dd3d44a45162 Pull complete 
E            9ba5236abc11 Extracting 1 s
E            9ba5236abc11 Extracting 1 s
E            9ba5236abc11 Extracting 1 s
E            9ba5236abc11 Extracting 1 s
E            9ba5236abc11 Extracting 1 s
E            5eab64f96e79 Pull complete 
E            33d5df67cfc0 Extracting 1 s
E            9ba5236abc11 Pull complete 
E            33d5df67cfc0 Extracting 1 s
E            adcf0b927145 Extracting 1 s
E            4d6d087a846e Pull complete 
E            33d5df67cfc0 Pull complete 
E            adcf0b927145 Pull complete 
E            e254ced0d9d1 Pull complete 
E            openldap Pulled 
E            Network pytest5621-ldap_default  Creating
E            Network pytest5621-ldap_default  Created
E            Container test-openldap  Creating
E            Container test-openldap  Created
E            Container test-openldap  Starting
E            Container test-openldap  Started
E            Container test-openldap  Waiting
E           container test-openldap exited (1)
E           """.

venv/lib/python3.11....../site-packages/pytest_docker/plugin.py:37: Exception
tests.integration.ldap.test_ldap::test_ldap_ingest
Stack Traces | 2.78s run time
docker_compose_runner = <function docker_compose_runner.<locals>.run at 0x7f80a1685c60>
pytestconfig = <_pytest.config.Config object at 0x7f814bec4590>
tmp_path = PosixPath('.../pytest-of-runner/pytest-0/test_ldap_ingest0')
mock_time = None

    @pytest.mark.integration
    def test_ldap_ingest(docker_compose_runner, pytestconfig, tmp_path, mock_time):
        test_resources_dir = pytestconfig.rootpath / "tests/integration/ldap"
    
>       with docker_compose_runner(
            test_resources_dir / "docker-compose.yml", "ldap"
        ) as docker_services:

.../integration/ldap/test_ldap.py:14: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
.../hostedtoolcache/Python/3.11.18.../x64/lib/python3.11/contextlib.py:137: in __enter__
    return next(self.gen)
           ^^^^^^^^^^^^^^
.../datahub/testing/docker_utils.py:255: in run
    compose.execute(command)
venv/lib/python3.11....../site-packages/pytest_docker/plugin.py:140: in execute
    return execute(command, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

command = 'docker compose --parallel -1 -f ".../integration/ldap/docker-compose.yml" -p "pytest5621-ldap" up --build --wait'
success_codes = (0,), ignore_stderr = False

    def execute(command: str, success_codes: Iterable[int] = (0,), ignore_stderr: bool = False) -> Union[bytes, Any]:
        """Run a shell command."""
        try:
            stderr_pipe = subprocess.DEVNULL if ignore_stderr else subprocess.STDOUT
            output = subprocess.check_output(command, stderr=stderr_pipe, shell=True)
            status = 0
        except subprocess.CalledProcessError as error:
            output = error.output or b""
            status = error.returncode
            command = error.cmd
    
        if status not in success_codes:
>           raise Exception(
                'Command {} returned {}: """{}""".'.format(command, status, output.decode("utf-8"))
            )
E           Exception: Command docker compose --parallel -1 -f ".../integration/ldap/docker-compose.yml" -p "pytest5621-ldap" up --build --wait returned 1: """time="2026-11-27T12:38:11Z" level=warning msg=".../integration/ldap/docker-compose.yml: the attribute `version` is obsolete, it will be ignored, please remove it to avoid potential confusion"
E            openldap Pulling 
E            5eab64f96e79 Pulling fs layer 
E            ff19393aeaeb Pulling fs layer 
E            dd3d44a45162 Pulling fs layer 
E            9ba5236abc11 Pulling fs layer 
E            4d6d087a846e Pulling fs layer 
E            33d5df67cfc0 Pulling fs layer 
E            adcf0b927145 Pulling fs layer 
E            e254ced0d9d1 Pulling fs layer 
E            ff19393aeaeb Download complete 
E            dd3d44a45162 Download complete 
E            9ba5236abc11 Downloading [===============================>                   ]  2.662MB/4.18MB
E            4d6d087a846e Download complete 
E            adcf0b927145 Download complete 
E            e254ced0d9d1 Download complete 
E            5eab64f96e79 Download complete 
E            ff19393aeaeb Extracting 1 s
E            9ba5236abc11 Download complete 
E            33d5df67cfc0 Download complete 
E            ff19393aeaeb Extracting 1 s
E            ff19393aeaeb Extracting 1 s
E            ff19393aeaeb Pull complete 
E            dd3d44a45162 Extracting 1 s
E            dd3d44a45162 Pull complete 
E            9ba5236abc11 Extracting 1 s
E            9ba5236abc11 Extracting 1 s
E            9ba5236abc11 Extracting 1 s
E            9ba5236abc11 Extracting 1 s
E            9ba5236abc11 Extracting 1 s
E            5eab64f96e79 Pull complete 
E            9ba5236abc11 Pull complete 
E            33d5df67cfc0 Extracting 1 s
E            4d6d087a846e Extracting 1 s
E            33d5df67cfc0 Pull complete 
E            4d6d087a846e Pull complete 
E            adcf0b927145 Extracting 1 s
E            adcf0b927145 Pull complete 
E            e254ced0d9d1 Pull complete 
E            openldap Pulled 
E            Network pytest5621-ldap_default  Creating
E            Network pytest5621-ldap_default  Created
E            Container test-openldap  Creating
E            Container test-openldap  Created
E            Container test-openldap  Starting
E            Container test-openldap  Started
E            Container test-openldap  Waiting
E           container test-openldap exited (1)
E           """.

venv/lib/python3.11....../site-packages/pytest_docker/plugin.py:37: Exception
tests.e2e.trace.test_api_trace::test_missing_elasticsearch_async_write
Stack Traces | 24.5s run time
auth_session = <tests.e2e.utils.TestSessionWrapper object at 0x7fb4aa389150>
graph_client = DataHubGraph: configured to talk to http://localhost:8080 with token: eyJh**********xKSo

    @pytest.mark.p0
    def test_missing_elasticsearch_async_write(auth_session, graph_client):
        urn = generated_urns["apiTraceDroppedElasticsearch"]
        aspect_name = "status"
    
        # Ensure a clean slate — pytest reruns reuse module-scoped fixtures and leave
        # the urn behind after a partial failure, turning the next write into a NO_OP.
        delete_urn(graph_client, urn)
        wait_for_writes_to_sync()
    
        resp = auth_session.post(
            f"{auth_session.gms_url()}.../v3/entity/dataset",
            params={"async": "true", "systemMetadata": "true"},
            json=[{"urn": urn, aspect_name: {"value": {"removed": False}}}],
        )
    
        trace_id = compare_trace_header_system_metadata(
            resp, resp.json()[0][aspect_name]["systemMetadata"]
        )
        wait_for_writes_to_sync(mcp_only=True)
    
        resp = auth_session.post(
            f"{auth_session.gms_url()}.../v1/trace/write/{trace_id}",
            params={"onlyIncludeErrors": "false", "detailed": "true"},
            json={urn: [aspect_name]},
        )
        assert resp.json() == {
            urn: {
                aspect_name: {
                    "success": True,
                    "primaryStorage": {"writeStatus": "ACTIVE_STATE"},
                    "searchStorage": {"writeStatus": "ACTIVE_STATE"},
                }
            }
        }
    
        # Simulate overwrite
        delete_elasticsearch_trace(trace_id)
    
        resp = auth_session.post(
            f"{auth_session.gms_url()}.../v1/trace/write/{trace_id}",
            params={"onlyIncludeErrors": "false", "detailed": "true", "skipCache": "true"},
            json={urn: [aspect_name]},
        )
        assert resp.json() == {
            urn: {
                aspect_name: {
                    "success": True,
                    "primaryStorage": {"writeStatus": "ACTIVE_STATE"},
                    "searchStorage": {"writeStatus": "HISTORIC_STATE"},
                }
            }
        }
    
        # Simulate dropped write
        delete_elasticsearch_system_metadata(urn)
        wait_until_system_metadata_deleted(urn)
    
        resp = auth_session.post(
            f"{auth_session.gms_url()}.../v1/trace/write/{trace_id}",
            params={"onlyIncludeErrors": "false", "detailed": "true", "skipCache": "true"},
            json={urn: [aspect_name]},
        )
>       assert resp.json() == {
            urn: {
                aspect_name: {
                    "success": False,
                    "primaryStorage": {"writeStatus": "ACTIVE_STATE"},
                    "searchStorage": {
                        "writeStatus": "ERROR",
                        "writeMessage": "Consumer has processed past the offset.",
                    },
                }
            }
        }
E       AssertionError: assert {'urn:li:dataset:(urn:li:dataPlatform:test,apiTraceDroppedElasticsearch,PROD)': {'status': {'success': True, 'primaryStorage': {'writeStatus': 'ACTIVE_STATE'}, 'searchStorage': {'writeStatus': 'PENDING', 'writeMessage': 'Consumer has processed past the offset; waiting for search visibility.'}}}} == {'urn:li:dataset:(urn:li:dataPlatform:test,apiTraceDroppedElasticsearch,PROD)': {'status': {'success': False, 'primaryStorage': {'writeStatus': 'ACTIVE_STATE'}, 'searchStorage': {'writeStatus': 'ERROR', 'writeMessage': 'Consumer has processed past the offset.'}}}}
E         
E         Differing items:
E         {'urn:li:dataset:(urn:li:dataPlatform:test,apiTraceDroppedElasticsearch,PROD)': {'status': {'success': True, 'primaryS...{'writeStatus': 'PENDING', 'writeMessage': 'Consumer has processed past the offset; waiting for search visibility.'}}}} != {'urn:li:dataset:(urn:li:dataPlatform:test,apiTraceDroppedElasticsearch,PROD)': {'status': {'success': False, 'primary...ACTIVE_STATE'}, 'searchStorage': {'writeStatus': 'ERROR', 'writeMessage': 'Consumer has processed past the offset.'}}}}
E         
E         Full diff: (-: missing in left side, +: extra in left side)
E           {
E               'urn:li:dataset:(urn:li:dataPlatform:test,apiTraceDroppedElasticsearch,PROD)': {
E                   'status': {
E         -             'success': False,
E         ?                        ^^^^
E         +             'success': True,
E         ?                        ^^^
E                       'primaryStorage': {
E                           'writeStatus': 'ACTIVE_STATE',
E                       },
E                       'searchStorage': {
E         -                 'writeStatus': 'ERROR',
E         ?                                  ^^^^
E         +                 'writeStatus': 'PENDING',
E         ?                                 + ^^^^^
E         -                 'writeMessage': 'Consumer has processed past the offset.',
E         ?                                                                        ^ -
E         +                 'writeMessage': 'Consumer has processed past the offset; waiting for search '
E         ?                                                                        ^^^^^^^^^^^^^^^^^^^^^
E         +                 'visibility.',
E                       },
E                   },
E               },
E           }

.../e2e/trace/test_api_trace.py:261: AssertionError
tests.integration.grafana.test_grafana::test_grafana_basic_ingest
Stack Traces | 210s run time
docker_compose_runner = <function docker_compose_runner.<locals>.run at 0x7f92ab5ce160>
test_resources_dir = PosixPath('.../tests/integration/grafana')

    @pytest.fixture(scope="module")
    def loaded_grafana(docker_compose_runner, test_resources_dir):
        with docker_compose_runner(
            test_resources_dir / "docker-compose.yml", "grafana"
        ) as docker_services:
            wait_for_port(docker_services, "postgres", 5432, timeout=90)
    
            def check_prometheus_ready():
                try:
                    prometheus_port = docker_services.port_for("prometheus", 9090)
                    response = requests.get(
                        f"http://localhost:{prometheus_port}/-/ready", timeout=5
                    )
                    return response.status_code == 200
                except (requests.exceptions.RequestException, Exception):
                    return False
    
            wait_for_port(
                docker_services,
                "prometheus",
                9090,
                timeout=90,
                checker=check_prometheus_ready,
            )
>           wait_for_port(docker_services, "grafana", 3000, timeout=180)

.../integration/grafana/test_grafana.py:161: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
.../datahub/testing/docker_utils.py:65: in wait_for_port
    docker_services.wait_until_responsive(
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = Services(_docker_compose=DockerComposeExecutor(_compose_command='docker compose --parallel -1', _compose_files=[PosixP...ion/grafana/docker-compose.yml')], _compose_project_name='pytest5630-grafana'), _services={'prometheus': {9090: 9090}})
check = <function wait_for_port.<locals>.<lambda> at 0x7f92ab5cee80>
timeout = 180, pause = 0.5, clock = <built-in function perf_counter>

    def wait_until_responsive(
        self,
        check: Any,
        timeout: float,
        pause: float,
        clock: Any = timeit.default_timer,
    ) -> None:
        """Wait until a service is responsive."""
    
        ref = clock()
        now = ref
        while (now - ref) < timeout:
            if check():
                return
            time.sleep(pause)
            now = clock()
    
>       raise Exception("Timeout reached while waiting on service!")
E       Exception: Timeout reached while waiting on service!

venv/lib/python3.11.../site-packages/pytest_docker/plugin.py:120: Exception

To view more test analytics, go to the Test Analytics Dashboard
📋 Got 3 mins? Take this short survey to help us improve Test Analytics.

The installer is unrelated to notebook column lineage and can fail native runs that previously succeeded.

Co-authored-by: Cursor <cursoragent@cursor.com>
Spark union stacks columns by position and keeps the left-hand names. unionByName still matches columns by name.

Co-authored-by: Cursor <cursoragent@cursor.com>
@datahub-connector-tests

datahub-connector-tests Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Connector Tests Results

All connector tests passed for commit bcf024c

View full test logs →

To skip connector tests, add the skip-connector-tests label (org members only).

Autogenerated by the connector-tests CI pipeline.

steve751 and others added 3 commits October 27, 2026 12:02
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 <cursoragent@cursor.com>
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 <cursoragent@cursor.com>
…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 <cursoragent@cursor.com>
@maggiehays maggiehays added the needs-review Label for PRs that need review from a maintainer. label Oct 27, 2026
steve751 and others added 2 commits November 3, 2026 10:13
…tion' into feat/fabric-notebook-column-lineage
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 <noreply@anthropic.com>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

7 issues found across 9 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md">

<violation number="1" location="metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md:380">
P3: The spelling-preservation statement is not true for `convert_urns_to_lowercase: true`: the emitter lowercases both field paths before publishing fine-grained lineage. Qualify this statement with the configured URN normalization so users do not expect `NAME` in the emitted lineage when lowercasing is enabled.</violation>
</file>

<file name="metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py">

<violation number="1" location="metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py:279">
P2: This assertion does not prove that `reconcile_code=False` suppresses column lineage because `_emit_dim_user` uses `_NOTEBOOK`, which has no column renames to emit. Run the disabled case with a notebook containing a known rename, such as `_COLUMN_NOTEBOOK`, and assert table lineage remains while field lineage is absent.</violation>

<violation number="2" location="metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py:583">
P2: The integration test never exercises `convert_urns_to_lowercase` behavior: its identity normalizer and matching-case setup allow incorrect field casing to pass. Use a lowercasing normalizer with mixed-case source/output names and assert the emitted field URNs use the normalized schema-field names.</violation>
</file>

<file name="metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py">

<violation number="1" location="metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py:374">
P2: Custom agent: **Enforce Strict Maintainability Standards**

This change grows `notebook_code_lineage.py` from 465 to 1,311 lines by adding the column-lineage interpreter here. Extract the projection and column-analysis logic into a focused module to keep this file below the 1,000-line threshold.</violation>

<violation number="2" location="metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py:726">
P2: `select("*")` drops the raw dataframe’s passthrough columns from the analyzer, so a subsequent advertised rename such as `df.select("*").select(col("x").alias("y"))` produces no upstream field edge. Preserve wildcard passthrough state when building the projected expression.</violation>

<violation number="3" location="metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py:797">
P2: `_union` discards column origins when either input is not already projected. Consequently, `read_a.union(read_b).select(col("id").alias("new_id"))` emits no column lineage; preserve origins for both union branches.</violation>
</file>

<file name="metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py">

<violation number="1" location="metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py:358">
P2: Custom agent: **Enforce i18n for User-Facing Strings**

This warning title and message are shown in the ingestion report UI, but they are raw English literals. Wrap both in the translation mechanism required for user-facing text.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

report=FabricOneLakeSourceReport(),
client=client,
known_table_urns=known,
normalize_name=lambda name: name,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The integration test never exercises convert_urns_to_lowercase behavior: its identity normalizer and matching-case setup allow incorrect field casing to pass. Use a lowercasing normalizer with mixed-case source/output names and assert the emitted field URNs use the normalized schema-field names.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py, line 583:

<comment>The integration test never exercises `convert_urns_to_lowercase` behavior: its identity normalizer and matching-case setup allow incorrect field casing to pass. Use a lowercasing normalizer with mixed-case source/output names and assert the emitted field URNs use the normalized schema-field names.</comment>

<file context>
@@ -237,9 +264,359 @@ def test_emitter_uses_code_to_drop_unused_plan_sources() -> None:
+        report=FabricOneLakeSourceReport(),
+        client=client,
+        known_table_urns=known,
+        normalize_name=lambda name: name,
+        owners_fn=lambda _upn: None,
+        reconcile_code=True,
</file context>

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This assertion does not prove that reconcile_code=False suppresses column lineage because _emit_dim_user uses _NOTEBOOK, which has no column renames to emit. Run the disabled case with a notebook containing a known rename, such as _COLUMN_NOTEBOOK, and assert table lineage remains while field lineage is absent.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At metadata-ingestion/tests/unit/fabric_onelake/test_notebook_code_lineage.py, line 279:

<comment>This assertion does not prove that `reconcile_code=False` suppresses column lineage because `_emit_dim_user` uses `_NOTEBOOK`, which has no column renames to emit. Run the disabled case with a notebook containing a known rename, such as `_COLUMN_NOTEBOOK`, and assert table lineage remains while field lineage is absent.</comment>

<file context>
@@ -237,9 +264,359 @@ def test_emitter_uses_code_to_drop_unused_plan_sources() -> None:
+        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
+
+
</file context>

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: select("*") drops the raw dataframe’s passthrough columns from the analyzer, so a subsequent advertised rename such as df.select("*").select(col("x").alias("y")) produces no upstream field edge. Preserve wildcard passthrough state when building the projected expression.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py, line 726:

<comment>`select("*")` drops the raw dataframe’s passthrough columns from the analyzer, so a subsequent advertised rename such as `df.select("*").select(col("x").alias("y"))` produces no upstream field edge. Preserve wildcard passthrough state when building the projected expression.</comment>

<file context>
@@ -406,13 +649,533 @@ def _writer_args(
+        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:
</file context>

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()))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: _union discards column origins when either input is not already projected. Consequently, read_a.union(read_b).select(col("id").alias("new_id")) emits no column lineage; preserve origins for both union branches.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py, line 797:

<comment>`_union` discards column origins when either input is not already projected. Consequently, `read_a.union(read_b).select(col("id").alias("new_id"))` emits no column lineage; preserve origins for both union branches.</comment>

<file context>
@@ -406,13 +649,533 @@ def _writer_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()))
+        case_sensitive = self._case_sensitive_columns
+        left_columns = _visible_columns(base, case_sensitive=case_sensitive)
</file context>

@@ -7,15 +7,20 @@
The source text names those tables even when the path is built at run time

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Custom agent: Enforce Strict Maintainability Standards

This change grows notebook_code_lineage.py from 465 to 1,311 lines by adding the column-lineage interpreter here. Extract the projection and column-analysis logic into a focused module to keep this file below the 1,000-line threshold.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py, line 374:

<comment>This change grows `notebook_code_lineage.py` from 465 to 1,311 lines by adding the column-lineage interpreter here. Extract the projection and column-analysis logic into a focused module to keep this file below the 1,000-line threshold.</comment>

<file context>
@@ -273,12 +364,119 @@ def _tail_has_tables(expr: ast.expr, env: Dict[str, str]) -> bool:
+
+
+@dataclass
+class _Projection:
+    """Columns of one dataframe expression.
+
</file context>

except NotebookCodeExtractionError as exc:
self._report.report_notebook_code_lineage_failed()
self._report.warning(
title="Failed to Extract Notebook Code Lineage",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Custom agent: Enforce i18n for User-Facing Strings

This warning title and message are shown in the ingestion report UI, but they are raw English literals. Wrap both in the translation mechanism required for user-facing text.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_jobs.py, line 358:

<comment>This warning title and message are shown in the ingestion report UI, but they are raw English literals. Wrap both in the translation mechanism required for user-facing text.</comment>

<file context>
@@ -298,12 +340,33 @@ def _spark_lineage(self, nb: PendingNotebook) -> Dict[SparkTableRef, List[str]]:
+            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. "
</file context>

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The spelling-preservation statement is not true for convert_urns_to_lowercase: true: the emitter lowercases both field paths before publishing fine-grained lineage. Qualify this statement with the configured URN normalization so users do not expect NAME in the emitted lineage when lowercasing is enabled.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At metadata-ingestion/docs/sources/fabric-onelake/fabric-onelake_post.md, line 380:

<comment>The spelling-preservation statement is not true for `convert_urns_to_lowercase: true`: the emitter lowercases both field paths before publishing fine-grained lineage. Qualify this statement with the configured URN normalization so users do not expect `NAME` in the emitted lineage when lowercasing is enabled.</comment>

<file context>
@@ -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 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).
</file context>
Suggested change
**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. Column matching ignores case by default, and the dataframe's spelling is preserved before the connector applies its configured URN normalization (`select("name")` resolves to `NAME`; with `convert_urns_to_lowercase: true`, the emitted field path is lowercased). 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.

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 <cursoragent@cursor.com>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 2 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py">

<violation number="1" location="metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py:520">
P2: `_record_lists` leaks through function-parameter shadowing, so an unresolved helper argument can reuse an outer loop’s configs and emit false lineage. Clear `_record_lists[name]` in `_hide_binding`.</violation>

<violation number="2" location="metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py:1008">
P2: Passing the loop config object itself to a helper loses the new record binding at the function boundary. `config["table_name"]` then remains unresolved, so the helper write is omitted and Spark’s carried-forward inputs are not reconciled; preserve record bindings in `_capture`/`_install` (or expand the fields at the call site).</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

flag = self._eval_bool(expr)
if flag is not None:
return ("bool", flag)
text = _eval_tail(expr, self._strings, self._records)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Passing the loop config object itself to a helper loses the new record binding at the function boundary. config["table_name"] then remains unresolved, so the helper write is omitted and Spark’s carried-forward inputs are not reconciled; preserve record bindings in _capture/_install (or expand the fields at the call site).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py, line 1008:

<comment>Passing the loop config object itself to a helper loses the new record binding at the function boundary. `config["table_name"]` then remains unresolved, so the helper write is omitted and Spark’s carried-forward inputs are not reconciled; preserve record bindings in `_capture`/`_install` (or expand the fields at the call site).</comment>

<file context>
@@ -904,7 +1005,7 @@ def _capture(self, expr: ast.expr) -> Tuple[str, object]:
         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)
</file context>

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]]] = {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: _record_lists leaks through function-parameter shadowing, so an unresolved helper argument can reuse an outer loop’s configs and emit false lineage. Clear _record_lists[name] in _hide_binding.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At metadata-ingestion/src/datahub/ingestion/source/fabric/onelake/notebook_code_lineage.py, line 520:

<comment>`_record_lists` leaks through function-parameter shadowing, so an unresolved helper argument can reuse an outer loop’s configs and emit false lineage. Clear `_record_lists[name]` in `_hide_binding`.</comment>

<file context>
@@ -477,6 +515,9 @@ def __init__(self, *, case_sensitive_columns: bool = False) -> None:
         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]] = {}
</file context>

steve751 and others added 3 commits November 27, 2026 11:12
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 <cursoragent@cursor.com>
…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 <cursoragent@cursor.com>
…rmat

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 <noreply@anthropic.com>

This branch was successfully deployed

1 active deployment
Preview — c5db198a Deployed Nov 27, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ingestion PR or Issue related to the ingestion of metadata needs-review Label for PRs that need review from a maintainer.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants