Repository navigation
Error handling in SchedulerJobRunner and improve datetime deserializa… - #54775
abhishekbhakat wants to merge 3 commits into
Conversation
|
Added tests that fail without the changes: _________________________________ test_dag_deserialize_ignores_templated_date_strings __________________________________
def test_dag_deserialize_ignores_templated_date_strings():
"""
Ensure that deserializing a DAG with a templated string in a *_date field
does not attempt datetime coercion that would crash with a TypeError.
This would fail prior to the guard that checks the value type is numeric.
"""
dag = DAG(
dag_id="test_templated_date_in_dag",
schedule=None,
start_date=timezone.datetime(2021, 1, 1),
)
dag.end_date = TEMPLATE_STR
serialized = SerializedDAG.serialize_dag(dag)
assert serialized.get("end_date") == TEMPLATE_STR
# Would raise TypeError before the fix; should round-trip now
> deserialized = SerializedDAG.deserialize_dag(serialized)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tests/serialization/test_templated_date_fields.py:76:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
airflow/serialization/serialized_objects.py:1711: in deserialize_dag
v = cls._deserialize_datetime(v)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
timestamp = "{{ (data_interval_end - macros.timedelta(days=4)).strftime('%Y-%m-%d') }}", tz = Timezone('UTC')
def from_timestamp(
timestamp: int | float, tz: str | FixedTimezone | Timezone | Literal["local"] = utc
) -> DateTime:
"""
Parse timestamp and return DateTime in a given time zone.
:param timestamp: epoch time in seconds.
:param tz: In which timezone should return a resulting object.
Could be either one of pendulum timezone, IANA timezone or `local` literal.
:meta private:
"""
> result = coerce_datetime(dt.datetime.fromtimestamp(timestamp, tz=utc))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E TypeError: 'str' object cannot be interpreted as an integer
airflow/utils/timezone.py:316: TypeError
=============================================== short test summary info ================================================
FAILED tests/serialization/test_templated_date_fields.py::test_operator_deserialize_ignores_templated_date_strings - TypeError: 'str' object cannot be interpreted as an integer
FAILED tests/serialization/test_templated_date_fields.py::test_dag_deserialize_ignores_templated_date_strings - TypeError: 'str' object cannot be interpreted as an integer
================================================== 2 failed in 0.99s =================================================== |
There was a problem hiding this comment.
Looks like the phenomenon after the change would be, the malformed dag using jinjia template on reserved keyword will still show in Airflow UI (parsed), but on its schedule, it won’t create dag run. Then we go to the scheduler log to find this error log, and notify users to fix the malformed dag.
But the malformed dag file would still make it to the serialized_dag table, and stay there. If we didn't capture the above, it will stay there forever.
| @@ -1306,7 +1306,8 @@ def populate_operator(cls, op: Operator, encoded_op: dict[str, Any]) -> None: | |||
| elif k == "resources": | |||
| v = Resources.from_dict(v) | |||
| elif k.endswith("_date"): | |||
| v = cls._deserialize_datetime(v) | |||
| if isinstance(v, (int, float)): | |||
There was a problem hiding this comment.
This is task level, let's set the scenario: someone assigns end_date = jinjia template, and pass it to the task level, and stores to serialized_dag.
In this scenario, it skips the string end_date, but would the deserialized object in create_dag_run populate a default value for the task level end_date? if not would it create null end_date and cause issue?
In the production example, we saw task level start_date was serialized to the dag-level start_date, and is a correct float, but end_date was serialized as the template string.
| @@ -1708,7 +1709,8 @@ def deserialize_dag(cls, encoded_dag: dict[str, Any]) -> SerializedDAG: | |||
| elif k == "dagrun_timeout": | |||
| v = cls._deserialize_timedelta(v) | |||
| elif k.endswith("_date"): | |||
| v = cls._deserialize_datetime(v) | |||
| if isinstance(v, (int, float)): | |||
There was a problem hiding this comment.
This is the dag level start_date and end_date.
Same scenario, if someone assigns start_date, end_date as jinjia template and pass to dag.
This would skip, would it cause issue if dag-level start_date is null?
|
If a task’s end_date is a Jinja template string and gets stored in serialized_dag, deserialization will keep it The field will not be null; it stays a string. That can break scheduling later:
But I don't believe setting it as None is helpful. If anything, it just promotes bad dag writing practices. |
|
@abhishekbhakat
I used a malformed dag with task level param start_date, end_date using jinjia template.
So if skipping the deserialization on _date, it will crash the scheduler as well. |
|
Does this not apply to main? It seems to me the logic around this did not change too much. |
It does apply to main. I'm working with @alvinzhangdd to confirm a solution on 2.11 and will raise a PR for main once we have things sorted out. |
|
@alvinzhangdd I think we should just raise Broken Dag error. Rather than letting scheduler deal with jinja rendering. |
bd447ca to
6dc1484
Compare
|
The changes add validation logic to the DAG constructor that checks task start_date and end_date fields for proper datetime formatting, and validates templated arguments in task args. When tasks use Jinja templates in their args parameter, the system now verifies that template_fields includes 'args' and performs dry-rendering of datetime templates to catch invalid date expressions before runtime. The DagBag error reporting is enhanced with configurable full traceback support, and the scheduler job runner now includes exception handling around DAG loading to prevent crashes from malformed DAGs. Also added tests with sample dags to validate the scenarios. |
|
sample traceback this raises: Broken DAG: [/Users/abhishekbhakat/Desktop/my_airflow/AIRFLOW_HOME/dags/dag_that_crash_scheduler_2.py]
Traceback (most recent call last):
File "/Users/abhishekbhakat/Desktop/my_airflow/airflow/utils/timezone.py", line 101, in convert_to_utc
if not is_localized(value):
^^^^^^^^^^^^^^^^^^^
File "/Users/abhishekbhakat/Desktop/my_airflow/airflow/utils/timezone.py", line 51, in is_localized
return value.utcoffset() is not None
^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'utcoffset'Broken DAG: [/Users/abhishekbhakat/Desktop/my_airflow/AIRFLOW_HOME/dags/dag_using_dry_render_bad.py]
Traceback (most recent call last):
File "/Users/abhishekbhakat/Desktop/my_airflow/.venv/lib/python3.11/site-packages/pendulum/parsing/__init__.py", line 78, in parse
return _normalize(_parse(text, **_options), **_options)
^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/abhishekbhakat/Desktop/my_airflow/.venv/lib/python3.11/site-packages/pendulum/parsing/__init__.py", line 125, in _parse
raise ParserError(f"Unable to parse string [{text}]")
pendulum.parsing.exceptions.ParserError: Unable to parse string [not-a-date] |
| dag = self.dagbag.get_dag(dag_model.dag_id, session=session) | ||
| try: | ||
| dag = self.dagbag.get_dag(dag_model.dag_id, session=session) | ||
| except Exception: |
There was a problem hiding this comment.
I’m not fond of this catches everything. Do we really expect this to fail with many kinds of exceptions? Such a broad clause tend to lead to bugs being difficult to investigate.
Can we limit this and the one below?
There was a problem hiding this comment.
I can raise specifically for serialization error. Which I'll have to import in job runner.
But I feel like broad exception handling is insurance against scheduler failure.
No matter what error arises, scheduler should never fail.
More specific exception handling belongs in DAG parsing logic or DAG serialization methods.
We can log the exception message. Let me know if you still think we should raise a specific exception.
There was a problem hiding this comment.
@uranusjr do you have a comment about it or are you ok with a broad exception?
related #54771
Also applies to main. Will raise a PR for main as well.