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


##########
dev/registry/tests/test_fill_durable_versions.py:
##########
@@ -0,0 +1,331 @@
+# 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
+
+import json
+import re
+import subprocess
+from unittest import mock
+
+import pytest
+from fill_durable_versions import (
+    DURABLE_TOKENS,
+    GitCommandError,
+    build_source_path,
+    durable_group,
+    find_first_releases,
+    get_released_tags,
+    main,
+    run_git,
+)
+
+POD_PATH = 
"providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/pod.py"
+POD_CLASS = 
"airflow.providers.cncf.kubernetes.operators.pod.KubernetesPodOperator"
+
+# Every class a test dates, each holding both tokens, for tests that are not 
about the class body.
+DURABLE_SOURCE = "\n".join(
+    f"class {name}:\n    def execute(self, task_state_store):\n        return 
self.execute_resumable()\n"
+    for name in ("Op", "KubernetesPodOperator")
+)
+

Review Comment:
   ```suggestion
   _DURABLE_CLASS_TEMPLATE = textwrap.dedent(
       """\
       class {name}:
           def execute(self, task_state_store):
               return self.execute_resumable()
       """
   )
   
   DURABLE_SOURCE = "\n".join(
       _DURABLE_CLASS_TEMPLATE.format(name=name) for name in ("Op", 
"KubernetesPodOperator")
   )
   ```
   
    I think it's easier to read this way



##########
dev/registry/extract_parameters.py:
##########
@@ -566,17 +572,77 @@ def is_durable_capable(cls: type, resumable_mixin: type | 
None) -> bool:
     2. Genuinely implementing ResumableJobMixin's contract, where `execute()` 
(or a class it
     delegates to) calls `execute_resumable()`.
     """
+    return find_durable_source(cls, resumable_mixin) is not None
+
+
+def find_durable_source(cls: type, resumable_mixin: type | None) -> 
tuple[type, str] | None:
+    """Return the class a durable capability comes from and the mechanism it 
uses, or None."""
     declaring_cls = _find_marker_declaring_class(cls)
     if declaring_cls is not None and _delegates_execute_to(cls, declaring_cls, 
_MAX_DEFERRAL_WALK_DEPTH):
-        return True
+        return declaring_cls, DURABLE_MECHANISM_MARKER
 
     if resumable_mixin is None or resumable_mixin not in cls.__mro__:
-        return False
+        return None
 
     if inspect.isabstract(cls):
-        return False
+        return None
+
+    owner = _execute_chain_calls_resumable(cls, _MAX_DEFERRAL_WALK_DEPTH)
+    return (owner, DURABLE_MECHANISM_MIXIN) if owner is not None else None
 
-    return _execute_chain_calls_resumable(cls, _MAX_DEFERRAL_WALK_DEPTH)
+
+def _repo_relative_source(cls: type) -> Path | None:

Review Comment:
   ```suggestion
   def _find_source_path_in_repo(cls: type) -> Path | None:
   ```



##########
dev/registry/extract_parameters.py:
##########
@@ -566,17 +572,77 @@ def is_durable_capable(cls: type, resumable_mixin: type | 
None) -> bool:
     2. Genuinely implementing ResumableJobMixin's contract, where `execute()` 
(or a class it
     delegates to) calls `execute_resumable()`.
     """
+    return find_durable_source(cls, resumable_mixin) is not None
+
+
+def find_durable_source(cls: type, resumable_mixin: type | None) -> 
tuple[type, str] | None:
+    """Return the class a durable capability comes from and the mechanism it 
uses, or None."""
     declaring_cls = _find_marker_declaring_class(cls)
     if declaring_cls is not None and _delegates_execute_to(cls, declaring_cls, 
_MAX_DEFERRAL_WALK_DEPTH):
-        return True
+        return declaring_cls, DURABLE_MECHANISM_MARKER
 
     if resumable_mixin is None or resumable_mixin not in cls.__mro__:
-        return False
+        return None
 
     if inspect.isabstract(cls):
-        return False
+        return None
+
+    owner = _execute_chain_calls_resumable(cls, _MAX_DEFERRAL_WALK_DEPTH)
+    return (owner, DURABLE_MECHANISM_MIXIN) if owner is not None else None
 
-    return _execute_chain_calls_resumable(cls, _MAX_DEFERRAL_WALK_DEPTH)
+
+def _repo_relative_source(cls: type) -> Path | None:
+    try:
+        source_file = inspect.getsourcefile(cls)
+    except TypeError:
+        return None
+    if source_file is None:
+        return None
+    try:
+        return Path(source_file).resolve().relative_to(AIRFLOW_ROOT.resolve())
+    except ValueError:
+        return None
+
+
+def _provider_id_from_source(rel_path: Path) -> str | None:

Review Comment:
   ```suggestion
   def _find_provider_id(rel_path: Path) -> str | None:
   ```



##########
dev/registry/fill_durable_versions.py:
##########
@@ -0,0 +1,204 @@
+#!/usr/bin/env python3
+# 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.
+"""Date each durable module in modules.json against the provider tags that 
first shipped it.
+
+Runs on the host rather than in Breeze with the rest of the module extraction, 
because it reads
+the ``providers-<id>/<version>`` git tags and Breeze does not mount ``.git``.
+
+Usage:
+    python dev/registry/fill_durable_versions.py --modules 
dev/registry/modules.json
+"""
+
+from __future__ import annotations
+
+import argparse
+import ast
+import functools
+import json
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+from packaging.version import InvalidVersion, Version
+
+AIRFLOW_ROOT = Path(__file__).parent.parent.parent
+
+# Inputs to the dating, not part of the published /api/modules.json contract.
+EXTRACTION_ONLY_FIELDS = ("durable_mechanism", "durable_gating_class")
+
+# Patterns matching the mechanism, never its registry declaration, and 
earliest match wins.
+# KubernetesPodOperator reconnected via task_state_store in 10.20.0 but only 
declared
+# `__supports_durable_execution` in 10.21.0; AgentOperator took `durable` in 
common-ai 0.1.0
+# but only moved to task_state_store in 0.7.0.
+DURABLE_TOKENS = {
+    "marker": r"task_state_store|durable: bool",
+    "resumable_mixin": "execute_resumable",
+}
+
+
+class GitCommandError(RuntimeError):
+    """A git call failed for a reason other than one the caller expected."""
+
+
+def run_git(*args: str, allowed_returncodes: tuple[int, ...] = (0,)) -> 
list[str]:
+    try:
+        result = subprocess.run(["git", *args], capture_output=True, 
text=True, cwd=AIRFLOW_ROOT, check=False)
+    except OSError as exc:
+        raise GitCommandError(f"Could not run git {' '.join(args)}: {exc}") 
from exc
+    if result.returncode not in allowed_returncodes:
+        raise GitCommandError(
+            f"git {' '.join(args)} failed with exit code {result.returncode}: 
{result.stderr.strip()}"
+        )
+    return [line for line in result.stdout.splitlines() if line]
+
+
[email protected]
+def get_released_tags(provider_id: str) -> tuple[str, ...]:
+    tags = []
+    for tag in run_git("tag", "--list", f"providers-{provider_id}/*"):
+        try:
+            version = Version(tag.rsplit("/", 1)[-1])
+        except InvalidVersion:
+            continue
+        if not version.is_prerelease:
+            tags.append(tag)
+    return tuple(tags)
+
+
+def build_source_path(provider_id: str, qualified_class: str) -> str:
+    module_path = qualified_class.rsplit(".", 1)[0].replace(".", "/")
+    return f"providers/{provider_id.replace('-', '/')}/src/{module_path}.py"
+
+
+def find_class_source(module_source: str, class_name: str) -> str | None:
+    """Return the source of the top-level class `class_name`, or None when the 
module lacks it."""
+    try:
+        tree = ast.parse(module_source)
+    except SyntaxError:
+        return None
+    for node in tree.body:
+        if isinstance(node, ast.ClassDef) and node.name == class_name:
+            return ast.get_source_segment(module_source, node)
+    return None
+
+
+def find_first_releases(
+    provider_id: str, token: str, targets: set[tuple[str, str]]
+) -> dict[tuple[str, str], str]:
+    """Map each (path, class) to the earliest released version of 
`provider_id` whose class holds `token`.
+
+    One `git grep` over every release tag finds the versions whose copy of 
each file holds the
+    token, so only those are read. The token is then searched in the class 
body alone, because
+    several durable classes can share a file and each adopts the capability in 
its own release.
+    """
+    tags = get_released_tags(provider_id)
+    if not tags:
+        return {}
+    paths = {path for path, _ in targets}
+    # git grep exits 1 when nothing matches, which is an ordinary answer here.
+    matches = run_git("grep", "-lE", token, *tags, "--", *sorted(paths), 
allowed_returncodes=(0, 1))
+    candidates: dict[str, list[tuple[Version, str]]] = {}
+    for line in matches:
+        tag, _, path = line.partition(":")
+        try:
+            version = Version(tag.rsplit("/", 1)[-1])
+        except InvalidVersion:
+            continue
+        if path in paths:
+            candidates.setdefault(path, []).append((version, tag))
+
+    pattern = re.compile(token)
+    first_releases: dict[tuple[str, str], str] = {}
+    for path, class_name in targets:
+        for version, tag in sorted(candidates.get(path, [])):
+            class_source = find_class_source("\n".join(run_git("show", 
f"{tag}:{path}")), class_name)
+            if class_source is not None and pattern.search(class_source):
+                first_releases[(path, class_name)] = str(version)
+                break
+    return first_releases
+
+
+def durable_group(module: dict) -> tuple[str, str, str, str] | None:

Review Comment:
   ```suggestion
   def find_durable_group(module: dict) -> tuple[str, str, str, str] | None:
   ```
   
   also making it a named tuple will be easier to read
   
   ```python
   class DurableGroup(NamedTuple):
       provider_id: str
       token: str
       source_path: str
       class_name: str
   ```



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