jedcunningham commented on code in PR #40335:
URL: https://github.com/apache/airflow/pull/40335#discussion_r1675319142


##########
docs/apache-airflow/administration-and-deployment/lineage.rst:
##########
@@ -89,6 +89,42 @@ has outlets defined (e.g. by using ``add_outlets(..)`` or 
has out of the box sup
 
 .. _precedence: https://docs.python.org/3/reference/expressions.html
 
+Hook Lineage
+------------
+
+Airflow provides a powerful feature for tracking data lineage not only between 
tasks but also from hooks used within those tasks.
+This functionality helps you understand how data flows throughout your Airflow 
pipelines.
+
+A global instance of ``HookLineageCollector`` serves as the central hub for 
collecting lineage information.
+Hooks can send details about datasets they interact with to this collector.
+The collector then uses this data to construct AIP-60 compliant Datasets, a 
standard format for describing datasets.
+
+.. code-block:: python
+
+    from airflow.lineage.hook_lineage import get_hook_lineage_collector
+
+
+    class CustomHook(BaseHook):
+        def run(self):
+            # run actual code
+            collector = get_hook_lineage_collector()
+            collector.add_inlet(dataset_kwargs={"scheme": "file", "path": 
"/tmp/in"}, self)
+            collector.add_outlet(dataset_kwargs={"scheme": "file", "path": 
"/tmp/out"}, self)

Review Comment:
   ```suggestion
               collector.add_inlet(dataset_kwargs={"scheme": "file", "path": 
"/tmp/in"}, hook=self)
               collector.add_outlet(dataset_kwargs={"scheme": "file", "path": 
"/tmp/out"}, hook=self)
   ```
   
   Positional args can't follow kwargs.



##########
airflow/lineage/hook.py:
##########
@@ -0,0 +1,149 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+from typing import Union
+
+import attr
+
+from airflow.datasets import Dataset
+from airflow.hooks.base import BaseHook
+from airflow.io.store import ObjectStore
+from airflow.providers_manager import ProvidersManager
+from airflow.utils.log.logging_mixin import LoggingMixin
+
+# Store context what sent lineage.
+LineageContext = Union[BaseHook, ObjectStore]
+
+_hook_lineage_collector: HookLineageCollector | None = None
+
+
+@attr.define
+class HookLineage:
+    """Holds lineage collected by HookLineageCollector."""
+
+    inputs: list[tuple[Dataset, LineageContext]] = attr.ib(factory=list)
+    outputs: list[tuple[Dataset, LineageContext]] = attr.ib(factory=list)
+
+
+class HookLineageCollector(LoggingMixin):
+    """
+    HookLineageCollector is a base class for collecting hook lineage 
information.
+
+    It is used to collect the input and output datasets of a hook execution.
+    """
+
+    def __init__(self, **kwargs):
+        super().__init__(**kwargs)
+        self.inputs: list[tuple[Dataset, LineageContext]] = []
+        self.outputs: list[tuple[Dataset, LineageContext]] = []
+
+    @staticmethod
+    def create_dataset(dataset_kwargs: dict) -> Dataset:
+        """Create a Dataset instance from the given dataset kwargs."""
+        if "uri" in dataset_kwargs:
+            # Fallback to default factory using the provided URI
+            return Dataset(uri=dataset_kwargs["uri"])
+
+        scheme: str = dataset_kwargs.pop("scheme", None)
+        if not scheme:
+            raise ValueError(
+                "Missing required parameter: either 'uri' or 'scheme' must be 
provided to create a Dataset."
+            )
+
+        dataset_factory = ProvidersManager().dataset_factories.get(scheme)
+        if not dataset_factory:
+            raise ValueError(
+                f"Unsupported scheme: '{scheme}'. Please provide a valid URI 
to create a Dataset."
+            )
+
+        return dataset_factory(**dataset_kwargs)
+
+    def add_input_dataset(self, dataset_kwargs: dict, hook: LineageContext) -> 
None:
+        """Add the input dataset and its corresponding hook execution context 
to the collector."""
+        try:
+            dataset = self.create_dataset(dataset_kwargs)
+        except Exception as e:
+            self.log.debug("Failed to create AIP-60 compliant Dataset. %s", e)
+            return
+        self.inputs.append((dataset, hook))
+
+    def add_output_dataset(self, dataset_kwargs: dict, hook: LineageContext) 
-> None:
+        """Add the output dataset and its corresponding hook execution context 
to the collector."""
+        try:
+            dataset = self.create_dataset(dataset_kwargs)
+        except Exception as e:
+            self.log.debug("Failed to create AIP-60 compliant Dataset. %s", e)
+            return
+        self.outputs.append((dataset, hook))
+
+    @property
+    def collected_datasets(self) -> HookLineage:
+        """Get the collected hook lineage information."""
+        return HookLineage(self.inputs, self.outputs)
+
+    @property
+    def has_collected(self) -> bool:
+        """Check if any datasets have been collected."""
+        return len(self.inputs) != 0 or len(self.outputs) != 0
+
+
+class NoOpCollector(HookLineageCollector):
+    """
+    NoOpCollector is a hook lineage collector that does nothing.
+
+    It is used when you want to disable lineage collection.
+    """
+
+    def add_input_dataset(self, *_):
+        pass
+
+    def add_output_dataset(self, *_):
+        pass
+
+    @property
+    def collected_datasets(
+        self,
+    ) -> HookLineage:
+        self.log.warning(
+            "Data lineage tracking might be incomplete. Consider registering a 
hook lineage reader for more detailed information."

Review Comment:
   Not "might be", right? Maybe something like this:
   
   ```suggestion
               "Data lineage tracking is disabled. Register a hook lineage 
reader to start tracking hook lineage."
   ```



##########
docs/apache-airflow/administration-and-deployment/lineage.rst:
##########
@@ -89,6 +89,42 @@ has outlets defined (e.g. by using ``add_outlets(..)`` or 
has out of the box sup
 
 .. _precedence: https://docs.python.org/3/reference/expressions.html
 
+Hook Lineage
+------------
+
+Airflow provides a powerful feature for tracking data lineage not only between 
tasks but also from hooks used within those tasks.
+This functionality helps you understand how data flows throughout your Airflow 
pipelines.
+
+A global instance of ``HookLineageCollector`` serves as the central hub for 
collecting lineage information.
+Hooks can send details about datasets they interact with to this collector.
+The collector then uses this data to construct AIP-60 compliant Datasets, a 
standard format for describing datasets.
+
+.. code-block:: python
+
+    from airflow.lineage.hook_lineage import get_hook_lineage_collector
+
+
+    class CustomHook(BaseHook):
+        def run(self):
+            # run actual code
+            collector = get_hook_lineage_collector()
+            collector.add_inlet(dataset_kwargs={"scheme": "file", "path": 
"/tmp/in"}, self)
+            collector.add_outlet(dataset_kwargs={"scheme": "file", "path": 
"/tmp/out"}, self)
+
+Lineage data collected by the ``HookLineageCollector`` can be accessed using 
an instance of ``HookLineageReader``.
+
+.. code-block:: python
+
+    from airflow.lineage.hook_lineage import HookLineageReader
+
+
+    class CustomHookLineageReader(HookLineageReader):
+        def get_inputs(self):
+            return self.lineage_collector.collected_datasets.inputs
+
+If no ``HookLineageReader`` is registered within Airflow, a default 
``NoOpCollector`` is used instead.

Review Comment:
   We are missing details on how to register them.
   
   On that note, feels a little weird that they have to come from providers? I 
haven't though through it much, but that's my initial reaction.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscr...@airflow.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to