Skip to content

Error handling in SchedulerJobRunner and improve datetime deserializa… - #54775

Closed
abhishekbhakat wants to merge 3 commits into
apache:v2-11-testfrom
abhishekbhakat:54771-scheduler-guardrail
Closed

abhishekbhakat wants to merge 3 commits into
apache:v2-11-testfrom
abhishekbhakat:54771-scheduler-guardrail

Conversation

@abhishekbhakat

@abhishekbhakat abhishekbhakat commented Aug 21, 2025 •

Copy link
Copy Markdown
Contributor

related #54771

Also applies to main. Will raise a PR for main as well.

@abhishekbhakat
abhishekbhakat marked this pull request as draft August 21, 2025 11:38
@abhishekbhakat

Copy link
Copy Markdown
Contributor Author

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

@abhishekbhakat
abhishekbhakat marked this pull request as ready for review August 21, 2025 11:54

@alvinzhangdd alvinzhangdd left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@kaxil kaxil added this to the Airflow 2.11.1 milestone Aug 22, 2025
@abhishekbhakat
abhishekbhakat marked this pull request as draft August 25, 2025 07:23
@abhishekbhakat

abhishekbhakat commented Aug 25, 2025 •

Copy link
Copy Markdown
Contributor Author

@alvinzhangdd

If a task’s end_date is a Jinja template string and gets stored in serialized_dag, deserialization will keep it
as that string (no coercion, no default).

The field will not be null; it stays a string. That can break scheduling later:

  • RunnableExecDateDep compares logical_date > ti.task.end_date and calls .isoformat() on it. A string end_date will raise a TypeError/AttributeError at this check.
  • If it had been None, there would be no issue (no comparisons done).

But I don't believe setting it as None is helpful. If anything, it just promotes bad dag writing practices.
Let me see if I can raise a broken dag error instead to let the user resolve the problem (it's not straight forward as jinja is not resolved untill runtime).

@alvinzhangdd

Copy link
Copy Markdown

@abhishekbhakat
Please check the google doc I shared with you in the channel. I did a local testing with

  • Patch 1
    • Only add try block to scheduler_job_runner.
  • Patch 2
    • Add try block to scheduler_job_runner.
    • Skip deserializing _date fields which are not int/float.

I used a malformed dag with task level param start_date, end_date using jinjia template.

  • Patch 1
    • When unpause dag, scheduler will not crash, just cannot create dag run for the dag.
    • Scheduler shows error log on create dag run
  • Patch 2
    • When unpause dag, scheduler will crash. The error is task.end_date is None
    • Reason is that the skip deserialization made end_date = None.

So if skipping the deserialization on _date, it will crash the scheduler as well.

scheduler-1     | [2025-08-22T21:21:53.314+0000] {scheduler_job_runner.py:1196} ERROR - Failed creating DagRun for foo_bar_dag
scheduler-1     | Traceback (most recent call last):
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/airflow/jobs/scheduler_job_runner.py", line 1180, in _create_dag_runs
scheduler-1     |     dag.create_dagrun(
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/airflow/utils/session.py", line 76, in wrapper
scheduler-1     |     return func(*args, **kwargs)
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/airflow/models/dag.py", line 3039, in create_dagrun
scheduler-1     |     run.verify_integrity(session=session)
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/airflow/utils/session.py", line 76, in wrapper
scheduler-1     |     return func(*args, **kwargs)
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/airflow/models/dagrun.py", line 1206, in verify_integrity
scheduler-1     |     self._create_task_instances(self.dag_id, tis_to_create, created_counts, hook_is_noop, session=session)
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/airflow/models/dagrun.py", line 1394, in _create_task_instances
scheduler-1     |     session.bulk_insert_mappings(TI, tasks)
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 3810, in bulk_insert_mappings
scheduler-1     |     self._bulk_save_mappings(
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 3913, in _bulk_save_mappings
scheduler-1     |     transaction.rollback(_capture_exception=True)
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/sqlalchemy/util/langhelpers.py", line 70, in __exit__
scheduler-1     |     compat.raise_(
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 211, in raise_
scheduler-1     |     raise exception
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 3901, in _bulk_save_mappings
scheduler-1     |     persistence._bulk_insert(
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/persistence.py", line 72, in _bulk_insert
scheduler-1     |     mappings = list(mappings)
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/airflow/models/dagrun.py", line 1355, in _create_tasks
scheduler-1     |     for task in tasks:
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/airflow/models/dagrun.py", line 1204, in <genexpr>
scheduler-1     |     tasks_to_create = (task for task in dag.task_dict.values() if task_filter(task))
scheduler-1     |   File "/usr/local/lib/python3.8/site-packages/airflow/models/dagrun.py", line 1197, in task_filter
scheduler-1     |     and (task.end_date is None or self.execution_date <= task.end_date)
scheduler-1     | TypeError: '<=' not supported between instances of 'DateTime' and 'str'

@uranusjr

Copy link
Copy Markdown
Member

Does this not apply to main? It seems to me the logic around this did not change too much.

@abhishekbhakat

Copy link
Copy Markdown
Contributor Author

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.

@abhishekbhakat

Copy link
Copy Markdown
Contributor Author

@alvinzhangdd I think we should just raise Broken Dag error. Rather than letting scheduler deal with jinja rendering.

@abhishekbhakat
abhishekbhakat force-pushed the 54771-scheduler-guardrail branch from bd447ca to 6dc1484 Compare August 30, 2025 06:40
@abhishekbhakat

Copy link
Copy Markdown
Contributor Author

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.

@abhishekbhakat

Copy link
Copy Markdown
Contributor Author

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]

@abhishekbhakat
abhishekbhakat marked this pull request as ready for review August 30, 2025 08:46
Comment thread airflow/jobs/scheduler_job_runner.py Outdated
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:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@uranusjr do you have a comment about it or are you ok with a broad exception?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants