You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "wjddn279 (via GitHub)" <gi...@apache.org> on 2025/12/15 06:45:16 UTC
[PR] add static checker for preventing to increase dag version [airflow]
wjddn279 opened a new pull request, #59430:
URL: https://github.com/apache/airflow/pull/59430
## Motivation
We observed that when runtime-varying values are used as arguments in DAG or Task constructors in Airflow, the DAG version increases infinitely. [slack](https://apache-airflow.slack.com/archives/CCQ7EGB1P/p1763408409990439?thread_ts=1763078254.725439&cid=CCQ7EGB1P) https://github.com/apache/airflow/issues/55768#issuecomment-3360876034
Checking for DAG version increments at runtime is difficult. The most accurate detection method would be to parse the DAG object twice and compare if values differ. However, this would nearly double the DAG parsing execution time.
Therefore, I add a feature that exposes DAG warnings for these cases through AST-based static analysis before parsing in the dag-processor. While it cannot cover 100% of DAG usage patterns, it can cover most cases and has minimal performance impact (since `ast.parse` [already runs](https://github.com/apache/airflow/blob/main/airflow-core/src/airflow/dag_processing/processor.py#L514) on every DAG parse).
## Logic of static check
The logic for detecting problematic situations through static check is as follows (I named this issue "runtime-varying"):
1. Statically analyze a single DAG file through `ast.parse`.
2. Traverse each node and check the following:
- Has a variable been assigned a runtime-varying value? → This is to check if that variable is passed as an argument to a DAG or Task instance.
```python
from datetime import datetime
import random as rd
start_date = datetime.now() # checked as tainted value
random_value = f"random_{rd.randint(1,1000)" # checked as tainted value
default_args = {'start_date': start_date} # checked as tainted value
```
3. Check if the object is a DAG or Task declaration statement, and verify if runtime-varying variables or function calls are passed as arguments.
- Check if it's a DAG declaration statement → We categorized DAG object definitions into 3 cases:
```python
from airflow import DAG
from airflow.decorators import dag
dag = DAG(dag_id='dag_id, default_args=default_args) # DAG object definition imported from airflow module
with DAG(dag_id='dag_id, default_args=default_args) as dag: # Defined as context manager in with statement
@dag(dag_id='dag_id, default_args=default_args) # Defined via dag decorator
```
- Check if it's a Task declaration statement → This case can be categorized into 2 types:
```python
task1 = PythonOperator(task_id='task_id', dag=dag) # When the DAG object checked above is passed as an argument
with DAG(dag_id='dag_id, default_args=default_args) as dag:
task2 = PythonOperator(task_id='task_id') # Function calls inside the with block where DAG context manager is declared
```
The cases covered by static checks are described in detail in the unit test code.
## User Notification for Static Check Errors
I considered that static check failures are not severe enough to cause DAG parsing to fail, so I added them to DAG warnings. Warnings are added to DAGs generated from the DAG file and displayed in the UI as shown below. There seems to be an issue where `\n` characters in messages are ignored when displayed in the UI, which we plan to fix in a future PR.
<img width="1700" height="750" alt="image" src="https://github.com/user-attachments/assets/f151199a-fbd2-4f2e-b407-f7f03214724f" />
## future work
If this PR is merged, the following items are planned for future work:
- Merge the existing `ast.parse` with the `ast.parse` executed in this subprocess.
- Fix the UI that displays DAG warnings.
- Make DAG warnings more visible by displaying them in the DAG list as well.
- Document the cases where DAG version increases infinitely and the coverage scope of this static check.
<!--
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.
-->
<!--
Thank you for contributing! Please make sure that your code changes
are covered with tests. And in case of new features or big changes
remember to adjust the documentation.
Feel free to ping committers for the review!
In case of an existing issue, reference it using one of the following:
closes: #ISSUE
related: #ISSUE
How to write a good git commit message:
http://chris.beams.io/posts/git-commit/
-->
<!-- Please keep an empty line above the dashes. -->
---
**^ Add meaningful description above**
Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information.
In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments).
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3678008192
Yeah, that is a good idea.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3748516414
@Lee-W
It needs more reviews?
I plan to start additional work to resolve this issue as soon as this PR is merged!
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3775748832
@sjyangkevin I think we can do something similar on the ruff end side as well. Let's create a AIR304 maybe?
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3699303938
One other check that could be added -> https://github.com/apache/airflow/discussions/59595#discussioncomment-15374911 -> check if any of the objects serialized is non-serializable and results with "object @ hash".
This is not a static check, though, it could be raised at the time of actual Dag Parsing only I think.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "ephraimbuddy (via GitHub)" <gi...@apache.org>.
ephraimbuddy commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2626462173
##########
airflow-core/src/airflow/dag_processing/collection.py:
##########
@@ -371,7 +374,10 @@ def update_dag_parsing_results_in_db(
warnings: set[DagWarning],
session: Session,
*,
- warning_types: tuple[DagWarningType] = (DagWarningType.NONEXISTENT_POOL,),
+ warning_types: tuple[DagWarningType, DagWarningType] = (
Review Comment:
```suggestion
warning_types: tuple[DagWarningType, ...] = (
```
we should use this everywhere for warning_types so we can avoid signature change in the future
##########
airflow-core/src/airflow/dag_processing/processor.py:
##########
@@ -200,20 +201,24 @@ def _parse_file_entrypoint():
sys.path.append(bundle_root)
result = _parse_file(msg, log)
+
if result is not None:
comms_decoder.send(result)
def _parse_file(msg: DagFileParseRequest, log: FilteringBoundLogger) -> DagFileParsingResult | None:
# TODO: Set known_pool names on DagBag!
+ warning_statement = check_dag_file_static(os.fspath(msg.file))
Review Comment:
We should have a catch all exceptions here to ensure this doesn't break the parsing. We should manually test this implementation with very large dag file.
##########
airflow-core/src/airflow/models/dagwarning.py:
##########
@@ -103,3 +103,4 @@ class DagWarningType(str, Enum):
ASSET_CONFLICT = "asset conflict"
NONEXISTENT_POOL = "non-existent pool"
+ PARSING_ERROR = "parsing error"
Review Comment:
Maybe RUNTIME_VARYING_VALUE
##########
airflow-core/src/airflow/dag_processing/processor.py:
##########
@@ -509,10 +513,6 @@ def start( # type: ignore[override]
client: Client,
**kwargs,
) -> Self:
- logger = kwargs["logger"]
-
- _pre_import_airflow_modules(os.fspath(path), logger)
Review Comment:
Why this change??
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2626223279
##########
airflow-core/src/airflow/dag_processing/manager.py:
##########
@@ -1190,13 +1190,17 @@ def process_parse_results(
files_parsed = {(bundle_name, relative_fileloc)}
files_parsed.update(import_errors.keys())
+ warning = parsing_result.warnings
+ if parsing_result.warnings and isinstance(parsing_result.warnings[0], dict):
Review Comment:
```suggestion
if (warnings := parsing_result.warnings) and isinstance(warnings[0], dict):
```
##########
airflow-core/src/airflow/utils/static_checker.py:
##########
@@ -0,0 +1,468 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "TASK constructor"
+ DAG_CONSTRUCTOR = "DAG constructor"
+
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+]
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(self, varying_vars: dict, imports: dict, from_imports: dict):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self._is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self._check_fstring_varying(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self._check_collection_varying(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self._check_dict_varying(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def _check_fstring_varying(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ source = self.get_varying_source(value.value)
+ if source:
+ return source
+ return None
+
+ def _check_collection_varying(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def _check_dict_varying(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def _is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
+ """Check for runtime-varying calls like now() (when imported via 'from import')."""
+ func_name = func.id
+
+ if func_name in self.from_imports:
+ module, original_name = self.from_imports[func_name]
+ module_parts = module.split(".")
+
+ for part in module_parts:
+ if (part, original_name) in RUNTIME_VARYING_CALLS:
+ return True
+
+ return False
+
+
+class DAGTaskDetector:
+ """
+ Detector dedicated to identifying DAG and Task constructors.
+
+ This detector identifies when code is creating DAG or Task objects
+ in Airflow. It needs to handle both traditional class instantiation and decorator styles.
+ """
+
+ def __init__(self, from_imports: dict):
+ self.from_imports = from_imports
+ self.dag_instances: set[str] = set()
+ self.is_in_dag_context: bool = False
+
+ def is_dag_constructor(self, node: ast.Call) -> bool:
+ """Check if a call is a DAG constructor."""
+ if not isinstance(node.func, ast.Name):
+ return False
+
+ func_name = node.func.id
+
+ # "from airflow import DAG" form or "from airflow.decorator import dag"
+ if func_name in self.from_imports:
+ module, original = self.from_imports[func_name]
+ if (module == "airflow" or module.startswith("airflow.")) and original in ("DAG", "dag"):
+ return True
+
+ return False
+
+ def is_task_constructor(self, node: ast.Call) -> bool:
+ """
+ Check if a call is a Task constructor.
+
+ Criteria:
+ 1. All calls within a DAG with block
+ 2. Calls that receive a DAG instance as an argument (dag=...)
+ """
+ # Inside DAG with block
+ if self.is_in_dag_context:
+ return True
+
+ # Passing DAG instance as argument
+ for arg in node.args:
+ if isinstance(arg, ast.Name) and arg.id in self.dag_instances:
+ return True
+
+ for keyword in node.keywords:
+ if keyword.value and isinstance(keyword.value, ast.Name):
+ if keyword.value.id in self.dag_instances:
+ return True
+
+ return False
+
+ def register_dag_instance(self, var_name: str):
+ """Register a DAG instance variable name."""
+ self.dag_instances.add(var_name)
+
+ def enter_dag_context(self):
+ """Enter a DAG with block."""
+ self.is_in_dag_context = True
+
+ def exit_dag_context(self):
+ """Exit a DAG with block."""
+ self.is_in_dag_context = False
+
+
+class AirflowRuntimeVaryingValueChecker(ast.NodeVisitor):
+ """
+ Main visitor class to detect runtime-varying value usage in Airflow DAG/Task.
+
+ Main responsibilities:
+ - Traverse AST and visit nodes
+ - Detect DAG/Task creation
+ - Track runtime-varying values and generate warnings
Review Comment:
```suggestion
Main visitor class to detect runtime-varying value usage in Airflow Dag/Task.
Main responsibilities:
- Traverse AST and visit nodes
- Detect Dag/Task creation
- Track runtime-varying values and generate warnings
```
##########
airflow-core/src/airflow/dag_processing/manager.py:
##########
@@ -1190,13 +1190,17 @@ def process_parse_results(
files_parsed = {(bundle_name, relative_fileloc)}
files_parsed.update(import_errors.keys())
+ warning = parsing_result.warnings
+ if parsing_result.warnings and isinstance(parsing_result.warnings[0], dict):
+ warning = [DagWarning(**warn) for warn in parsing_result.warnings]
Review Comment:
```suggestion
warning = [DagWarning(**warn) for warn in warnings]
```
##########
airflow-core/src/airflow/utils/static_checker.py:
##########
@@ -0,0 +1,468 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "TASK constructor"
+ DAG_CONSTRUCTOR = "DAG constructor"
+
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+]
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(self, varying_vars: dict, imports: dict, from_imports: dict):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self._is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self._check_fstring_varying(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self._check_collection_varying(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self._check_dict_varying(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def _check_fstring_varying(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ source = self.get_varying_source(value.value)
+ if source:
+ return source
+ return None
+
+ def _check_collection_varying(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def _check_dict_varying(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def _is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
+ """Check for runtime-varying calls like now() (when imported via 'from import')."""
+ func_name = func.id
+
+ if func_name in self.from_imports:
+ module, original_name = self.from_imports[func_name]
+ module_parts = module.split(".")
+
+ for part in module_parts:
+ if (part, original_name) in RUNTIME_VARYING_CALLS:
+ return True
+
+ return False
+
+
+class DAGTaskDetector:
+ """
+ Detector dedicated to identifying DAG and Task constructors.
+
+ This detector identifies when code is creating DAG or Task objects
+ in Airflow. It needs to handle both traditional class instantiation and decorator styles.
+ """
+
+ def __init__(self, from_imports: dict):
+ self.from_imports = from_imports
+ self.dag_instances: set[str] = set()
+ self.is_in_dag_context: bool = False
+
+ def is_dag_constructor(self, node: ast.Call) -> bool:
+ """Check if a call is a DAG constructor."""
+ if not isinstance(node.func, ast.Name):
+ return False
+
+ func_name = node.func.id
+
+ # "from airflow import DAG" form or "from airflow.decorator import dag"
+ if func_name in self.from_imports:
+ module, original = self.from_imports[func_name]
+ if (module == "airflow" or module.startswith("airflow.")) and original in ("DAG", "dag"):
+ return True
+
+ return False
+
+ def is_task_constructor(self, node: ast.Call) -> bool:
+ """
+ Check if a call is a Task constructor.
+
+ Criteria:
+ 1. All calls within a DAG with block
+ 2. Calls that receive a DAG instance as an argument (dag=...)
+ """
+ # Inside DAG with block
+ if self.is_in_dag_context:
+ return True
+
+ # Passing DAG instance as argument
+ for arg in node.args:
+ if isinstance(arg, ast.Name) and arg.id in self.dag_instances:
+ return True
+
+ for keyword in node.keywords:
+ if keyword.value and isinstance(keyword.value, ast.Name):
+ if keyword.value.id in self.dag_instances:
+ return True
+
+ return False
+
+ def register_dag_instance(self, var_name: str):
+ """Register a DAG instance variable name."""
+ self.dag_instances.add(var_name)
+
+ def enter_dag_context(self):
+ """Enter a DAG with block."""
+ self.is_in_dag_context = True
+
+ def exit_dag_context(self):
+ """Exit a DAG with block."""
+ self.is_in_dag_context = False
+
+
+class AirflowRuntimeVaryingValueChecker(ast.NodeVisitor):
+ """
+ Main visitor class to detect runtime-varying value usage in Airflow DAG/Task.
+
+ Main responsibilities:
+ - Traverse AST and visit nodes
+ - Detect DAG/Task creation
+ - Track runtime-varying values and generate warnings
Review Comment:
and other DAG usage
##########
airflow-core/src/airflow/models/dagwarning.py:
##########
@@ -103,3 +103,4 @@ class DagWarningType(str, Enum):
ASSET_CONFLICT = "asset conflict"
NONEXISTENT_POOL = "non-existent pool"
+ PARSING_ERROR = "parsing error"
Review Comment:
This is more like a warning instead of an error?
##########
airflow-core/src/airflow/utils/static_checker.py:
##########
@@ -0,0 +1,468 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "TASK constructor"
+ DAG_CONSTRUCTOR = "DAG constructor"
Review Comment:
```suggestion
TASK_CONSTRUCTOR = "Task constructor"
DAG_CONSTRUCTOR = "Dag constructor"
```
Is there a reason we use upper case?
##########
airflow-core/src/airflow/utils/static_checker.py:
##########
@@ -0,0 +1,468 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "TASK constructor"
+ DAG_CONSTRUCTOR = "DAG constructor"
+
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+]
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(self, varying_vars: dict, imports: dict, from_imports: dict):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self._is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self._check_fstring_varying(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self._check_collection_varying(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self._check_dict_varying(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def _check_fstring_varying(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ source = self.get_varying_source(value.value)
+ if source:
+ return source
+ return None
+
+ def _check_collection_varying(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def _check_dict_varying(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def _is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
+ """Check for runtime-varying calls like now() (when imported via 'from import')."""
+ func_name = func.id
+
+ if func_name in self.from_imports:
+ module, original_name = self.from_imports[func_name]
+ module_parts = module.split(".")
+
+ for part in module_parts:
+ if (part, original_name) in RUNTIME_VARYING_CALLS:
+ return True
+
+ return False
+
+
+class DAGTaskDetector:
+ """
+ Detector dedicated to identifying DAG and Task constructors.
+
+ This detector identifies when code is creating DAG or Task objects
+ in Airflow. It needs to handle both traditional class instantiation and decorator styles.
+ """
+
+ def __init__(self, from_imports: dict):
+ self.from_imports = from_imports
+ self.dag_instances: set[str] = set()
+ self.is_in_dag_context: bool = False
+
+ def is_dag_constructor(self, node: ast.Call) -> bool:
+ """Check if a call is a DAG constructor."""
+ if not isinstance(node.func, ast.Name):
+ return False
+
+ func_name = node.func.id
+
+ # "from airflow import DAG" form or "from airflow.decorator import dag"
+ if func_name in self.from_imports:
+ module, original = self.from_imports[func_name]
+ if (module == "airflow" or module.startswith("airflow.")) and original in ("DAG", "dag"):
+ return True
+
+ return False
+
+ def is_task_constructor(self, node: ast.Call) -> bool:
+ """
+ Check if a call is a Task constructor.
+
+ Criteria:
+ 1. All calls within a DAG with block
+ 2. Calls that receive a DAG instance as an argument (dag=...)
+ """
+ # Inside DAG with block
+ if self.is_in_dag_context:
+ return True
+
+ # Passing DAG instance as argument
+ for arg in node.args:
+ if isinstance(arg, ast.Name) and arg.id in self.dag_instances:
+ return True
+
+ for keyword in node.keywords:
+ if keyword.value and isinstance(keyword.value, ast.Name):
+ if keyword.value.id in self.dag_instances:
+ return True
+
+ return False
+
+ def register_dag_instance(self, var_name: str):
+ """Register a DAG instance variable name."""
+ self.dag_instances.add(var_name)
+
+ def enter_dag_context(self):
+ """Enter a DAG with block."""
+ self.is_in_dag_context = True
+
+ def exit_dag_context(self):
+ """Exit a DAG with block."""
+ self.is_in_dag_context = False
+
+
+class AirflowRuntimeVaryingValueChecker(ast.NodeVisitor):
+ """
+ Main visitor class to detect runtime-varying value usage in Airflow DAG/Task.
+
+ Main responsibilities:
+ - Traverse AST and visit nodes
+ - Detect DAG/Task creation
+ - Track runtime-varying values and generate warnings
+ """
+
+ def __init__(self):
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.imports: dict[str, str] = {}
+ self.from_imports: dict[str, tuple[str, str]] = {}
+ self.varying_vars: dict[str, tuple[int, str]] = {}
+
+ # Helper objects
+ self.value_analyzer = RuntimeVaryingValueAnalyzer(self.varying_vars, self.imports, self.from_imports)
+ self.dag_detector = DAGTaskDetector(self.from_imports)
+
+ def visit_Import(self, node: ast.Import):
+ """Process import statements."""
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.imports[name] = alias.name
+
+ def visit_ImportFrom(self, node: ast.ImportFrom):
+ """Process from ... import statements."""
+ if node.module:
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.from_imports[name] = (node.module, alias.name)
+
+ def visit_Assign(self, node: ast.Assign):
+ """
+ Process variable assignments.
+
+ Checks:
+ 1. DAG instance assignment
+ 2. Task instance assignment
+ 3. Runtime-varying value assignment
+ """
+ value = node.value
+
+ # DAG constructor
+ if isinstance(value, ast.Call) and self.dag_detector.is_dag_constructor(value):
+ self._register_dag_instances(node.targets)
+ self._check_and_warn(value, WarningContext.DAG_CONSTRUCTOR)
+
+ # Task constructor
+ elif isinstance(value, ast.Call) and self.dag_detector.is_task_constructor(value):
+ self._check_and_warn(value, WarningContext.TASK_CONSTRUCTOR)
+
+ # Track runtime-varying values
+ else:
+ self._track_varying_assignment(node)
+
+ def visit_Call(self, node: ast.Call):
+ """
+ Process function calls.
+
+ Check not assign but just call the function or dag definition via decorator.
+ """
+ if self.dag_detector.is_dag_constructor(node):
+ self._check_and_warn(node, WarningContext.DAG_CONSTRUCTOR)
+
+ elif self.dag_detector.is_task_constructor(node):
+ self._check_and_warn(node, WarningContext.TASK_CONSTRUCTOR)
+
+ def visit_For(self, node: ast.For):
+ """
+ Process for statements.
+
+ Check if iteration target contains runtime-varying values.
+ """
+ # check the iterator value is runtime-varying
+ # iter is runtime-varying : for iter in [datetime.now(), 3]
+ varying_source = self.value_analyzer.get_varying_source(node.iter)
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars[node.target.id] = (node.lineno, varying_source)
+
+ for body in node.body:
+ self.visit(body)
+
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars.pop(node.target.id)
+
+ def visit_With(self, node: ast.With):
+ """
+ Process with statements.
+
+ Detect DAG context manager.
+ """
+ is_with_dag_context = False
+ for item in node.items:
+ # check if the dag instance exists in with context
+ self.visit(item)
+ if isinstance(item.context_expr, ast.Call):
+ if self.dag_detector.is_dag_constructor(item.context_expr):
+ # check the value defined in with statement to detect entering DAG with block
+ is_with_dag_context = True
+
+ if is_with_dag_context:
+ self.dag_detector.enter_dag_context()
+
+ for body in node.body:
+ self.visit(body)
+
+ # Exit DAG with block
+ self.dag_detector.exit_dag_context()
+
+ def _register_dag_instances(self, targets: list):
+ """Register DAG instance variable names."""
+ for target in targets:
+ if isinstance(target, ast.Name):
+ self.dag_detector.register_dag_instance(target.id)
+
+ def _track_varying_assignment(self, node: ast.Assign):
+ """Track variable assignments with runtime-varying values."""
+ varying_source = self.value_analyzer.get_varying_source(node.value)
+ if varying_source:
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ self.varying_vars[target.id] = (node.lineno, varying_source)
+
+ def _check_and_warn(self, call: ast.Call, context: WarningContext):
+ """Check function call arguments and generate warnings."""
+ varying_source = self.value_analyzer.get_varying_source(call)
+ if varying_source:
+ self.warnings.append(
+ RuntimeVaryingValueWarning(
+ line=call.lineno,
+ col=call.col_offset,
+ code=ast.unparse(call),
+ message=self._get_warning_message(context),
+ )
+ )
+
+ def _get_warning_message(self, context: WarningContext):
+ """Get appropriate warning message based on context."""
+ if self.dag_detector.is_in_dag_context and context == WarningContext.TASK_CONSTRUCTOR:
+ return "Don't use runtime-varying values as function arguments within with DAG block"
+ return f"Don't use runtime-varying value as argument in {context.value}"
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "⚠️ This DAG uses runtime-variable values in DAG construction.",
+ "⚠️ It causes the DAG version to increase as values change on every DAG parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.append(f"Line {w.line}, Col {w.col}")
+ lines.append(f"Code: {w.code}")
+ lines.append(f"Issue: {w.message}")
+ lines.append("")
+
+ return "\n".join(lines)
+
+
+def check_dag_file_static(file_path):
Review Comment:
```suggestion
def check_dag_file_static(file_path) -> str | None:
```
##########
airflow-core/src/airflow/utils/static_checker.py:
##########
@@ -0,0 +1,468 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "TASK constructor"
+ DAG_CONSTRUCTOR = "DAG constructor"
+
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+]
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(self, varying_vars: dict, imports: dict, from_imports: dict):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self._is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self._check_fstring_varying(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self._check_collection_varying(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self._check_dict_varying(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def _check_fstring_varying(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ source = self.get_varying_source(value.value)
+ if source:
+ return source
+ return None
+
+ def _check_collection_varying(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def _check_dict_varying(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def _is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
+ """Check for runtime-varying calls like now() (when imported via 'from import')."""
+ func_name = func.id
+
+ if func_name in self.from_imports:
+ module, original_name = self.from_imports[func_name]
+ module_parts = module.split(".")
+
+ for part in module_parts:
+ if (part, original_name) in RUNTIME_VARYING_CALLS:
+ return True
+
+ return False
+
+
+class DAGTaskDetector:
+ """
+ Detector dedicated to identifying DAG and Task constructors.
+
+ This detector identifies when code is creating DAG or Task objects
+ in Airflow. It needs to handle both traditional class instantiation and decorator styles.
+ """
+
+ def __init__(self, from_imports: dict):
+ self.from_imports = from_imports
+ self.dag_instances: set[str] = set()
+ self.is_in_dag_context: bool = False
+
+ def is_dag_constructor(self, node: ast.Call) -> bool:
+ """Check if a call is a DAG constructor."""
+ if not isinstance(node.func, ast.Name):
+ return False
+
+ func_name = node.func.id
+
+ # "from airflow import DAG" form or "from airflow.decorator import dag"
+ if func_name in self.from_imports:
+ module, original = self.from_imports[func_name]
+ if (module == "airflow" or module.startswith("airflow.")) and original in ("DAG", "dag"):
+ return True
+
+ return False
+
+ def is_task_constructor(self, node: ast.Call) -> bool:
+ """
+ Check if a call is a Task constructor.
+
+ Criteria:
+ 1. All calls within a DAG with block
+ 2. Calls that receive a DAG instance as an argument (dag=...)
+ """
+ # Inside DAG with block
+ if self.is_in_dag_context:
+ return True
+
+ # Passing DAG instance as argument
+ for arg in node.args:
+ if isinstance(arg, ast.Name) and arg.id in self.dag_instances:
+ return True
+
+ for keyword in node.keywords:
+ if keyword.value and isinstance(keyword.value, ast.Name):
+ if keyword.value.id in self.dag_instances:
+ return True
+
+ return False
+
+ def register_dag_instance(self, var_name: str):
+ """Register a DAG instance variable name."""
+ self.dag_instances.add(var_name)
+
+ def enter_dag_context(self):
+ """Enter a DAG with block."""
+ self.is_in_dag_context = True
+
+ def exit_dag_context(self):
+ """Exit a DAG with block."""
+ self.is_in_dag_context = False
+
+
+class AirflowRuntimeVaryingValueChecker(ast.NodeVisitor):
+ """
+ Main visitor class to detect runtime-varying value usage in Airflow DAG/Task.
+
+ Main responsibilities:
+ - Traverse AST and visit nodes
+ - Detect DAG/Task creation
+ - Track runtime-varying values and generate warnings
+ """
+
+ def __init__(self):
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.imports: dict[str, str] = {}
+ self.from_imports: dict[str, tuple[str, str]] = {}
+ self.varying_vars: dict[str, tuple[int, str]] = {}
+
+ # Helper objects
+ self.value_analyzer = RuntimeVaryingValueAnalyzer(self.varying_vars, self.imports, self.from_imports)
+ self.dag_detector = DAGTaskDetector(self.from_imports)
+
+ def visit_Import(self, node: ast.Import):
+ """Process import statements."""
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.imports[name] = alias.name
+
+ def visit_ImportFrom(self, node: ast.ImportFrom):
+ """Process from ... import statements."""
+ if node.module:
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.from_imports[name] = (node.module, alias.name)
+
+ def visit_Assign(self, node: ast.Assign):
+ """
+ Process variable assignments.
+
+ Checks:
+ 1. DAG instance assignment
+ 2. Task instance assignment
+ 3. Runtime-varying value assignment
+ """
+ value = node.value
+
+ # DAG constructor
+ if isinstance(value, ast.Call) and self.dag_detector.is_dag_constructor(value):
+ self._register_dag_instances(node.targets)
+ self._check_and_warn(value, WarningContext.DAG_CONSTRUCTOR)
+
+ # Task constructor
+ elif isinstance(value, ast.Call) and self.dag_detector.is_task_constructor(value):
+ self._check_and_warn(value, WarningContext.TASK_CONSTRUCTOR)
+
+ # Track runtime-varying values
+ else:
+ self._track_varying_assignment(node)
+
+ def visit_Call(self, node: ast.Call):
+ """
+ Process function calls.
+
+ Check not assign but just call the function or dag definition via decorator.
+ """
+ if self.dag_detector.is_dag_constructor(node):
+ self._check_and_warn(node, WarningContext.DAG_CONSTRUCTOR)
+
+ elif self.dag_detector.is_task_constructor(node):
+ self._check_and_warn(node, WarningContext.TASK_CONSTRUCTOR)
+
+ def visit_For(self, node: ast.For):
+ """
+ Process for statements.
+
+ Check if iteration target contains runtime-varying values.
+ """
+ # check the iterator value is runtime-varying
+ # iter is runtime-varying : for iter in [datetime.now(), 3]
+ varying_source = self.value_analyzer.get_varying_source(node.iter)
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars[node.target.id] = (node.lineno, varying_source)
+
+ for body in node.body:
+ self.visit(body)
+
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars.pop(node.target.id)
+
+ def visit_With(self, node: ast.With):
+ """
+ Process with statements.
+
+ Detect DAG context manager.
+ """
+ is_with_dag_context = False
+ for item in node.items:
+ # check if the dag instance exists in with context
+ self.visit(item)
+ if isinstance(item.context_expr, ast.Call):
+ if self.dag_detector.is_dag_constructor(item.context_expr):
+ # check the value defined in with statement to detect entering DAG with block
+ is_with_dag_context = True
+
+ if is_with_dag_context:
+ self.dag_detector.enter_dag_context()
+
+ for body in node.body:
+ self.visit(body)
+
+ # Exit DAG with block
+ self.dag_detector.exit_dag_context()
+
+ def _register_dag_instances(self, targets: list):
+ """Register DAG instance variable names."""
+ for target in targets:
+ if isinstance(target, ast.Name):
+ self.dag_detector.register_dag_instance(target.id)
+
+ def _track_varying_assignment(self, node: ast.Assign):
+ """Track variable assignments with runtime-varying values."""
+ varying_source = self.value_analyzer.get_varying_source(node.value)
+ if varying_source:
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ self.varying_vars[target.id] = (node.lineno, varying_source)
+
+ def _check_and_warn(self, call: ast.Call, context: WarningContext):
+ """Check function call arguments and generate warnings."""
+ varying_source = self.value_analyzer.get_varying_source(call)
+ if varying_source:
+ self.warnings.append(
+ RuntimeVaryingValueWarning(
+ line=call.lineno,
+ col=call.col_offset,
+ code=ast.unparse(call),
+ message=self._get_warning_message(context),
+ )
+ )
+
+ def _get_warning_message(self, context: WarningContext):
+ """Get appropriate warning message based on context."""
+ if self.dag_detector.is_in_dag_context and context == WarningContext.TASK_CONSTRUCTOR:
+ return "Don't use runtime-varying values as function arguments within with DAG block"
+ return f"Don't use runtime-varying value as argument in {context.value}"
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "⚠️ This DAG uses runtime-variable values in DAG construction.",
+ "⚠️ It causes the DAG version to increase as values change on every DAG parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.append(f"Line {w.line}, Col {w.col}")
+ lines.append(f"Code: {w.code}")
+ lines.append(f"Issue: {w.message}")
+ lines.append("")
+
+ return "\n".join(lines)
+
+
+def check_dag_file_static(file_path):
+ try:
+ parsed = ast.parse(Path(file_path).read_bytes())
+ except Exception:
Review Comment:
Is it possible to catch a more specific exception here?
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3678789299
Taking your points together, it sounds like defining the configuration with three options would make sense. Please let me know if you have any objections or alternative suggestions.
```
AIRFLOW__DAG_PROCESSOR__STATIC_CHECK_LEVEL = warn # off | warn | error
```
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3704364183
@potiuk Yes, I think it would be good to work on that task in a separate PR.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2644095699
##########
airflow-core/src/airflow/utils/static_checker.py:
##########
@@ -0,0 +1,508 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+class StaticCheckerResult:
Review Comment:
Even here and module name -> I would say it's better if that whole PR focuses on "dag stability" or similar checks - rather than generic "static checks" -> yes it is done via static anaylysis of the AST, but there are so many different static checks that could even likely be done in different moments, with different switches and different "off/error/warning" values for the switches, that generically naming it "static checks" now is too early.
I would say when we see the need for **third** such check we should see if we can implement some generic framework for static checks execution and error raising - but at this stage it's purely about "Dag stability".
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2635906096
##########
airflow-core/src/airflow/utils/static_checker.py:
##########
@@ -0,0 +1,468 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+RUNTIME_VARYING_CALLS = [
Review Comment:
Probably should cover pendulum datetimes etc too?
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3661256034
I'd love some other pair of eyes on it, but I think this is a great start for good approach to solve the problem with varying Dags. I think we need to think a bit more on next steps and explore different kinds of UX for that, also I think such mechanism should have a way to suppress such warnings (for example by comment in the Dag) - but other than that - it looks great.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3665192870
> I think we should have an opt-out solution for those that doesn't mind the dag being non deterministic.
I agree that too. I think there are two options
- making config section for disabling it (e.g. AIRFLOW__DAG_PROCESSOR_ENABLE_PARSING_WARNING)
- as Jarek said, suppress it by comment in the Dag
WDYT?
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3693796275
> @Lee-W @ephraimbuddy @jedcunningham Can you give more reivew for this?
There is a holiday period, so I guess it might be a bit later ;)
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2664977281
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def get_varying_fstring(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ if source := self.get_varying_source(value.value):
+ return source
+ return None
+
+ def get_varying_collection(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def get_varying_dict(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
+ """Check for runtime-varying calls like now() (when imported via 'from import')."""
+ func_name = func.id
+
+ if func_name in self.from_imports:
+ module, original_name = self.from_imports[func_name]
+ module_parts = module.split(".")
+
+ for part in module_parts:
+ if (part, original_name) in RUNTIME_VARYING_CALLS:
+ return True
+
+ return False
+
+
+class DagTaskDetector:
+ """
+ Detector dedicated to identifying Dag and Task constructors.
+
+ This detector identifies when code is creating Dag or Task objects
+ in Airflow. It needs to handle both traditional class instantiation and decorator styles.
+ """
+
+ def __init__(self, from_imports: dict):
+ self.from_imports = from_imports
+ self.dag_instances: set[str] = set()
+ self.is_in_dag_context: bool = False
+
+ def is_dag_constructor(self, node: ast.Call) -> bool:
+ """Check if a call is a Dag constructor."""
+ if not isinstance(node.func, ast.Name):
+ return False
+
+ func_name = node.func.id
+
+ # "from airflow import DAG" form or "from airflow.decorator import dag"
+ if func_name in self.from_imports:
+ module, original = self.from_imports[func_name]
+ if (module == "airflow" or module.startswith("airflow.")) and original in ("DAG", "dag"):
+ return True
+
+ return False
+
+ def is_task_constructor(self, node: ast.Call) -> bool:
+ """
+ Check if a call is a Task constructor.
+
+ Criteria:
+ 1. All calls within a Dag with block
+ 2. Calls that receive a Dag instance as an argument (dag=...)
+ """
+ # Inside Dag with block
+ if self.is_in_dag_context:
+ return True
+
+ # Passing Dag instance as argument
+ for arg in node.args:
+ if isinstance(arg, ast.Name) and arg.id in self.dag_instances:
+ return True
+
+ for keyword in node.keywords:
+ if keyword.value and isinstance(keyword.value, ast.Name):
+ if keyword.value.id in self.dag_instances:
+ return True
+
+ return False
+
+ def register_dag_instance(self, var_name: str):
+ """Register a Dag instance variable name."""
+ self.dag_instances.add(var_name)
+
+ def enter_dag_context(self):
+ """Enter a Dag with block."""
+ self.is_in_dag_context = True
+
+ def exit_dag_context(self):
+ """Exit a Dag with block."""
+ self.is_in_dag_context = False
+
+
+class AirflowRuntimeVaryingValueChecker(ast.NodeVisitor):
+ """
+ Main visitor class to detect runtime-varying value usage in Airflow Dag/Task.
+
+ Main responsibilities:
+ - Traverse AST and visit nodes
+ - Detect Dag/Task creation
+ - Track runtime-varying values and generate warnings
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel = DagStabilityCheckLevel.warning):
+ self.static_check_result: DagStabilityCheckerResult = DagStabilityCheckerResult(
+ check_level=check_level
+ )
+ self.imports: dict[str, str] = {}
+ self.from_imports: dict[str, tuple[str, str]] = {}
+ self.varying_vars: dict[str, tuple[int, str]] = {}
+ self.check_level = check_level
+
+ # Helper objects
+ self.value_analyzer = RuntimeVaryingValueAnalyzer(self.varying_vars, self.imports, self.from_imports)
+ self.dag_detector = DagTaskDetector(self.from_imports)
+
+ def visit_Import(self, node: ast.Import):
+ """Process import statements."""
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.imports[name] = alias.name
+
+ def visit_ImportFrom(self, node: ast.ImportFrom):
+ """Process from ... import statements."""
+ if node.module:
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.from_imports[name] = (node.module, alias.name)
+
+ def visit_Assign(self, node: ast.Assign):
+ """
+ Process variable assignments.
+
+ Checks:
+ 1. Dag instance assignment
+ 2. Task instance assignment
+ 3. Runtime-varying value assignment
+ """
+ value = node.value
+
+ # Dag constructor
+ if isinstance(value, ast.Call) and self.dag_detector.is_dag_constructor(value):
+ self._register_dag_instances(node.targets)
+ self._check_and_warn(value, WarningContext.DAG_CONSTRUCTOR)
+
+ # Task constructor
+ elif isinstance(value, ast.Call) and self.dag_detector.is_task_constructor(value):
+ self._check_and_warn(value, WarningContext.TASK_CONSTRUCTOR)
+
+ # Track runtime-varying values
+ else:
+ self._track_varying_assignment(node)
+
+ def visit_Call(self, node: ast.Call):
+ """
+ Process function calls.
+
+ Check not assign but just call the function or Dag definition via decorator.
+ """
+ if self.dag_detector.is_dag_constructor(node):
+ self._check_and_warn(node, WarningContext.DAG_CONSTRUCTOR)
+
+ elif self.dag_detector.is_task_constructor(node):
+ self._check_and_warn(node, WarningContext.TASK_CONSTRUCTOR)
+
+ def visit_For(self, node: ast.For):
+ """
+ Process for statements.
+
+ Check if iteration target contains runtime-varying values.
+ """
+ # check the iterator value is runtime-varying
+ # iter is runtime-varying : for iter in [datetime.now(), 3]
+ varying_source = self.value_analyzer.get_varying_source(node.iter)
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars[node.target.id] = (node.lineno, varying_source)
+
+ for body in node.body:
+ self.visit(body)
+
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars.pop(node.target.id)
+
+ def visit_With(self, node: ast.With):
+ """
+ Process with statements.
+
+ Detect Dag context manager.
+ """
+ is_with_dag_context = False
+ for item in node.items:
+ # check if the Dag instance exists in with context
+ self.visit(item)
+ if isinstance(item.context_expr, ast.Call):
+ if self.dag_detector.is_dag_constructor(item.context_expr):
+ # check the value defined in with statement to detect entering Dag with block
+ is_with_dag_context = True
+
+ if is_with_dag_context:
+ self.dag_detector.enter_dag_context()
+
+ for body in node.body:
+ self.visit(body)
+
+ # Exit Dag with block
+ self.dag_detector.exit_dag_context()
+
+ def _register_dag_instances(self, targets: list):
+ """Register Dag instance variable names."""
+ for target in targets:
+ if isinstance(target, ast.Name):
+ self.dag_detector.register_dag_instance(target.id)
+
+ def _track_varying_assignment(self, node: ast.Assign):
+ """Track variable assignments with runtime-varying values."""
+ varying_source = self.value_analyzer.get_varying_source(node.value)
+ if varying_source:
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ self.varying_vars[target.id] = (node.lineno, varying_source)
+
+ def _check_and_warn(self, call: ast.Call, context: WarningContext):
+ """Check function call arguments and generate warnings."""
+ varying_source = self.value_analyzer.get_varying_source(call)
+ if varying_source:
+ self.static_check_result.warnings.append(
+ RuntimeVaryingValueWarning(
+ line=call.lineno,
+ col=call.col_offset,
+ code=ast.unparse(call),
+ message=self._get_warning_message(context),
+ )
+ )
+
+ def _get_warning_message(self, context: WarningContext):
+ """Get appropriate warning message based on context."""
+ if self.dag_detector.is_in_dag_context and context == WarningContext.TASK_CONSTRUCTOR:
+ return "Don't use runtime-varying values as function arguments within with Dag block"
+ return f"Don't use runtime-varying value as argument in {context.value}"
+
+
+def check_dag_file_stability(file_path) -> DagStabilityCheckerResult:
+ from airflow.configuration import conf
+
+ check_level = conf.getenum("dag_processor", "dag_stability_check_level", DagStabilityCheckLevel)
Review Comment:
https://github.com/apache/airflow/blob/main/shared/configuration/src/airflow_shared/configuration/parser.py#L1096
It currently exists in main (it's a method I added in a previous [PR](https://github.com/apache/airflow/pull/56821))
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3764567377
@potiuk @pierrejeambrun
Oh, I see. I misunderstood. I've checked everything and marked them as resolved.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3726638151
I've changed the config section `dag_version_inflation_check_level` and related names! thanks.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3677982090
I think you may be mixing up the 2 different versions we have now.
Bundle versioning: The deployment manager can choose to use a versioned dag bundle (and likewise the dag author can also use `disable_bundle_versioning`) to control whether versioned dag code is used when running a task. This can be controlled. But it only controls code used to execute tasks.
Dag versioning: a.k.a keep history of serdags used in runs. This is always on - there is no mechanism to disable it. This is what the static check here is covering. This powers the UI to show what the dag looked like historically.
> something that we've been also doing in Airflow 2 and it never created huge issue (except a bit more often DB update for those ?
Depends on perspective I guess. I'd argue that tasks disappearing from the UI when dag structure changes is pretty bad. But either way, there is currently no way to control that, and that was by design.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2626911875
##########
airflow-core/src/airflow/dag_processing/processor.py:
##########
@@ -509,10 +513,6 @@ def start( # type: ignore[override]
client: Client,
**kwargs,
) -> Self:
- logger = kwargs["logger"]
-
- _pre_import_airflow_modules(os.fspath(path), logger)
Review Comment:
OMG! Just mistake.. thanks for checking!
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2660908546
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,510 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a DAG file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level):
Review Comment:
```suggestion
def __init__(self, check_level: Literal["warning", "error"]):
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,510 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a DAG file.
Review Comment:
```suggestion
Represents the result of stability analysis on a Dag file.
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,510 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a DAG file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level):
+ self.check_level: str = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "⚠️ This Dag uses runtime-variable values in Dag construction.",
+ "⚠️ It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.append(f"Line {w.line}, Col {w.col}")
+ lines.append(f"Code: {w.code}")
+ lines.append(f"Issue: {w.message}")
+ lines.append("")
+
+ if self.runtime_varying_values:
+ lines.append("️⚠️ Don't use the variables as arguments in DAG/Task constructors:")
+ # Sort by line number
+ sorted_vars = sorted(self.runtime_varying_values.items(), key=lambda x: x[1][0])
+ for var_name, (line, source) in sorted_vars:
+ lines.append(f" Line {line}: '{var_name}' related '{source}'")
+ lines.append("")
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids):
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != "warning":
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != "error":
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(self, varying_vars: dict, imports: dict, from_imports: dict):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self._is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self._check_fstring_varying(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self._check_collection_varying(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self._check_dict_varying(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def _check_fstring_varying(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ source = self.get_varying_source(value.value)
+ if source:
+ return source
+ return None
+
+ def _check_collection_varying(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def _check_dict_varying(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def _is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
+ """Check for runtime-varying calls like now() (when imported via 'from import')."""
+ func_name = func.id
+
+ if func_name in self.from_imports:
+ module, original_name = self.from_imports[func_name]
+ module_parts = module.split(".")
+
+ for part in module_parts:
+ if (part, original_name) in RUNTIME_VARYING_CALLS:
+ return True
+
+ return False
+
+
+class DagTaskDetector:
+ """
+ Detector dedicated to identifying Dag and Task constructors.
+
+ This detector identifies when code is creating Dag or Task objects
+ in Airflow. It needs to handle both traditional class instantiation and decorator styles.
+ """
+
+ def __init__(self, from_imports: dict):
+ self.from_imports = from_imports
+ self.dag_instances: set[str] = set()
+ self.is_in_dag_context: bool = False
+
+ def is_dag_constructor(self, node: ast.Call) -> bool:
+ """Check if a call is a DAG constructor."""
+ if not isinstance(node.func, ast.Name):
+ return False
+
+ func_name = node.func.id
+
+ # "from airflow import DAG" form or "from airflow.decorator import dag"
+ if func_name in self.from_imports:
+ module, original = self.from_imports[func_name]
+ if (module == "airflow" or module.startswith("airflow.")) and original in ("DAG", "dag"):
+ return True
+
+ return False
+
+ def is_task_constructor(self, node: ast.Call) -> bool:
+ """
+ Check if a call is a Task constructor.
+
+ Criteria:
+ 1. All calls within a DAG with block
+ 2. Calls that receive a DAG instance as an argument (dag=...)
+ """
+ # Inside DAG with block
+ if self.is_in_dag_context:
+ return True
+
+ # Passing DAG instance as argument
+ for arg in node.args:
+ if isinstance(arg, ast.Name) and arg.id in self.dag_instances:
+ return True
+
+ for keyword in node.keywords:
+ if keyword.value and isinstance(keyword.value, ast.Name):
+ if keyword.value.id in self.dag_instances:
+ return True
+
+ return False
+
+ def register_dag_instance(self, var_name: str):
+ """Register a DAG instance variable name."""
+ self.dag_instances.add(var_name)
+
+ def enter_dag_context(self):
+ """Enter a DAG with block."""
+ self.is_in_dag_context = True
+
+ def exit_dag_context(self):
+ """Exit a DAG with block."""
+ self.is_in_dag_context = False
+
+
+class AirflowRuntimeVaryingValueChecker(ast.NodeVisitor):
+ """
+ Main visitor class to detect runtime-varying value usage in Airflow DAG/Task.
Review Comment:
```suggestion
Main visitor class to detect runtime-varying value usage in Airflow Dag/Task.
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,510 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a DAG file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level):
+ self.check_level: str = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "⚠️ This Dag uses runtime-variable values in Dag construction.",
+ "⚠️ It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.append(f"Line {w.line}, Col {w.col}")
+ lines.append(f"Code: {w.code}")
+ lines.append(f"Issue: {w.message}")
+ lines.append("")
+
+ if self.runtime_varying_values:
+ lines.append("️⚠️ Don't use the variables as arguments in DAG/Task constructors:")
+ # Sort by line number
+ sorted_vars = sorted(self.runtime_varying_values.items(), key=lambda x: x[1][0])
+ for var_name, (line, source) in sorted_vars:
+ lines.append(f" Line {line}: '{var_name}' related '{source}'")
+ lines.append("")
Review Comment:
```suggestion
lines.extend(
[
"️⚠️ Don't use the variables as arguments in DAG/Task constructors:",
*(
f" Line {line}: '{var_name}' related '{source}'"
for var_name, (line, source) in sorted(
self.runtime_varying_values.items(),
key=lambda x: x[1][0],
)
),
"",
]
)
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,510 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a DAG file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level):
+ self.check_level: str = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "⚠️ This Dag uses runtime-variable values in Dag construction.",
+ "⚠️ It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.append(f"Line {w.line}, Col {w.col}")
+ lines.append(f"Code: {w.code}")
+ lines.append(f"Issue: {w.message}")
+ lines.append("")
Review Comment:
```suggestion
lines.extend(
[
f"Line {w.line}, Col {w.col}",
f"Code: {w.code}",
f"Issue: {w.message}",
"",
]
)
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,510 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a DAG file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level):
+ self.check_level: str = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "⚠️ This Dag uses runtime-variable values in Dag construction.",
+ "⚠️ It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.append(f"Line {w.line}, Col {w.col}")
+ lines.append(f"Code: {w.code}")
+ lines.append(f"Issue: {w.message}")
+ lines.append("")
+
+ if self.runtime_varying_values:
+ lines.append("️⚠️ Don't use the variables as arguments in DAG/Task constructors:")
+ # Sort by line number
+ sorted_vars = sorted(self.runtime_varying_values.items(), key=lambda x: x[1][0])
+ for var_name, (line, source) in sorted_vars:
+ lines.append(f" Line {line}: '{var_name}' related '{source}'")
+ lines.append("")
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids):
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != "warning":
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != "error":
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(self, varying_vars: dict, imports: dict, from_imports: dict):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self._is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self._check_fstring_varying(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self._check_collection_varying(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self._check_dict_varying(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def _check_fstring_varying(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ source = self.get_varying_source(value.value)
+ if source:
+ return source
+ return None
+
+ def _check_collection_varying(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def _check_dict_varying(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def _is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
+ """Check for runtime-varying calls like now() (when imported via 'from import')."""
+ func_name = func.id
+
+ if func_name in self.from_imports:
+ module, original_name = self.from_imports[func_name]
+ module_parts = module.split(".")
+
+ for part in module_parts:
+ if (part, original_name) in RUNTIME_VARYING_CALLS:
+ return True
+
+ return False
+
+
+class DagTaskDetector:
+ """
+ Detector dedicated to identifying Dag and Task constructors.
+
+ This detector identifies when code is creating Dag or Task objects
+ in Airflow. It needs to handle both traditional class instantiation and decorator styles.
+ """
+
+ def __init__(self, from_imports: dict):
+ self.from_imports = from_imports
+ self.dag_instances: set[str] = set()
+ self.is_in_dag_context: bool = False
+
+ def is_dag_constructor(self, node: ast.Call) -> bool:
+ """Check if a call is a DAG constructor."""
+ if not isinstance(node.func, ast.Name):
+ return False
+
+ func_name = node.func.id
+
+ # "from airflow import DAG" form or "from airflow.decorator import dag"
+ if func_name in self.from_imports:
+ module, original = self.from_imports[func_name]
+ if (module == "airflow" or module.startswith("airflow.")) and original in ("DAG", "dag"):
+ return True
+
+ return False
+
+ def is_task_constructor(self, node: ast.Call) -> bool:
+ """
+ Check if a call is a Task constructor.
+
+ Criteria:
+ 1. All calls within a DAG with block
+ 2. Calls that receive a DAG instance as an argument (dag=...)
+ """
+ # Inside DAG with block
+ if self.is_in_dag_context:
+ return True
+
+ # Passing DAG instance as argument
+ for arg in node.args:
+ if isinstance(arg, ast.Name) and arg.id in self.dag_instances:
+ return True
+
+ for keyword in node.keywords:
+ if keyword.value and isinstance(keyword.value, ast.Name):
+ if keyword.value.id in self.dag_instances:
+ return True
+
+ return False
+
+ def register_dag_instance(self, var_name: str):
+ """Register a DAG instance variable name."""
+ self.dag_instances.add(var_name)
+
+ def enter_dag_context(self):
+ """Enter a DAG with block."""
+ self.is_in_dag_context = True
+
+ def exit_dag_context(self):
+ """Exit a DAG with block."""
+ self.is_in_dag_context = False
Review Comment:
```suggestion
"""Register a Dag instance variable name."""
self.dag_instances.add(var_name)
def enter_dag_context(self):
"""Enter a Dag with block."""
self.is_in_dag_context = True
def exit_dag_context(self):
"""Exit a Dag with block."""
self.is_in_dag_context = False
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,468 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+RUNTIME_VARYING_CALLS = [
Review Comment:
We can move this list to the top so that we can easily find where to extend
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,510 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a DAG file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level):
+ self.check_level: str = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "⚠️ This Dag uses runtime-variable values in Dag construction.",
+ "⚠️ It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.append(f"Line {w.line}, Col {w.col}")
+ lines.append(f"Code: {w.code}")
+ lines.append(f"Issue: {w.message}")
+ lines.append("")
+
+ if self.runtime_varying_values:
+ lines.append("️⚠️ Don't use the variables as arguments in DAG/Task constructors:")
+ # Sort by line number
+ sorted_vars = sorted(self.runtime_varying_values.items(), key=lambda x: x[1][0])
+ for var_name, (line, source) in sorted_vars:
+ lines.append(f" Line {line}: '{var_name}' related '{source}'")
+ lines.append("")
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids):
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != "warning":
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != "error":
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(self, varying_vars: dict, imports: dict, from_imports: dict):
Review Comment:
let's improve the type annotation a bit here
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,510 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a DAG file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level):
+ self.check_level: str = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "⚠️ This Dag uses runtime-variable values in Dag construction.",
+ "⚠️ It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.append(f"Line {w.line}, Col {w.col}")
+ lines.append(f"Code: {w.code}")
+ lines.append(f"Issue: {w.message}")
+ lines.append("")
+
+ if self.runtime_varying_values:
+ lines.append("️⚠️ Don't use the variables as arguments in DAG/Task constructors:")
+ # Sort by line number
+ sorted_vars = sorted(self.runtime_varying_values.items(), key=lambda x: x[1][0])
+ for var_name, (line, source) in sorted_vars:
+ lines.append(f" Line {line}: '{var_name}' related '{source}'")
+ lines.append("")
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids):
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != "warning":
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != "error":
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(self, varying_vars: dict, imports: dict, from_imports: dict):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self._is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self._check_fstring_varying(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self._check_collection_varying(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self._check_dict_varying(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def _check_fstring_varying(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ source = self.get_varying_source(value.value)
+ if source:
Review Comment:
```suggestion
if source := self.get_varying_source(value.value):
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,510 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a DAG file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level):
+ self.check_level: str = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "⚠️ This Dag uses runtime-variable values in Dag construction.",
+ "⚠️ It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.append(f"Line {w.line}, Col {w.col}")
+ lines.append(f"Code: {w.code}")
+ lines.append(f"Issue: {w.message}")
+ lines.append("")
+
+ if self.runtime_varying_values:
+ lines.append("️⚠️ Don't use the variables as arguments in DAG/Task constructors:")
+ # Sort by line number
+ sorted_vars = sorted(self.runtime_varying_values.items(), key=lambda x: x[1][0])
+ for var_name, (line, source) in sorted_vars:
+ lines.append(f" Line {line}: '{var_name}' related '{source}'")
+ lines.append("")
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids):
Review Comment:
```suggestion
def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, Any]]:
```
or make the dict part a typed dict
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,510 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a DAG file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level):
+ self.check_level: str = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "⚠️ This Dag uses runtime-variable values in Dag construction.",
+ "⚠️ It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.append(f"Line {w.line}, Col {w.col}")
+ lines.append(f"Code: {w.code}")
+ lines.append(f"Issue: {w.message}")
+ lines.append("")
+
+ if self.runtime_varying_values:
+ lines.append("️⚠️ Don't use the variables as arguments in DAG/Task constructors:")
+ # Sort by line number
+ sorted_vars = sorted(self.runtime_varying_values.items(), key=lambda x: x[1][0])
+ for var_name, (line, source) in sorted_vars:
+ lines.append(f" Line {line}: '{var_name}' related '{source}'")
+ lines.append("")
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids):
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != "warning":
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != "error":
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(self, varying_vars: dict, imports: dict, from_imports: dict):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self._is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self._check_fstring_varying(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self._check_collection_varying(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self._check_dict_varying(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def _check_fstring_varying(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ source = self.get_varying_source(value.value)
+ if source:
+ return source
+ return None
+
+ def _check_collection_varying(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def _check_dict_varying(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def _is_runtime_varying_call(self, node: ast.Call) -> bool:
Review Comment:
```suggestion
def is_runtime_varying_call(self, node: ast.Call) -> bool:
```
Why do we need to make these methods private?
##########
airflow-core/src/airflow/config_templates/config.yml:
##########
@@ -2663,6 +2663,22 @@ dag_processor:
type: boolean
example: ~
default: "True"
+ dag_stability_check_level:
+ description: |
+ Controls the behavior of dag stability checker performed before DAG parsing in the dag-processor.
Review Comment:
```suggestion
Controls the behavior of Dag stability checker performed before Dag parsing in the Dag processor.
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,510 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a DAG file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level):
+ self.check_level: str = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "⚠️ This Dag uses runtime-variable values in Dag construction.",
+ "⚠️ It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.append(f"Line {w.line}, Col {w.col}")
+ lines.append(f"Code: {w.code}")
+ lines.append(f"Issue: {w.message}")
+ lines.append("")
+
+ if self.runtime_varying_values:
+ lines.append("️⚠️ Don't use the variables as arguments in DAG/Task constructors:")
+ # Sort by line number
+ sorted_vars = sorted(self.runtime_varying_values.items(), key=lambda x: x[1][0])
+ for var_name, (line, source) in sorted_vars:
+ lines.append(f" Line {line}: '{var_name}' related '{source}'")
+ lines.append("")
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids):
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != "warning":
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != "error":
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(self, varying_vars: dict, imports: dict, from_imports: dict):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self._is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self._check_fstring_varying(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self._check_collection_varying(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self._check_dict_varying(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def _check_fstring_varying(self, node: ast.JoinedStr) -> str | None:
Review Comment:
If we name the first method as `get_varing_source`, should this be named as something like `get_varing_fstring` instead?
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3751016390
@pierrejeambrun doen! thanks!
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3773424254
#protm
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2656770971
##########
airflow-core/src/airflow/dag_processing/processor.py:
##########
@@ -229,8 +242,7 @@ def _parse_file(msg: DagFileParseRequest, log: FilteringBoundLogger) -> DagFileP
fileloc=msg.file,
serialized_dags=serialized_dags,
import_errors=bag.import_errors,
- # TODO: Make `bag.dag_warnings` not return SQLA model objects
- warnings=[],
+ warnings=stability_check_result.get_warning_dag_format_dict(bag.dag_ids),
Review Comment:
Since we update them separately by DagWarningType, there shouldn't be any case where one warning overrides another
https://github.com/apache/airflow/blob/main/airflow-core/src/airflow/dag_processing/collection.py#L268
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2674478338
##########
airflow-core/src/airflow/config_templates/config.yml:
##########
@@ -2663,6 +2663,22 @@ dag_processor:
type: boolean
example: ~
default: "True"
+ dag_stability_check_level:
Review Comment:
I've changed the config section dag_version_inflation_check_level and related names! thanks.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3664762232
> I think we should have an opt-out solution for those that doesn't mind the dag being non deterministic.
Yep, totally agree with this
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2626906812
##########
airflow-core/src/airflow/dag_processing/manager.py:
##########
@@ -1190,13 +1190,17 @@ def process_parse_results(
files_parsed = {(bundle_name, relative_fileloc)}
files_parsed.update(import_errors.keys())
+ warning = parsing_result.warnings
+ if parsing_result.warnings and isinstance(parsing_result.warnings[0], dict):
+ warning = [DagWarning(**warn) for warn in parsing_result.warnings]
Review Comment:
thanks!
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3706902396
> @potiuk Yes, I think it would be good to work on that task in a separate PR.
Also there is apparently a case with callable template fields https://github.com/apache/airflow/issues/60064 that has a pr (failing - it does not solve the problem) in https://github.com/apache/airflow/pull/60065 - so having such "serialized object" check could help in detecting gaps in our implementation .
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "ephraimbuddy (via GitHub)" <gi...@apache.org>.
ephraimbuddy commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2660693206
##########
airflow-core/src/airflow/config_templates/config.yml:
##########
@@ -2663,6 +2663,22 @@ dag_processor:
type: boolean
example: ~
default: "True"
+ dag_stability_check_level:
+ description: |
+ Controls the behavior of dag stability checker performed before DAG parsing in the dag-processor.
Review Comment:
```suggestion
Controls the behavior of dag stability checker performed before Dag parsing in the dag-processor.
```
we now use Dag instead of DAG as discussed in mailing list
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk merged PR #59430:
URL: https://github.com/apache/airflow/pull/59430
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "sjyangkevin (via GitHub)" <gi...@apache.org>.
sjyangkevin commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3776087962
> @sjyangkevin I think we can do something similar on the ruff end side as well. Let's create a AIR304 maybe?
I think it is a good idea. Having this check in ruff can potentially help identify/get the warning early. We could have this AIR304 for suggesting fix for the issue, or probably also use it to suggest DAG writing practices.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "ephraimbuddy (via GitHub)" <gi...@apache.org>.
ephraimbuddy commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2664923712
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def get_varying_fstring(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ if source := self.get_varying_source(value.value):
+ return source
+ return None
+
+ def get_varying_collection(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def get_varying_dict(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
+ """Check for runtime-varying calls like now() (when imported via 'from import')."""
+ func_name = func.id
+
+ if func_name in self.from_imports:
+ module, original_name = self.from_imports[func_name]
+ module_parts = module.split(".")
+
+ for part in module_parts:
+ if (part, original_name) in RUNTIME_VARYING_CALLS:
+ return True
+
+ return False
+
+
+class DagTaskDetector:
+ """
+ Detector dedicated to identifying Dag and Task constructors.
+
+ This detector identifies when code is creating Dag or Task objects
+ in Airflow. It needs to handle both traditional class instantiation and decorator styles.
+ """
+
+ def __init__(self, from_imports: dict):
+ self.from_imports = from_imports
+ self.dag_instances: set[str] = set()
+ self.is_in_dag_context: bool = False
+
+ def is_dag_constructor(self, node: ast.Call) -> bool:
+ """Check if a call is a Dag constructor."""
+ if not isinstance(node.func, ast.Name):
+ return False
+
+ func_name = node.func.id
+
+ # "from airflow import DAG" form or "from airflow.decorator import dag"
+ if func_name in self.from_imports:
+ module, original = self.from_imports[func_name]
+ if (module == "airflow" or module.startswith("airflow.")) and original in ("DAG", "dag"):
+ return True
+
+ return False
+
+ def is_task_constructor(self, node: ast.Call) -> bool:
+ """
+ Check if a call is a Task constructor.
+
+ Criteria:
+ 1. All calls within a Dag with block
+ 2. Calls that receive a Dag instance as an argument (dag=...)
+ """
+ # Inside Dag with block
+ if self.is_in_dag_context:
+ return True
+
+ # Passing Dag instance as argument
+ for arg in node.args:
+ if isinstance(arg, ast.Name) and arg.id in self.dag_instances:
+ return True
+
+ for keyword in node.keywords:
+ if keyword.value and isinstance(keyword.value, ast.Name):
+ if keyword.value.id in self.dag_instances:
+ return True
+
+ return False
+
+ def register_dag_instance(self, var_name: str):
+ """Register a Dag instance variable name."""
+ self.dag_instances.add(var_name)
+
+ def enter_dag_context(self):
+ """Enter a Dag with block."""
+ self.is_in_dag_context = True
+
+ def exit_dag_context(self):
+ """Exit a Dag with block."""
+ self.is_in_dag_context = False
+
+
+class AirflowRuntimeVaryingValueChecker(ast.NodeVisitor):
+ """
+ Main visitor class to detect runtime-varying value usage in Airflow Dag/Task.
+
+ Main responsibilities:
+ - Traverse AST and visit nodes
+ - Detect Dag/Task creation
+ - Track runtime-varying values and generate warnings
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel = DagStabilityCheckLevel.warning):
+ self.static_check_result: DagStabilityCheckerResult = DagStabilityCheckerResult(
+ check_level=check_level
+ )
+ self.imports: dict[str, str] = {}
+ self.from_imports: dict[str, tuple[str, str]] = {}
+ self.varying_vars: dict[str, tuple[int, str]] = {}
+ self.check_level = check_level
+
+ # Helper objects
+ self.value_analyzer = RuntimeVaryingValueAnalyzer(self.varying_vars, self.imports, self.from_imports)
+ self.dag_detector = DagTaskDetector(self.from_imports)
+
+ def visit_Import(self, node: ast.Import):
+ """Process import statements."""
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.imports[name] = alias.name
+
+ def visit_ImportFrom(self, node: ast.ImportFrom):
+ """Process from ... import statements."""
+ if node.module:
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.from_imports[name] = (node.module, alias.name)
+
+ def visit_Assign(self, node: ast.Assign):
+ """
+ Process variable assignments.
+
+ Checks:
+ 1. Dag instance assignment
+ 2. Task instance assignment
+ 3. Runtime-varying value assignment
+ """
+ value = node.value
+
+ # Dag constructor
+ if isinstance(value, ast.Call) and self.dag_detector.is_dag_constructor(value):
+ self._register_dag_instances(node.targets)
+ self._check_and_warn(value, WarningContext.DAG_CONSTRUCTOR)
+
+ # Task constructor
+ elif isinstance(value, ast.Call) and self.dag_detector.is_task_constructor(value):
+ self._check_and_warn(value, WarningContext.TASK_CONSTRUCTOR)
+
+ # Track runtime-varying values
+ else:
+ self._track_varying_assignment(node)
+
+ def visit_Call(self, node: ast.Call):
+ """
+ Process function calls.
+
+ Check not assign but just call the function or Dag definition via decorator.
+ """
+ if self.dag_detector.is_dag_constructor(node):
+ self._check_and_warn(node, WarningContext.DAG_CONSTRUCTOR)
+
+ elif self.dag_detector.is_task_constructor(node):
+ self._check_and_warn(node, WarningContext.TASK_CONSTRUCTOR)
+
+ def visit_For(self, node: ast.For):
+ """
+ Process for statements.
+
+ Check if iteration target contains runtime-varying values.
+ """
+ # check the iterator value is runtime-varying
+ # iter is runtime-varying : for iter in [datetime.now(), 3]
+ varying_source = self.value_analyzer.get_varying_source(node.iter)
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars[node.target.id] = (node.lineno, varying_source)
+
+ for body in node.body:
+ self.visit(body)
+
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars.pop(node.target.id)
+
+ def visit_With(self, node: ast.With):
+ """
+ Process with statements.
+
+ Detect Dag context manager.
+ """
+ is_with_dag_context = False
+ for item in node.items:
+ # check if the Dag instance exists in with context
+ self.visit(item)
+ if isinstance(item.context_expr, ast.Call):
+ if self.dag_detector.is_dag_constructor(item.context_expr):
+ # check the value defined in with statement to detect entering Dag with block
+ is_with_dag_context = True
+
+ if is_with_dag_context:
+ self.dag_detector.enter_dag_context()
+
+ for body in node.body:
+ self.visit(body)
+
+ # Exit Dag with block
+ self.dag_detector.exit_dag_context()
+
+ def _register_dag_instances(self, targets: list):
+ """Register Dag instance variable names."""
+ for target in targets:
+ if isinstance(target, ast.Name):
+ self.dag_detector.register_dag_instance(target.id)
+
+ def _track_varying_assignment(self, node: ast.Assign):
+ """Track variable assignments with runtime-varying values."""
+ varying_source = self.value_analyzer.get_varying_source(node.value)
+ if varying_source:
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ self.varying_vars[target.id] = (node.lineno, varying_source)
+
+ def _check_and_warn(self, call: ast.Call, context: WarningContext):
+ """Check function call arguments and generate warnings."""
+ varying_source = self.value_analyzer.get_varying_source(call)
+ if varying_source:
+ self.static_check_result.warnings.append(
+ RuntimeVaryingValueWarning(
+ line=call.lineno,
+ col=call.col_offset,
+ code=ast.unparse(call),
+ message=self._get_warning_message(context),
+ )
+ )
+
+ def _get_warning_message(self, context: WarningContext):
+ """Get appropriate warning message based on context."""
+ if self.dag_detector.is_in_dag_context and context == WarningContext.TASK_CONSTRUCTOR:
+ return "Don't use runtime-varying values as function arguments within with Dag block"
+ return f"Don't use runtime-varying value as argument in {context.value}"
+
+
+def check_dag_file_stability(file_path) -> DagStabilityCheckerResult:
+ from airflow.configuration import conf
+
+ check_level = conf.getenum("dag_processor", "dag_stability_check_level", DagStabilityCheckLevel)
Review Comment:
There's no conf.getenum. How is this supposed to work?
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "Lee-W (via GitHub)" <gi...@apache.org>.
Lee-W commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2667554477
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def get_varying_fstring(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ if source := self.get_varying_source(value.value):
+ return source
+ return None
+
+ def get_varying_collection(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def get_varying_dict(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
Review Comment:
```suggestion
if isinstance(node.func, ast.Attribute) and self._is_runtime_varying_attribute_call(node.func):
return True
elif isinstance(node.func, ast.Name) and self._is_runtime_varying_name_call(node.func):
return True
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def get_varying_fstring(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ if source := self.get_varying_source(value.value):
+ return source
+ return None
+
+ def get_varying_collection(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def get_varying_dict(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
Review Comment:
```suggestion
def has_varying_arguments(self, node: ast.Call) -> bool:
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def get_varying_fstring(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ if source := self.get_varying_source(value.value):
+ return source
+ return None
+
+ def get_varying_collection(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def get_varying_dict(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
+ """Check for runtime-varying calls like now() (when imported via 'from import')."""
+ func_name = func.id
+
+ if func_name in self.from_imports:
+ module, original_name = self.from_imports[func_name]
+ module_parts = module.split(".")
+
+ for part in module_parts:
+ if (part, original_name) in RUNTIME_VARYING_CALLS:
+ return True
+
+ return False
+
+
+class DagTaskDetector:
+ """
+ Detector dedicated to identifying Dag and Task constructors.
+
+ This detector identifies when code is creating Dag or Task objects
+ in Airflow. It needs to handle both traditional class instantiation and decorator styles.
+ """
+
+ def __init__(self, from_imports: dict):
Review Comment:
```suggestion
def __init__(self, from_imports: dict[str, tuple[str, str]]):
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def get_varying_fstring(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ if source := self.get_varying_source(value.value):
+ return source
+ return None
+
+ def get_varying_collection(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def get_varying_dict(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
+ """Check for runtime-varying calls like now() (when imported via 'from import')."""
+ func_name = func.id
+
+ if func_name in self.from_imports:
+ module, original_name = self.from_imports[func_name]
+ module_parts = module.split(".")
+
+ for part in module_parts:
+ if (part, original_name) in RUNTIME_VARYING_CALLS:
+ return True
+
+ return False
+
+
+class DagTaskDetector:
+ """
+ Detector dedicated to identifying Dag and Task constructors.
+
+ This detector identifies when code is creating Dag or Task objects
+ in Airflow. It needs to handle both traditional class instantiation and decorator styles.
+ """
+
+ def __init__(self, from_imports: dict):
+ self.from_imports = from_imports
+ self.dag_instances: set[str] = set()
+ self.is_in_dag_context: bool = False
+
+ def is_dag_constructor(self, node: ast.Call) -> bool:
+ """Check if a call is a Dag constructor."""
+ if not isinstance(node.func, ast.Name):
+ return False
+
+ func_name = node.func.id
+
+ # "from airflow import DAG" form or "from airflow.decorator import dag"
+ if func_name in self.from_imports:
+ module, original = self.from_imports[func_name]
+ if (module == "airflow" or module.startswith("airflow.")) and original in ("DAG", "dag"):
+ return True
+
+ return False
+
+ def is_task_constructor(self, node: ast.Call) -> bool:
+ """
+ Check if a call is a Task constructor.
+
+ Criteria:
+ 1. All calls within a Dag with block
+ 2. Calls that receive a Dag instance as an argument (dag=...)
+ """
+ # Inside Dag with block
+ if self.is_in_dag_context:
+ return True
+
+ # Passing Dag instance as argument
+ for arg in node.args:
+ if isinstance(arg, ast.Name) and arg.id in self.dag_instances:
+ return True
+
+ for keyword in node.keywords:
+ if keyword.value and isinstance(keyword.value, ast.Name):
+ if keyword.value.id in self.dag_instances:
+ return True
+
+ return False
+
+ def register_dag_instance(self, var_name: str):
+ """Register a Dag instance variable name."""
+ self.dag_instances.add(var_name)
+
+ def enter_dag_context(self):
+ """Enter a Dag with block."""
+ self.is_in_dag_context = True
+
+ def exit_dag_context(self):
+ """Exit a Dag with block."""
+ self.is_in_dag_context = False
+
+
+class AirflowRuntimeVaryingValueChecker(ast.NodeVisitor):
+ """
+ Main visitor class to detect runtime-varying value usage in Airflow Dag/Task.
+
+ Main responsibilities:
+ - Traverse AST and visit nodes
+ - Detect Dag/Task creation
+ - Track runtime-varying values and generate warnings
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel = DagStabilityCheckLevel.warning):
+ self.static_check_result: DagStabilityCheckerResult = DagStabilityCheckerResult(
+ check_level=check_level
+ )
+ self.imports: dict[str, str] = {}
+ self.from_imports: dict[str, tuple[str, str]] = {}
+ self.varying_vars: dict[str, tuple[int, str]] = {}
+ self.check_level = check_level
+
+ # Helper objects
+ self.value_analyzer = RuntimeVaryingValueAnalyzer(self.varying_vars, self.imports, self.from_imports)
+ self.dag_detector = DagTaskDetector(self.from_imports)
+
+ def visit_Import(self, node: ast.Import):
+ """Process import statements."""
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.imports[name] = alias.name
+
+ def visit_ImportFrom(self, node: ast.ImportFrom):
+ """Process from ... import statements."""
+ if node.module:
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.from_imports[name] = (node.module, alias.name)
+
+ def visit_Assign(self, node: ast.Assign):
+ """
+ Process variable assignments.
+
+ Checks:
+ 1. Dag instance assignment
+ 2. Task instance assignment
+ 3. Runtime-varying value assignment
+ """
+ value = node.value
+
+ # Dag constructor
+ if isinstance(value, ast.Call) and self.dag_detector.is_dag_constructor(value):
+ self._register_dag_instances(node.targets)
+ self._check_and_warn(value, WarningContext.DAG_CONSTRUCTOR)
+
+ # Task constructor
+ elif isinstance(value, ast.Call) and self.dag_detector.is_task_constructor(value):
+ self._check_and_warn(value, WarningContext.TASK_CONSTRUCTOR)
+
+ # Track runtime-varying values
+ else:
+ self._track_varying_assignment(node)
+
+ def visit_Call(self, node: ast.Call):
+ """
+ Process function calls.
+
+ Check not assign but just call the function or Dag definition via decorator.
+ """
+ if self.dag_detector.is_dag_constructor(node):
+ self._check_and_warn(node, WarningContext.DAG_CONSTRUCTOR)
+
+ elif self.dag_detector.is_task_constructor(node):
+ self._check_and_warn(node, WarningContext.TASK_CONSTRUCTOR)
+
+ def visit_For(self, node: ast.For):
+ """
+ Process for statements.
+
+ Check if iteration target contains runtime-varying values.
+ """
+ # check the iterator value is runtime-varying
+ # iter is runtime-varying : for iter in [datetime.now(), 3]
+ varying_source = self.value_analyzer.get_varying_source(node.iter)
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars[node.target.id] = (node.lineno, varying_source)
+
+ for body in node.body:
+ self.visit(body)
+
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars.pop(node.target.id)
+
+ def visit_With(self, node: ast.With):
+ """
+ Process with statements.
+
+ Detect Dag context manager.
+ """
+ is_with_dag_context = False
+ for item in node.items:
+ # check if the Dag instance exists in with context
+ self.visit(item)
+ if isinstance(item.context_expr, ast.Call):
+ if self.dag_detector.is_dag_constructor(item.context_expr):
+ # check the value defined in with statement to detect entering Dag with block
+ is_with_dag_context = True
+
+ if is_with_dag_context:
+ self.dag_detector.enter_dag_context()
+
+ for body in node.body:
+ self.visit(body)
+
+ # Exit Dag with block
+ self.dag_detector.exit_dag_context()
+
+ def _register_dag_instances(self, targets: list):
+ """Register Dag instance variable names."""
+ for target in targets:
+ if isinstance(target, ast.Name):
+ self.dag_detector.register_dag_instance(target.id)
+
+ def _track_varying_assignment(self, node: ast.Assign):
+ """Track variable assignments with runtime-varying values."""
+ varying_source = self.value_analyzer.get_varying_source(node.value)
+ if varying_source:
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ self.varying_vars[target.id] = (node.lineno, varying_source)
+
+ def _check_and_warn(self, call: ast.Call, context: WarningContext):
+ """Check function call arguments and generate warnings."""
+ varying_source = self.value_analyzer.get_varying_source(call)
+ if varying_source:
+ self.static_check_result.warnings.append(
+ RuntimeVaryingValueWarning(
+ line=call.lineno,
+ col=call.col_offset,
+ code=ast.unparse(call),
+ message=self._get_warning_message(context),
+ )
+ )
+
+ def _get_warning_message(self, context: WarningContext):
Review Comment:
```suggestion
def _get_warning_message(self, context: WarningContext) -> str:
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def get_varying_fstring(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ if source := self.get_varying_source(value.value):
+ return source
+ return None
+
+ def get_varying_collection(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
Review Comment:
```suggestion
if (source := self.get_varying_source(elt)):
return source
```
##########
airflow-core/src/airflow/config_templates/config.yml:
##########
@@ -2663,6 +2663,22 @@ dag_processor:
type: boolean
example: ~
default: "True"
+ dag_stability_check_level:
Review Comment:
dag_stability sounds more like whether this Dag can be run stably to me 🤔
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def get_varying_fstring(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ if source := self.get_varying_source(value.value):
+ return source
+ return None
+
+ def get_varying_collection(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def get_varying_dict(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
Review Comment:
```suggestion
def is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
Review Comment:
```suggestion
if isinstance(node, ast.Call)
# 1. Direct runtime-varying call
if self.is_runtime_varying_call(node):
return ast.unparse(node)
# 2. Method call chain
if isinstance(node.func, ast.Attribute):
self.get_varying_source(node.func.value)
# 3. Runtime-varying variable reference
if isinstance(node, ast.Name) and node.id in self.varying_vars:
_, source = self.varying_vars[node.id]
return source
# 4. f-string
if isinstance(node, ast.JoinedStr):
return self.get_varying_fstring(node)
# 5. Binary operation
if isinstance(node, ast.BinOp):
return self.get_varying_source(node.left) or self.get_varying_source(node.right)
# 6. Collections (list/tuple/set)
if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
return self.get_varying_collection(node.elts)
# 7. List comprehension
if isinstance(node, ast.ListComp):
return self.get_varying_source(node.elt)
# 8. Dictionary
if isinstance(node, ast.Dict):
return self.get_varying_dict(node)
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def get_varying_fstring(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ if source := self.get_varying_source(value.value):
+ return source
+ return None
+
+ def get_varying_collection(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def get_varying_dict(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
Review Comment:
```suggestion
if key and (source := self.get_varying_source(key)):
return source
if value and (source := self.get_varing_source(value)):
return source
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def get_varying_fstring(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ if source := self.get_varying_source(value.value):
+ return source
+ return None
+
+ def get_varying_collection(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def get_varying_dict(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
+ """Check for runtime-varying calls like now() (when imported via 'from import')."""
+ func_name = func.id
+
+ if func_name in self.from_imports:
+ module, original_name = self.from_imports[func_name]
+ module_parts = module.split(".")
+
+ for part in module_parts:
+ if (part, original_name) in RUNTIME_VARYING_CALLS:
+ return True
+
+ return False
+
+
+class DagTaskDetector:
+ """
+ Detector dedicated to identifying Dag and Task constructors.
+
+ This detector identifies when code is creating Dag or Task objects
+ in Airflow. It needs to handle both traditional class instantiation and decorator styles.
+ """
+
+ def __init__(self, from_imports: dict):
+ self.from_imports = from_imports
Review Comment:
```suggestion
self.from_imports: dict[str, tuple[str, str]] = from_imports
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
Review Comment:
```suggestion
def get_formatted_warnings(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
"""Convert warning statement to Dag warning format."""
from airflow.models.dagwarning import DagWarningType
if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
return []
return [
{
"dag_id": dag_id,
"warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
"message": self.format_warnings(),
}
for dag_id in dag_ids
]
def get_formatted_errors(self, file_path, bundle_path) -> dict[str, str | None] | None:
if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
return None
relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
return {relative_file_path: self.format_warnings()}
```
The first function is not returning a dict but a list. Naming them this way or similar would be easier to understand
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def get_varying_fstring(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ if source := self.get_varying_source(value.value):
+ return source
+ return None
+
+ def get_varying_collection(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def get_varying_dict(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
Review Comment:
```suggestion
def is_runtime_varying_name_call(self, func: ast.Name) -> bool:
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def get_varying_fstring(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ if source := self.get_varying_source(value.value):
+ return source
+ return None
+
+ def get_varying_collection(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def get_varying_dict(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
+ """Check for runtime-varying calls like now() (when imported via 'from import')."""
+ func_name = func.id
+
+ if func_name in self.from_imports:
+ module, original_name = self.from_imports[func_name]
+ module_parts = module.split(".")
+
+ for part in module_parts:
+ if (part, original_name) in RUNTIME_VARYING_CALLS:
+ return True
+
+ return False
+
+
+class DagTaskDetector:
+ """
+ Detector dedicated to identifying Dag and Task constructors.
+
+ This detector identifies when code is creating Dag or Task objects
+ in Airflow. It needs to handle both traditional class instantiation and decorator styles.
+ """
+
+ def __init__(self, from_imports: dict):
+ self.from_imports = from_imports
+ self.dag_instances: set[str] = set()
+ self.is_in_dag_context: bool = False
+
+ def is_dag_constructor(self, node: ast.Call) -> bool:
+ """Check if a call is a Dag constructor."""
+ if not isinstance(node.func, ast.Name):
+ return False
+
+ func_name = node.func.id
+
+ # "from airflow import DAG" form or "from airflow.decorator import dag"
+ if func_name in self.from_imports:
+ module, original = self.from_imports[func_name]
+ if (module == "airflow" or module.startswith("airflow.")) and original in ("DAG", "dag"):
+ return True
+
+ return False
+
+ def is_task_constructor(self, node: ast.Call) -> bool:
+ """
+ Check if a call is a Task constructor.
+
+ Criteria:
+ 1. All calls within a Dag with block
+ 2. Calls that receive a Dag instance as an argument (dag=...)
+ """
+ # Inside Dag with block
+ if self.is_in_dag_context:
+ return True
+
+ # Passing Dag instance as argument
+ for arg in node.args:
+ if isinstance(arg, ast.Name) and arg.id in self.dag_instances:
+ return True
+
+ for keyword in node.keywords:
+ if keyword.value and isinstance(keyword.value, ast.Name):
+ if keyword.value.id in self.dag_instances:
+ return True
+
+ return False
+
+ def register_dag_instance(self, var_name: str):
+ """Register a Dag instance variable name."""
+ self.dag_instances.add(var_name)
+
+ def enter_dag_context(self):
+ """Enter a Dag with block."""
+ self.is_in_dag_context = True
+
+ def exit_dag_context(self):
+ """Exit a Dag with block."""
+ self.is_in_dag_context = False
+
+
+class AirflowRuntimeVaryingValueChecker(ast.NodeVisitor):
+ """
+ Main visitor class to detect runtime-varying value usage in Airflow Dag/Task.
+
+ Main responsibilities:
+ - Traverse AST and visit nodes
+ - Detect Dag/Task creation
+ - Track runtime-varying values and generate warnings
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel = DagStabilityCheckLevel.warning):
+ self.static_check_result: DagStabilityCheckerResult = DagStabilityCheckerResult(
+ check_level=check_level
+ )
+ self.imports: dict[str, str] = {}
+ self.from_imports: dict[str, tuple[str, str]] = {}
+ self.varying_vars: dict[str, tuple[int, str]] = {}
+ self.check_level = check_level
+
+ # Helper objects
+ self.value_analyzer = RuntimeVaryingValueAnalyzer(self.varying_vars, self.imports, self.from_imports)
+ self.dag_detector = DagTaskDetector(self.from_imports)
+
+ def visit_Import(self, node: ast.Import):
+ """Process import statements."""
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.imports[name] = alias.name
+
+ def visit_ImportFrom(self, node: ast.ImportFrom):
+ """Process from ... import statements."""
+ if node.module:
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.from_imports[name] = (node.module, alias.name)
+
+ def visit_Assign(self, node: ast.Assign):
+ """
+ Process variable assignments.
+
+ Checks:
+ 1. Dag instance assignment
+ 2. Task instance assignment
+ 3. Runtime-varying value assignment
+ """
+ value = node.value
+
+ # Dag constructor
+ if isinstance(value, ast.Call) and self.dag_detector.is_dag_constructor(value):
+ self._register_dag_instances(node.targets)
+ self._check_and_warn(value, WarningContext.DAG_CONSTRUCTOR)
+
+ # Task constructor
+ elif isinstance(value, ast.Call) and self.dag_detector.is_task_constructor(value):
+ self._check_and_warn(value, WarningContext.TASK_CONSTRUCTOR)
+
+ # Track runtime-varying values
+ else:
+ self._track_varying_assignment(node)
+
+ def visit_Call(self, node: ast.Call):
+ """
+ Process function calls.
+
+ Check not assign but just call the function or Dag definition via decorator.
+ """
+ if self.dag_detector.is_dag_constructor(node):
+ self._check_and_warn(node, WarningContext.DAG_CONSTRUCTOR)
+
+ elif self.dag_detector.is_task_constructor(node):
+ self._check_and_warn(node, WarningContext.TASK_CONSTRUCTOR)
+
+ def visit_For(self, node: ast.For):
+ """
+ Process for statements.
+
+ Check if iteration target contains runtime-varying values.
+ """
+ # check the iterator value is runtime-varying
+ # iter is runtime-varying : for iter in [datetime.now(), 3]
+ varying_source = self.value_analyzer.get_varying_source(node.iter)
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars[node.target.id] = (node.lineno, varying_source)
+
+ for body in node.body:
+ self.visit(body)
+
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars.pop(node.target.id)
+
+ def visit_With(self, node: ast.With):
+ """
+ Process with statements.
+
+ Detect Dag context manager.
+ """
+ is_with_dag_context = False
+ for item in node.items:
+ # check if the Dag instance exists in with context
+ self.visit(item)
+ if isinstance(item.context_expr, ast.Call):
+ if self.dag_detector.is_dag_constructor(item.context_expr):
+ # check the value defined in with statement to detect entering Dag with block
+ is_with_dag_context = True
+
+ if is_with_dag_context:
+ self.dag_detector.enter_dag_context()
+
+ for body in node.body:
+ self.visit(body)
+
+ # Exit Dag with block
+ self.dag_detector.exit_dag_context()
+
+ def _register_dag_instances(self, targets: list):
+ """Register Dag instance variable names."""
+ for target in targets:
+ if isinstance(target, ast.Name):
+ self.dag_detector.register_dag_instance(target.id)
+
+ def _track_varying_assignment(self, node: ast.Assign):
+ """Track variable assignments with runtime-varying values."""
+ varying_source = self.value_analyzer.get_varying_source(node.value)
+ if varying_source:
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ self.varying_vars[target.id] = (node.lineno, varying_source)
+
+ def _check_and_warn(self, call: ast.Call, context: WarningContext):
+ """Check function call arguments and generate warnings."""
+ varying_source = self.value_analyzer.get_varying_source(call)
+ if varying_source:
+ self.static_check_result.warnings.append(
+ RuntimeVaryingValueWarning(
+ line=call.lineno,
+ col=call.col_offset,
+ code=ast.unparse(call),
+ message=self._get_warning_message(context),
+ )
+ )
+
+ def _get_warning_message(self, context: WarningContext):
+ """Get appropriate warning message based on context."""
+ if self.dag_detector.is_in_dag_context and context == WarningContext.TASK_CONSTRUCTOR:
+ return "Don't use runtime-varying values as function arguments within with Dag block"
+ return f"Don't use runtime-varying value as argument in {context.value}"
+
+
+def check_dag_file_stability(file_path) -> DagStabilityCheckerResult:
+ from airflow.configuration import conf
+
+ check_level = conf.getenum("dag_processor", "dag_stability_check_level", DagStabilityCheckLevel)
+
+ if check_level == DagStabilityCheckLevel.off:
+ return DagStabilityCheckerResult(check_level=check_level)
+
+ try:
+ parsed = ast.parse(Path(file_path).read_bytes())
+ except Exception:
Review Comment:
```suggestion
except SyntaxError, ValueError, TypeError:
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def get_varying_fstring(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ if source := self.get_varying_source(value.value):
+ return source
+ return None
+
+ def get_varying_collection(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def get_varying_dict(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
+ """Check for runtime-varying calls like now() (when imported via 'from import')."""
+ func_name = func.id
+
+ if func_name in self.from_imports:
+ module, original_name = self.from_imports[func_name]
+ module_parts = module.split(".")
+
+ for part in module_parts:
+ if (part, original_name) in RUNTIME_VARYING_CALLS:
+ return True
+
+ return False
+
+
+class DagTaskDetector:
+ """
+ Detector dedicated to identifying Dag and Task constructors.
+
+ This detector identifies when code is creating Dag or Task objects
+ in Airflow. It needs to handle both traditional class instantiation and decorator styles.
+ """
+
+ def __init__(self, from_imports: dict):
+ self.from_imports = from_imports
+ self.dag_instances: set[str] = set()
+ self.is_in_dag_context: bool = False
+
+ def is_dag_constructor(self, node: ast.Call) -> bool:
+ """Check if a call is a Dag constructor."""
+ if not isinstance(node.func, ast.Name):
+ return False
+
+ func_name = node.func.id
+
+ # "from airflow import DAG" form or "from airflow.decorator import dag"
+ if func_name in self.from_imports:
+ module, original = self.from_imports[func_name]
+ if (module == "airflow" or module.startswith("airflow.")) and original in ("DAG", "dag"):
+ return True
+
+ return False
+
+ def is_task_constructor(self, node: ast.Call) -> bool:
+ """
+ Check if a call is a Task constructor.
+
+ Criteria:
+ 1. All calls within a Dag with block
+ 2. Calls that receive a Dag instance as an argument (dag=...)
+ """
+ # Inside Dag with block
+ if self.is_in_dag_context:
+ return True
+
+ # Passing Dag instance as argument
+ for arg in node.args:
+ if isinstance(arg, ast.Name) and arg.id in self.dag_instances:
+ return True
+
+ for keyword in node.keywords:
+ if keyword.value and isinstance(keyword.value, ast.Name):
+ if keyword.value.id in self.dag_instances:
+ return True
+
+ return False
+
+ def register_dag_instance(self, var_name: str):
+ """Register a Dag instance variable name."""
+ self.dag_instances.add(var_name)
+
+ def enter_dag_context(self):
+ """Enter a Dag with block."""
+ self.is_in_dag_context = True
+
+ def exit_dag_context(self):
+ """Exit a Dag with block."""
+ self.is_in_dag_context = False
+
+
+class AirflowRuntimeVaryingValueChecker(ast.NodeVisitor):
+ """
+ Main visitor class to detect runtime-varying value usage in Airflow Dag/Task.
+
+ Main responsibilities:
+ - Traverse AST and visit nodes
+ - Detect Dag/Task creation
+ - Track runtime-varying values and generate warnings
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel = DagStabilityCheckLevel.warning):
+ self.static_check_result: DagStabilityCheckerResult = DagStabilityCheckerResult(
+ check_level=check_level
+ )
+ self.imports: dict[str, str] = {}
+ self.from_imports: dict[str, tuple[str, str]] = {}
+ self.varying_vars: dict[str, tuple[int, str]] = {}
+ self.check_level = check_level
+
+ # Helper objects
+ self.value_analyzer = RuntimeVaryingValueAnalyzer(self.varying_vars, self.imports, self.from_imports)
+ self.dag_detector = DagTaskDetector(self.from_imports)
+
+ def visit_Import(self, node: ast.Import):
+ """Process import statements."""
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.imports[name] = alias.name
+
+ def visit_ImportFrom(self, node: ast.ImportFrom):
+ """Process from ... import statements."""
+ if node.module:
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.from_imports[name] = (node.module, alias.name)
+
+ def visit_Assign(self, node: ast.Assign):
+ """
+ Process variable assignments.
+
+ Checks:
+ 1. Dag instance assignment
+ 2. Task instance assignment
+ 3. Runtime-varying value assignment
+ """
+ value = node.value
+
+ # Dag constructor
+ if isinstance(value, ast.Call) and self.dag_detector.is_dag_constructor(value):
+ self._register_dag_instances(node.targets)
+ self._check_and_warn(value, WarningContext.DAG_CONSTRUCTOR)
+
+ # Task constructor
+ elif isinstance(value, ast.Call) and self.dag_detector.is_task_constructor(value):
+ self._check_and_warn(value, WarningContext.TASK_CONSTRUCTOR)
+
+ # Track runtime-varying values
+ else:
+ self._track_varying_assignment(node)
+
+ def visit_Call(self, node: ast.Call):
+ """
+ Process function calls.
+
+ Check not assign but just call the function or Dag definition via decorator.
+ """
+ if self.dag_detector.is_dag_constructor(node):
+ self._check_and_warn(node, WarningContext.DAG_CONSTRUCTOR)
+
+ elif self.dag_detector.is_task_constructor(node):
+ self._check_and_warn(node, WarningContext.TASK_CONSTRUCTOR)
+
+ def visit_For(self, node: ast.For):
+ """
+ Process for statements.
+
+ Check if iteration target contains runtime-varying values.
+ """
+ # check the iterator value is runtime-varying
+ # iter is runtime-varying : for iter in [datetime.now(), 3]
+ varying_source = self.value_analyzer.get_varying_source(node.iter)
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars[node.target.id] = (node.lineno, varying_source)
+
+ for body in node.body:
+ self.visit(body)
+
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars.pop(node.target.id)
+
+ def visit_With(self, node: ast.With):
+ """
+ Process with statements.
+
+ Detect Dag context manager.
+ """
+ is_with_dag_context = False
+ for item in node.items:
+ # check if the Dag instance exists in with context
+ self.visit(item)
+ if isinstance(item.context_expr, ast.Call):
+ if self.dag_detector.is_dag_constructor(item.context_expr):
+ # check the value defined in with statement to detect entering Dag with block
+ is_with_dag_context = True
+
+ if is_with_dag_context:
+ self.dag_detector.enter_dag_context()
+
+ for body in node.body:
+ self.visit(body)
+
+ # Exit Dag with block
+ self.dag_detector.exit_dag_context()
+
+ def _register_dag_instances(self, targets: list):
+ """Register Dag instance variable names."""
+ for target in targets:
+ if isinstance(target, ast.Name):
+ self.dag_detector.register_dag_instance(target.id)
+
+ def _track_varying_assignment(self, node: ast.Assign):
+ """Track variable assignments with runtime-varying values."""
+ varying_source = self.value_analyzer.get_varying_source(node.value)
+ if varying_source:
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ self.varying_vars[target.id] = (node.lineno, varying_source)
+
+ def _check_and_warn(self, call: ast.Call, context: WarningContext):
+ """Check function call arguments and generate warnings."""
+ varying_source = self.value_analyzer.get_varying_source(call)
+ if varying_source:
Review Comment:
```suggestion
if (varying_source := self.value_analyzer.get_varying_source(call)):
```
##########
airflow-core/src/airflow/utils/dag_stability_checker.py:
##########
@@ -0,0 +1,533 @@
+# 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 ast
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+
+RUNTIME_VARYING_CALLS = [
+ ("datetime", "now"),
+ ("datetime", "today"),
+ ("datetime", "utcnow"),
+ ("date", "today"),
+ ("time", "time"),
+ ("time", "localtime"),
+ ("random", "random"),
+ ("random", "randint"),
+ ("random", "choice"),
+ ("random", "uniform"),
+ ("uuid", "uuid4"),
+ ("uuid", "uuid1"),
+ ("pendulum", "now"),
+ ("pendulum", "today"),
+ ("pendulum", "yesterday"),
+ ("pendulum", "tomorrow"),
+]
+
+
+class DagStabilityCheckLevel(Enum):
+ """enum class for Dag stability check level."""
+
+ off = "off"
+ warning = "warning"
+ error = "error"
+
+
+class DagStabilityCheckerResult:
+ """
+ Represents the result of stability analysis on a Dag file.
+
+ Stores detected warnings and formats them appropriately based on the configured check level
+ (warning or error).
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel):
+ self.check_level: DagStabilityCheckLevel = check_level
+ self.warnings: list[RuntimeVaryingValueWarning] = []
+ self.runtime_varying_values: dict = {}
+
+ def format_warnings(self) -> str | None:
+ """Return formatted string of warning list."""
+ if not self.warnings:
+ return None
+
+ lines = [
+ "This Dag uses runtime-variable values in Dag construction.",
+ "It causes the Dag version to increase as values change on every Dag parse.",
+ "",
+ ]
+ for w in self.warnings:
+ lines.extend(
+ [
+ f"Line {w.line}, Col {w.col}",
+ f"Code: {w.code}",
+ f"Issue: {w.message}",
+ "",
+ ]
+ )
+
+ if self.runtime_varying_values:
+ lines.extend(
+ [
+ "️Don't use the variables as arguments in Dag/Task constructors:",
+ *(
+ f" Line {line}: '{var_name}' related '{source}'"
+ for var_name, (line, source) in sorted(
+ self.runtime_varying_values.items(),
+ key=lambda x: x[1][0],
+ )
+ ),
+ "",
+ ]
+ )
+
+ return "\n".join(lines)
+
+ def get_warning_dag_format_dict(self, dag_ids: list[str]) -> list[dict[str, str | None]]:
+ """Convert warning statement to Dag warning format."""
+ from airflow.models.dagwarning import DagWarningType
+
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.warning:
+ return []
+ return [
+ {
+ "dag_id": dag_id,
+ "warning_type": DagWarningType.RUNTIME_VARYING_VALUE.value,
+ "message": self.format_warnings(),
+ }
+ for dag_id in dag_ids
+ ]
+
+ def get_error_format_dict(self, file_path, bundle_path):
+ if not self.warnings or self.check_level != DagStabilityCheckLevel.error:
+ return None
+
+ relative_file_path = str(Path(file_path).relative_to(bundle_path)) if bundle_path else file_path
+ return {relative_file_path: self.format_warnings()}
+
+
+@dataclass
+class RuntimeVaryingValueWarning:
+ """Warning information for runtime-varying value detection."""
+
+ line: int
+ col: int
+ code: str
+ message: str
+
+
+class WarningContext(str, Enum):
+ """Context types for warnings."""
+
+ TASK_CONSTRUCTOR = "Task constructor"
+ DAG_CONSTRUCTOR = "Dag constructor"
+
+
+class RuntimeVaryingValueAnalyzer:
+ """
+ Analyzer dedicated to tracking and detecting runtime-varying values.
+
+ This analyzer is responsible for identifying if a given AST node
+ contains values that change on every execution (datetime.now(), random(), etc.).
+ """
+
+ def __init__(
+ self,
+ varying_vars: dict[str, tuple[int, str]],
+ imports: dict[str, str],
+ from_imports: dict[str, tuple[str, str]],
+ ):
+ self.varying_vars = varying_vars
+ self.imports = imports
+ self.from_imports = from_imports
+
+ def get_varying_source(self, node: ast.expr) -> str | None:
+ """
+ Check if an AST node contains runtime-varying values and return the source.
+
+ Checks:
+ - Runtime-varying function calls (datetime.now(), etc.)
+ - Runtime-varying variable references
+ - Runtime-varying values in f-strings
+ - Runtime-varying values in expressions/collections
+ """
+ # 1. Direct runtime-varying call
+ if isinstance(node, ast.Call) and self.is_runtime_varying_call(node):
+ return ast.unparse(node)
+
+ # 2. Runtime-varying variable reference
+ if isinstance(node, ast.Name) and node.id in self.varying_vars:
+ _, source = self.varying_vars[node.id]
+ return source
+
+ # 3. f-string
+ if isinstance(node, ast.JoinedStr):
+ return self.get_varying_fstring(node)
+
+ # 4. Binary operation
+ if isinstance(node, ast.BinOp):
+ return self.get_varying_source(node.left) or self.get_varying_source(node.right)
+
+ # 5. Collections (list/tuple/set)
+ if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
+ return self.get_varying_collection(node.elts)
+
+ # 6. List comprehension
+ if isinstance(node, ast.ListComp):
+ return self.get_varying_source(node.elt)
+
+ # 7. Dictionary
+ if isinstance(node, ast.Dict):
+ return self.get_varying_dict(node)
+
+ # 8. Method call chain
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+ return self.get_varying_source(node.func.value)
+
+ return None
+
+ def get_varying_fstring(self, node: ast.JoinedStr) -> str | None:
+ """Check for runtime-varying values inside f-strings."""
+ for value in node.values:
+ if isinstance(value, ast.FormattedValue):
+ if source := self.get_varying_source(value.value):
+ return source
+ return None
+
+ def get_varying_collection(self, elements: list) -> str | None:
+ """Check for runtime-varying values in collection elements."""
+ for elt in elements:
+ source = self.get_varying_source(elt)
+ if source:
+ return source
+ return None
+
+ def get_varying_dict(self, node: ast.Dict) -> str | None:
+ """Check for runtime-varying values in dictionary keys/values."""
+ for key, value in zip(node.keys, node.values):
+ if key:
+ source = self.get_varying_source(key)
+ if source:
+ return source
+ if value:
+ source = self.get_varying_source(value)
+ if source:
+ return source
+ return None
+
+ def is_runtime_varying_call(self, node: ast.Call) -> bool:
+ """
+ Check if a call is runtime-varying.
+
+ 1. Is the function itself runtime-varying?
+ 2. Do the arguments contain runtime-varying values?
+ """
+ # Check if the function itself is runtime-varying
+ if isinstance(node.func, ast.Attribute):
+ if self._is_runtime_varying_attribute_call(node.func):
+ return True
+ elif isinstance(node.func, ast.Name):
+ if self._is_runtime_varying_name_call(node.func):
+ return True
+
+ # Check if arguments contain runtime-varying values
+ return self._has_varying_arguments(node)
+
+ def _has_varying_arguments(self, node: ast.Call) -> bool:
+ """Check if function arguments contain runtime-varying values."""
+ for arg in node.args:
+ if self.get_varying_source(arg):
+ return True
+
+ for kw in node.keywords:
+ if self.get_varying_source(kw.value):
+ return True
+
+ return False
+
+ def _is_runtime_varying_attribute_call(self, attr: ast.Attribute) -> bool:
+ """Check for runtime-varying calls like datetime.now()."""
+ method_name = attr.attr
+
+ if isinstance(attr.value, ast.Name):
+ module_or_alias = attr.value.id
+ actual_module = self.imports.get(module_or_alias, module_or_alias)
+
+ # If imported via "from import"
+ if module_or_alias in self.from_imports:
+ _, original_name = self.from_imports[module_or_alias]
+ actual_module = original_name
+
+ return (actual_module, method_name) in RUNTIME_VARYING_CALLS
+
+ # Nested attribute (e.g., datetime.datetime.now)
+ if isinstance(attr.value, ast.Attribute):
+ inner_attr = attr.value
+ if isinstance(inner_attr.value, ast.Name):
+ return (inner_attr.attr, method_name) in RUNTIME_VARYING_CALLS
+
+ return False
+
+ def _is_runtime_varying_name_call(self, func: ast.Name) -> bool:
+ """Check for runtime-varying calls like now() (when imported via 'from import')."""
+ func_name = func.id
+
+ if func_name in self.from_imports:
+ module, original_name = self.from_imports[func_name]
+ module_parts = module.split(".")
+
+ for part in module_parts:
+ if (part, original_name) in RUNTIME_VARYING_CALLS:
+ return True
+
+ return False
+
+
+class DagTaskDetector:
+ """
+ Detector dedicated to identifying Dag and Task constructors.
+
+ This detector identifies when code is creating Dag or Task objects
+ in Airflow. It needs to handle both traditional class instantiation and decorator styles.
+ """
+
+ def __init__(self, from_imports: dict):
+ self.from_imports = from_imports
+ self.dag_instances: set[str] = set()
+ self.is_in_dag_context: bool = False
+
+ def is_dag_constructor(self, node: ast.Call) -> bool:
+ """Check if a call is a Dag constructor."""
+ if not isinstance(node.func, ast.Name):
+ return False
+
+ func_name = node.func.id
+
+ # "from airflow import DAG" form or "from airflow.decorator import dag"
+ if func_name in self.from_imports:
+ module, original = self.from_imports[func_name]
+ if (module == "airflow" or module.startswith("airflow.")) and original in ("DAG", "dag"):
+ return True
+
+ return False
+
+ def is_task_constructor(self, node: ast.Call) -> bool:
+ """
+ Check if a call is a Task constructor.
+
+ Criteria:
+ 1. All calls within a Dag with block
+ 2. Calls that receive a Dag instance as an argument (dag=...)
+ """
+ # Inside Dag with block
+ if self.is_in_dag_context:
+ return True
+
+ # Passing Dag instance as argument
+ for arg in node.args:
+ if isinstance(arg, ast.Name) and arg.id in self.dag_instances:
+ return True
+
+ for keyword in node.keywords:
+ if keyword.value and isinstance(keyword.value, ast.Name):
+ if keyword.value.id in self.dag_instances:
+ return True
+
+ return False
+
+ def register_dag_instance(self, var_name: str):
+ """Register a Dag instance variable name."""
+ self.dag_instances.add(var_name)
+
+ def enter_dag_context(self):
+ """Enter a Dag with block."""
+ self.is_in_dag_context = True
+
+ def exit_dag_context(self):
+ """Exit a Dag with block."""
+ self.is_in_dag_context = False
+
+
+class AirflowRuntimeVaryingValueChecker(ast.NodeVisitor):
+ """
+ Main visitor class to detect runtime-varying value usage in Airflow Dag/Task.
+
+ Main responsibilities:
+ - Traverse AST and visit nodes
+ - Detect Dag/Task creation
+ - Track runtime-varying values and generate warnings
+ """
+
+ def __init__(self, check_level: DagStabilityCheckLevel = DagStabilityCheckLevel.warning):
+ self.static_check_result: DagStabilityCheckerResult = DagStabilityCheckerResult(
+ check_level=check_level
+ )
+ self.imports: dict[str, str] = {}
+ self.from_imports: dict[str, tuple[str, str]] = {}
+ self.varying_vars: dict[str, tuple[int, str]] = {}
+ self.check_level = check_level
+
+ # Helper objects
+ self.value_analyzer = RuntimeVaryingValueAnalyzer(self.varying_vars, self.imports, self.from_imports)
+ self.dag_detector = DagTaskDetector(self.from_imports)
+
+ def visit_Import(self, node: ast.Import):
+ """Process import statements."""
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.imports[name] = alias.name
+
+ def visit_ImportFrom(self, node: ast.ImportFrom):
+ """Process from ... import statements."""
+ if node.module:
+ for alias in node.names:
+ name = alias.asname or alias.name
+ self.from_imports[name] = (node.module, alias.name)
+
+ def visit_Assign(self, node: ast.Assign):
+ """
+ Process variable assignments.
+
+ Checks:
+ 1. Dag instance assignment
+ 2. Task instance assignment
+ 3. Runtime-varying value assignment
+ """
+ value = node.value
+
+ # Dag constructor
+ if isinstance(value, ast.Call) and self.dag_detector.is_dag_constructor(value):
+ self._register_dag_instances(node.targets)
+ self._check_and_warn(value, WarningContext.DAG_CONSTRUCTOR)
+
+ # Task constructor
+ elif isinstance(value, ast.Call) and self.dag_detector.is_task_constructor(value):
+ self._check_and_warn(value, WarningContext.TASK_CONSTRUCTOR)
+
+ # Track runtime-varying values
+ else:
+ self._track_varying_assignment(node)
+
+ def visit_Call(self, node: ast.Call):
+ """
+ Process function calls.
+
+ Check not assign but just call the function or Dag definition via decorator.
+ """
+ if self.dag_detector.is_dag_constructor(node):
+ self._check_and_warn(node, WarningContext.DAG_CONSTRUCTOR)
+
+ elif self.dag_detector.is_task_constructor(node):
+ self._check_and_warn(node, WarningContext.TASK_CONSTRUCTOR)
+
+ def visit_For(self, node: ast.For):
+ """
+ Process for statements.
+
+ Check if iteration target contains runtime-varying values.
+ """
+ # check the iterator value is runtime-varying
+ # iter is runtime-varying : for iter in [datetime.now(), 3]
+ varying_source = self.value_analyzer.get_varying_source(node.iter)
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars[node.target.id] = (node.lineno, varying_source)
+
+ for body in node.body:
+ self.visit(body)
+
+ if varying_source:
+ if isinstance(node.target, ast.Name):
+ self.varying_vars.pop(node.target.id)
+
+ def visit_With(self, node: ast.With):
+ """
+ Process with statements.
+
+ Detect Dag context manager.
+ """
+ is_with_dag_context = False
+ for item in node.items:
+ # check if the Dag instance exists in with context
+ self.visit(item)
+ if isinstance(item.context_expr, ast.Call):
+ if self.dag_detector.is_dag_constructor(item.context_expr):
+ # check the value defined in with statement to detect entering Dag with block
+ is_with_dag_context = True
+
+ if is_with_dag_context:
+ self.dag_detector.enter_dag_context()
+
+ for body in node.body:
+ self.visit(body)
+
+ # Exit Dag with block
+ self.dag_detector.exit_dag_context()
+
+ def _register_dag_instances(self, targets: list):
+ """Register Dag instance variable names."""
+ for target in targets:
+ if isinstance(target, ast.Name):
+ self.dag_detector.register_dag_instance(target.id)
+
+ def _track_varying_assignment(self, node: ast.Assign):
+ """Track variable assignments with runtime-varying values."""
+ varying_source = self.value_analyzer.get_varying_source(node.value)
+ if varying_source:
Review Comment:
```suggestion
if (varying_source := self.value_analyzer.get_varying_source(node.value)):
```
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3677991249
> Dag versioning: a.k.a keep history of serdags used in runs. This is always on - there is no mechanism to disable it. This is what the static check here is covering. This powers the UI to show what the dag looked like historically.
Understood. Then indeed such warning should always be raised - however I think it would be great to give better control on how to raise it - and whether it should just `detect` such cases or `prevent` them (if import error is raised rather than just UI warning).,
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "jedcunningham (via GitHub)" <gi...@apache.org>.
jedcunningham commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3676050789
> Maybe we should - by default exclude non-versioned Dags from this warning.
You can turn off using versioned bundles (what code is used for a task), but you cannot turn of dag versioning (keeping history of what the dag looked like).
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3693077314
@Lee-W @ephraimbuddy @ephraimbuddy
Can you give more reivew for this?
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3691828470
All my issues solved !
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3686384114
When the log level is set to ERROR, a DAG import error occurs as shown below.
<img width="1387" height="809" alt="image" src="https://github.com/user-attachments/assets/63036105-fa7a-423b-bd86-b59ac6da23df" />
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3687742500
This looks way better now - one general comment I have is to not aim for "generic static checking" in this PR - but more focus on what is being checked (stability of the Dag serialized form) - naming it as generic "static check" is a bit of to big of a generalisation.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3666528308
> > I think we should have an opt-out solution for those that doesn't mind the dag being non deterministic.
100%
> I agree that too. I think there are two options
>
> * making config section for disabling it (e.g. AIRFLOW__DAG_PROCESSOR_ENABLE_PARSING_WARNING)
> * as Jarek said, suppress it by comment in the Dag
I think (despite Airflow having too many configuration parameters already) there should be few ways:
* Comments have this drawbacks that they are missing from AST. So possibly we should have something similar to when we check for `Dag` in the source code - and possibly even in the same time to avoid double reading the Dag to memory and with the same control to disable it
* Maybe we should have some .airflowignore style exclude as well - I can easily imagine filename patter-matching in play here.
* Maybe we should - by default exclude non-versioned Dags from this warning. This would be pretty much backwards-compatible for those who don't care about versioning (though I believe there is the effect of continuously overriding SerialzedDag in case of non-versioned Dags, but that is less problematic and Airflow had no problems handling it in the past.
* Also global flag disabling or enabling it globally. Here maybe also we could have a three-value check:
* None
* Alll
* OnlyVersioned (default)
* Finally I think we might have another global flag "Treat unstable Dag warnings as errors". I imagine situatoin where some users would like to absolutely not want unstable Dags.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3677838926
> You can turn off using versioned bundles (what code is used for a task), but you cannot turn of dag versioning (keeping history of what the dag looked like).
Yeah - but ....it does not result in creating a new version entry - it will just continuously override SerializedDags yeah? So generally that's something that we've been also doing in Airflow 2 and it never created huge issue (except a bit more often DB update for those ?
This is what I wanted to express in this comment:
> Maybe we should - by default exclude non-versioned Dags from this warning. This would be pretty much backwards-compatible for those who don't care about versioning (though I believe there is the effect of continuously overriding SerialzedDag in case of non-versioned Dags, but that is less problematic and Airflow had no problems handling it in the past.
But maybe I am wrong and in such case we also create multiple versions in the DB ? Have not looked there in that detail?
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2656767445
##########
airflow-core/src/airflow/config_templates/config.yml:
##########
@@ -2663,6 +2663,22 @@ dag_processor:
type: boolean
example: ~
default: "True"
+ dag_stability_check_level:
Review Comment:
Yes, it's a somewhat broad concept name, but I don't think it's a big problem. If it's too detailed, the word tends to get too long.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "wjddn279 (via GitHub)" <gi...@apache.org>.
wjddn279 commented on PR #59430:
URL: https://github.com/apache/airflow/pull/59430#issuecomment-3713812257
@ephraimbuddy @Lee-W
Review feedback has been addressed. Thanks for checking!
I've thoroughly reviewed all instances of the renaming to Dag! Thanks for pointing that out.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2644086300
##########
airflow-core/src/airflow/dag_processing/processor.py:
##########
@@ -200,22 +201,34 @@ def _parse_file_entrypoint():
sys.path.append(bundle_root)
result = _parse_file(msg, log)
+
if result is not None:
comms_decoder.send(result)
def _parse_file(msg: DagFileParseRequest, log: FilteringBoundLogger) -> DagFileParsingResult | None:
# TODO: Set known_pool names on DagBag!
+ static_check_result = check_dag_file_static(os.fspath(msg.file))
Review Comment:
same here - > I think we should make it clear that this is a "dag stability" check - not "static check" in general.
##########
airflow-core/src/airflow/dag_processing/processor.py:
##########
@@ -200,22 +201,34 @@ def _parse_file_entrypoint():
sys.path.append(bundle_root)
result = _parse_file(msg, log)
+
if result is not None:
comms_decoder.send(result)
def _parse_file(msg: DagFileParseRequest, log: FilteringBoundLogger) -> DagFileParsingResult | None:
# TODO: Set known_pool names on DagBag!
+ static_check_result = check_dag_file_static(os.fspath(msg.file))
Review Comment:
same here -> names should be updated - > I think we should make it clear that this is a "dag stability" check - not "static check" in general.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2644084125
##########
airflow-core/src/airflow/config_templates/config.yml:
##########
@@ -2663,6 +2663,23 @@ dag_processor:
type: boolean
example: ~
default: "True"
+ static_check_level:
Review Comment:
```suggestion
dag_stability_check_level:
```
Or similar. I think there are many more static checks we might want to run - this is jut one of them and I doubt they will all be enabled with the same switch.
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] add static checker for preventing to increase dag version [airflow]
Posted by "ephraimbuddy (via GitHub)" <gi...@apache.org>.
ephraimbuddy commented on code in PR #59430:
URL: https://github.com/apache/airflow/pull/59430#discussion_r2655072558
##########
airflow-core/src/airflow/config_templates/config.yml:
##########
@@ -2663,6 +2663,22 @@ dag_processor:
type: boolean
example: ~
default: "True"
+ dag_stability_check_level:
+ description: |
+ Controls the behavior of dag stability checker performed before DAG parsing in the dag-processor.
+ Static checks detect potential issues such as runtime-varying values in DAG/Task constructors
+ that could cause DAG version inflation.
+
+ * ``off``: Disables dag stability checks entirely. No errors or warnings are generated.
+ * ``warning``: DAGs load normally but warnings are displayed in the UI when issues are detected.
Review Comment:
```suggestion
* ``warning``: Dags load normally but warnings are displayed in the UI when issues are detected.
```
##########
airflow-core/src/airflow/config_templates/config.yml:
##########
@@ -2663,6 +2663,22 @@ dag_processor:
type: boolean
example: ~
default: "True"
+ dag_stability_check_level:
+ description: |
+ Controls the behavior of dag stability checker performed before DAG parsing in the dag-processor.
+ Static checks detect potential issues such as runtime-varying values in DAG/Task constructors
+ that could cause DAG version inflation.
Review Comment:
```suggestion
Controls the behavior of dag stability checker performed before Dag parsing in the dag-processor.
The check detects potential issues such as runtime-varying values in Dag/Task constructors
that could cause Dag version inflation.
```
We might need to word the first line to reflect exactly that this is about version inflation
##########
airflow-core/src/airflow/config_templates/config.yml:
##########
@@ -2663,6 +2663,22 @@ dag_processor:
type: boolean
example: ~
default: "True"
+ dag_stability_check_level:
Review Comment:
I think it will be more clear to call this: `dag_version_inflation_check_level` for easy discovery and understanding but no strong opinion here
##########
airflow-core/src/airflow/dag_processing/processor.py:
##########
@@ -229,8 +242,7 @@ def _parse_file(msg: DagFileParseRequest, log: FilteringBoundLogger) -> DagFileP
fileloc=msg.file,
serialized_dags=serialized_dags,
import_errors=bag.import_errors,
- # TODO: Make `bag.dag_warnings` not return SQLA model objects
- warnings=[],
+ warnings=stability_check_result.get_warning_dag_format_dict(bag.dag_ids),
Review Comment:
Will this not override other dag warnings?
--
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-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org