Lee-W commented on code in PR #69575:
URL: https://github.com/apache/airflow/pull/69575#discussion_r3594529824


##########
providers/common/dataquality/docs/rules.rst:
##########
@@ -0,0 +1,239 @@
+ .. 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.
+
+.. _dq:rules:
+
+Rules, rule sets, and checks
+============================
+
+Rules are data, not code. A 
:class:`~airflow.providers.common.dataquality.rules.RuleSet` is a named tuple of
+:class:`~airflow.providers.common.dataquality.rules.DQRule` -- plain, 
serializable objects with no behavior of
+their own. They describe *what* to check; 
:class:`~airflow.providers.common.dataquality.operators.dq_check.DQCheckOperator`
+(see :doc:`operators`) is what actually runs them. Rules are usually written 
by hand, but they
+can also be proposed by an LLM -- see :doc:`agents`.
+
+.. code-block:: python
+
+    from airflow.providers.common.dataquality.rules import DQRule, RuleSet

Review Comment:
   should we make it part of the example Dag instead?



##########
providers/common/dataquality/src/airflow/providers/common/dataquality/backends/object_storage.py:
##########
@@ -0,0 +1,256 @@
+# 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.
+"""
+Object-storage results backend.
+
+Each DQ check writes a keyed JSON document plus read indexes optimized for the 
UI:
+
+    
runs/by_task/dag_id=<dag>/task_id=<task>/date=<2026-07-04>/<started_at>__<run_uid>.json
+        Canonical run record: ``{"run": ..., "results": [...], "summary": 
...}``.
+
+    
runs/by_task_instance/dag_id=<dag>/task_id=<task>/<safe_run_id>__<map_index>.json
+        Latest result for a task-instance page. Last write wins across retries.
+
+    
rules/by_task_rule/dag_id=<dag>/task_id=<task>/rule_uid=<uid>/<started_at>__<run_uid>.json
+        One rule result plus run context: ``{"run": ..., "result": ...}``.
+
+The duplicate files are intentional read indexes: DQ tasks write once, while 
the UI reads
+many times. Keeping these indexes avoids scanning all task runs for common UI 
views.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from datetime import datetime, timezone
+from typing import Any
+
+from airflow.providers.common.dataquality.results import DQRun, RuleResult, 
build_summary
+from airflow.sdk import ObjectStoragePath
+
+log = logging.getLogger(__name__)
+
+
+class ObjectStorageResultsBackend:
+    """Persist DQ results as JSON files via ``ObjectStoragePath``."""
+
+    def __init__(self, results_path: str, conn_id: str | None = None) -> None:

Review Comment:
   ```suggestion
       def __init__(self, *, results_path: str, conn_id: str | None = None) -> 
None:
   ```
   
   let's make it keyword only, so that it will be easier for us to add new args 
in the future



##########
providers/common/dataquality/src/airflow/providers/common/dataquality/backends/object_storage.py:
##########
@@ -0,0 +1,256 @@
+# 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.
+"""
+Object-storage results backend.
+
+Each DQ check writes a keyed JSON document plus read indexes optimized for the 
UI:
+
+    
runs/by_task/dag_id=<dag>/task_id=<task>/date=<2026-07-04>/<started_at>__<run_uid>.json
+        Canonical run record: ``{"run": ..., "results": [...], "summary": 
...}``.
+
+    
runs/by_task_instance/dag_id=<dag>/task_id=<task>/<safe_run_id>__<map_index>.json
+        Latest result for a task-instance page. Last write wins across retries.
+
+    
rules/by_task_rule/dag_id=<dag>/task_id=<task>/rule_uid=<uid>/<started_at>__<run_uid>.json
+        One rule result plus run context: ``{"run": ..., "result": ...}``.
+
+The duplicate files are intentional read indexes: DQ tasks write once, while 
the UI reads
+many times. Keeping these indexes avoids scanning all task runs for common UI 
views.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from datetime import datetime, timezone
+from typing import Any
+
+from airflow.providers.common.dataquality.results import DQRun, RuleResult, 
build_summary
+from airflow.sdk import ObjectStoragePath
+
+log = logging.getLogger(__name__)
+
+
+class ObjectStorageResultsBackend:
+    """Persist DQ results as JSON files via ``ObjectStoragePath``."""
+
+    def __init__(self, results_path: str, conn_id: str | None = None) -> None:
+        self.root = ObjectStoragePath(results_path, conn_id=conn_id)
+
+    def write_run(self, run: DQRun, results: list[RuleResult]) -> None:
+        timestamp = run.started_at or datetime.now(tz=timezone.utc).isoformat()
+        compact_ts = self._get_safe_key(timestamp)
+        payload = self._build_run_payload(run, results)
+
+        self._write_run_file(run, timestamp[:10], compact_ts, payload)
+        self._write_task_instance_index(run, payload)
+        self._write_rule_indexes(run, results, timestamp)
+
+    def read_task_rule_history(
+        self, dag_id: str, task_id: str, rule_uid: str, limit: int = 100, 
before: str | None = None

Review Comment:
   The passing order kinda has its meaning. Accepting positional args is 
probably ok. But i would make it keyword only for explicitness



##########
providers/common/dataquality/src/airflow/providers/common/dataquality/assets.py:
##########
@@ -0,0 +1,172 @@
+# 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.
+"""
+Asset-level data quality declarations.
+
+Quality configuration lives inside ``Asset.extra`` under the 
``airflow.dataquality`` key, so it is
+serialized with the Dag and needs no Airflow core changes. The rules travel 
with the asset
+definition instead of being scattered across the Dags that check it.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Any
+
+from airflow.providers.common.dataquality.exceptions import 
DQRuleValidationError
+from airflow.providers.common.dataquality.rules import RuleSet
+from airflow.sdk import task
+
+if TYPE_CHECKING:
+    from collections.abc import Mapping, Sequence
+
+    from airflow.sdk import Asset
+    from airflow.sdk.execution_time.comms import 
AssetEventDagRunReferenceResult
+
+log = logging.getLogger(__name__)
+
+DQ_EXTRA_KEY = "airflow.dataquality"
+DQ_RESULT_EXTRA_KEY = "airflow.dataquality.result"
+
+
+def asset_quality(
+    asset: Asset,
+    *,
+    ruleset: RuleSet | dict[str, Any] | str,
+    conn_id: str | None = None,
+    table: str | None = None,
+) -> Asset:
+    """
+    Attach data quality configuration to an asset, returning the same asset.
+
+    :param asset: The asset the rules describe.
+    :param ruleset: A 
:class:`~airflow.providers.common.dataquality.rules.RuleSet`, its dict form, or 
a path
+        to a YAML ruleset file (resolved eagerly, at Dag-parse time).
+    :param conn_id: Default connection a check operator should use for this 
asset.
+    :param table: Default table to check; falls back to the asset name when 
unset.
+
+    Usage::
+
+        orders = asset_quality(
+            Asset("orders", uri="postgres://warehouse/analytics/orders"),
+            ruleset=rules,
+            conn_id="warehouse",
+            table="analytics.orders",
+        )
+        check = DQCheckOperator(task_id="dq", asset=orders)
+    """
+    if isinstance(ruleset, str):
+        ruleset = RuleSet.from_file(ruleset)
+    elif isinstance(ruleset, dict):
+        ruleset = RuleSet.from_dict(ruleset)
+    config: dict[str, Any] = {"ruleset": ruleset.to_dict()}
+    if conn_id:
+        config["conn_id"] = conn_id
+    if table:
+        config["table"] = table
+    asset.extra[DQ_EXTRA_KEY] = config

Review Comment:
   Please don't use `asset.extra`. This is going to be removed 
https://github.com/apache/airflow/issues/55200. 



##########
providers/common/dataquality/src/airflow/providers/common/dataquality/backends/object_storage.py:
##########
@@ -0,0 +1,256 @@
+# 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.
+"""
+Object-storage results backend.
+
+Each DQ check writes a keyed JSON document plus read indexes optimized for the 
UI:
+
+    
runs/by_task/dag_id=<dag>/task_id=<task>/date=<2026-07-04>/<started_at>__<run_uid>.json
+        Canonical run record: ``{"run": ..., "results": [...], "summary": 
...}``.
+
+    
runs/by_task_instance/dag_id=<dag>/task_id=<task>/<safe_run_id>__<map_index>.json
+        Latest result for a task-instance page. Last write wins across retries.
+
+    
rules/by_task_rule/dag_id=<dag>/task_id=<task>/rule_uid=<uid>/<started_at>__<run_uid>.json
+        One rule result plus run context: ``{"run": ..., "result": ...}``.
+
+The duplicate files are intentional read indexes: DQ tasks write once, while 
the UI reads
+many times. Keeping these indexes avoids scanning all task runs for common UI 
views.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from datetime import datetime, timezone
+from typing import Any
+
+from airflow.providers.common.dataquality.results import DQRun, RuleResult, 
build_summary
+from airflow.sdk import ObjectStoragePath
+
+log = logging.getLogger(__name__)
+
+
+class ObjectStorageResultsBackend:
+    """Persist DQ results as JSON files via ``ObjectStoragePath``."""
+
+    def __init__(self, results_path: str, conn_id: str | None = None) -> None:
+        self.root = ObjectStoragePath(results_path, conn_id=conn_id)
+
+    def write_run(self, run: DQRun, results: list[RuleResult]) -> None:
+        timestamp = run.started_at or datetime.now(tz=timezone.utc).isoformat()
+        compact_ts = self._get_safe_key(timestamp)
+        payload = self._build_run_payload(run, results)
+
+        self._write_run_file(run, timestamp[:10], compact_ts, payload)
+        self._write_task_instance_index(run, payload)
+        self._write_rule_indexes(run, results, timestamp)
+
+    def read_task_rule_history(
+        self, dag_id: str, task_id: str, rule_uid: str, limit: int = 100, 
before: str | None = None
+    ) -> dict[str, Any]:
+        """Return recent results for one rule produced by one task, newest 
first."""
+        rule_dir = (
+            self.root
+            / "rules"
+            / "by_task_rule"
+            / f"dag_id={dag_id}"
+            / f"task_id={task_id}"
+            / f"rule_uid={rule_uid}"
+        )
+        return self._read_rule_history_dir(rule_dir, limit, before)
+
+    def read_task_runs(
+        self, dag_id: str, task_id: str, limit: int = 50, before: str | None = 
None
+    ) -> dict[str, Any]:
+        """
+        Return recent data quality runs for one task, newest first.
+
+        Returns ``{"items": [...], "next_cursor": ...}``. ``before`` is the 
opaque
+        ``next_cursor`` from the previous page, so "load more" only reads runs 
it hasn't
+        shown yet. ``next_cursor`` is set by reading one extra entry past 
``limit``: cheap
+        on every page except the last one, where there's no way to confirm 
history is
+        exhausted without walking to the end.
+
+        ``date=`` partition names sort correctly as plain strings, so 
directories are walked
+        newest-first. Filenames are ``{started_at}__{run_uid}.json``, so 
sorting each partition's
+        filenames before scanning also walks newest-first within the partition 
-- required for
+        the early exit below to stop on the actual newest runs rather than an 
arbitrary subset.
+        Scanning stops as soon as ``limit + 1`` matching runs have been 
collected — a task with
+        years of history doesn't pay for a full scan on every page.
+        """
+        task_dir = self.root / "runs" / "by_task" / f"dag_id={dag_id}" / 
f"task_id={task_id}"
+        if not task_dir.exists():
+            return {"items": [], "next_cursor": None}
+
+        date_dirs = sorted((path for path in task_dir.iterdir() if 
path.is_dir()), reverse=True)
+        runs = []
+        for date_dir in date_dirs:
+            for path in sorted(date_dir.iterdir(), key=lambda p: p.name, 
reverse=True):
+                if not path.name.endswith(".json"):
+                    continue
+                payload = self._read_json(path)
+                if payload is None:
+                    continue
+                cursor = self._get_run_payload_cursor(payload)
+                if before is not None and cursor >= before:
+                    continue

Review Comment:
   ```suggestion
                   if (payload := self._read_json(path)) is None:
                       continue
                   if before is not None and (cursor := 
self._get_run_payload_cursor(payload)) >= before:
                       continue
   ```
   
   nit



##########
providers/common/dataquality/src/airflow/providers/common/dataquality/assets.py:
##########
@@ -0,0 +1,190 @@
+# 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.
+"""
+Asset-level data quality declarations.
+
+Quality configuration lives inside ``Asset.extra`` under the 
``airflow.dataquality`` key, so it is
+serialized with the Dag and needs no Airflow core changes. The rules travel 
with the asset
+definition instead of being scattered across the Dags that check it.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Any
+
+from airflow.providers.common.dataquality.exceptions import 
DQRuleValidationError
+from airflow.providers.common.dataquality.rules import RuleSet
+from airflow.sdk import task
+
+if TYPE_CHECKING:
+    from collections.abc import Mapping, Sequence
+
+    from airflow.sdk import Asset
+    from airflow.sdk.execution_time.comms import 
AssetEventDagRunReferenceResult
+
+log = logging.getLogger(__name__)
+
+DQ_EXTRA_KEY = "airflow.dataquality"
+DQ_RESULT_EXTRA_KEY = "airflow.dataquality.result"
+
+
+def asset_quality(
+    asset: Asset,

Review Comment:
   Are we going to support `AssetRef`, `AssetAlias`? 



##########
providers/common/dataquality/src/airflow/providers/common/dataquality/backends/object_storage.py:
##########
@@ -0,0 +1,256 @@
+# 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.
+"""
+Object-storage results backend.
+
+Each DQ check writes a keyed JSON document plus read indexes optimized for the 
UI:
+
+    
runs/by_task/dag_id=<dag>/task_id=<task>/date=<2026-07-04>/<started_at>__<run_uid>.json
+        Canonical run record: ``{"run": ..., "results": [...], "summary": 
...}``.
+
+    
runs/by_task_instance/dag_id=<dag>/task_id=<task>/<safe_run_id>__<map_index>.json
+        Latest result for a task-instance page. Last write wins across retries.
+
+    
rules/by_task_rule/dag_id=<dag>/task_id=<task>/rule_uid=<uid>/<started_at>__<run_uid>.json
+        One rule result plus run context: ``{"run": ..., "result": ...}``.
+
+The duplicate files are intentional read indexes: DQ tasks write once, while 
the UI reads
+many times. Keeping these indexes avoids scanning all task runs for common UI 
views.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from datetime import datetime, timezone
+from typing import Any
+
+from airflow.providers.common.dataquality.results import DQRun, RuleResult, 
build_summary
+from airflow.sdk import ObjectStoragePath
+
+log = logging.getLogger(__name__)
+
+
+class ObjectStorageResultsBackend:
+    """Persist DQ results as JSON files via ``ObjectStoragePath``."""
+
+    def __init__(self, results_path: str, conn_id: str | None = None) -> None:
+        self.root = ObjectStoragePath(results_path, conn_id=conn_id)
+
+    def write_run(self, run: DQRun, results: list[RuleResult]) -> None:
+        timestamp = run.started_at or datetime.now(tz=timezone.utc).isoformat()
+        compact_ts = self._get_safe_key(timestamp)
+        payload = self._build_run_payload(run, results)
+
+        self._write_run_file(run, timestamp[:10], compact_ts, payload)
+        self._write_task_instance_index(run, payload)
+        self._write_rule_indexes(run, results, timestamp)
+
+    def read_task_rule_history(
+        self, dag_id: str, task_id: str, rule_uid: str, limit: int = 100, 
before: str | None = None
+    ) -> dict[str, Any]:
+        """Return recent results for one rule produced by one task, newest 
first."""
+        rule_dir = (
+            self.root
+            / "rules"
+            / "by_task_rule"
+            / f"dag_id={dag_id}"
+            / f"task_id={task_id}"
+            / f"rule_uid={rule_uid}"
+        )
+        return self._read_rule_history_dir(rule_dir, limit, before)
+
+    def read_task_runs(
+        self, dag_id: str, task_id: str, limit: int = 50, before: str | None = 
None
+    ) -> dict[str, Any]:
+        """
+        Return recent data quality runs for one task, newest first.
+
+        Returns ``{"items": [...], "next_cursor": ...}``. ``before`` is the 
opaque
+        ``next_cursor`` from the previous page, so "load more" only reads runs 
it hasn't
+        shown yet. ``next_cursor`` is set by reading one extra entry past 
``limit``: cheap
+        on every page except the last one, where there's no way to confirm 
history is
+        exhausted without walking to the end.
+
+        ``date=`` partition names sort correctly as plain strings, so 
directories are walked
+        newest-first. Filenames are ``{started_at}__{run_uid}.json``, so 
sorting each partition's
+        filenames before scanning also walks newest-first within the partition 
-- required for
+        the early exit below to stop on the actual newest runs rather than an 
arbitrary subset.
+        Scanning stops as soon as ``limit + 1`` matching runs have been 
collected — a task with
+        years of history doesn't pay for a full scan on every page.
+        """
+        task_dir = self.root / "runs" / "by_task" / f"dag_id={dag_id}" / 
f"task_id={task_id}"
+        if not task_dir.exists():
+            return {"items": [], "next_cursor": None}
+
+        date_dirs = sorted((path for path in task_dir.iterdir() if 
path.is_dir()), reverse=True)
+        runs = []
+        for date_dir in date_dirs:
+            for path in sorted(date_dir.iterdir(), key=lambda p: p.name, 
reverse=True):
+                if not path.name.endswith(".json"):
+                    continue
+                payload = self._read_json(path)
+                if payload is None:
+                    continue
+                cursor = self._get_run_payload_cursor(payload)
+                if before is not None and cursor >= before:
+                    continue
+                runs.append(payload)
+                if len(runs) > limit:
+                    break
+            if len(runs) > limit:
+                break
+
+        ordered = sorted(runs, key=self._get_run_payload_cursor, reverse=True)
+        page = ordered[:limit]
+        next_cursor = self._get_run_payload_cursor(page[-1]) if len(ordered) > 
limit and page else None
+        return {"items": page, "next_cursor": next_cursor}

Review Comment:
   does the output format always look like this? if so, should we make it a 
TypedDict



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to