Repository: apache/airflow

Issue:
`retry_exponential_backoff` algorithm does not account for case when `retry_delay` is zero
<!--

Welcome to Apache Airflow!  For a smooth issue process, try to answer the following questions.
Don't worry if they're not all applicable; just try to include what you can :-)

If you need to include code snippets or logs, please put them in fenced code
blocks.  If they're super-long, please use the details tag like
<details><summary>super-long log</summary> lots of stuff </details>

Please delete these comment blocks before submitting the issue.

-->

<!--

IMPORTANT!!!

PLEASE CHECK "SIMILAR TO X EXISTING ISSUES" OPTION IF VISIBLE
NEXT TO "SUBMIT NEW ISSUE" BUTTON!!!

PLEASE CHECK IF THIS ISSUE HAS BEEN REPORTED PREVIOUSLY USING SEARCH!!!

Please complete the next sections or the issue will be closed.
These questions are the first thing we need to know to understand the context.

-->

**Apache Airflow version**: 2.1.2


**Kubernetes version (if you are using kubernetes)** (use `kubectl version`):

**Environment**:

- **Cloud provider or hardware configuration**:
- **OS** (e.g. from /etc/os-release):
- **Kernel** (e.g. `uname -a`):
- **Install tools**:
- **Others**:

**What happened**:
When `retry_exponential_backoff` is enabled and `retry_interval` is inadvertently set to zero, a divide by zero error occurs in the `modded_hash` calculation of the exponential backoff algorithm, causing the scheduler to crash.

<!-- (please include exact error messages if you can) -->

**What you expected to happen**:
Scheduler should treat it as a task with `retry_delay` of zero.

<!-- What do you think went wrong? -->

**How to reproduce it**:
Create a task with `retry_delay=timedelta()` and `retry_exponential_backoff=True`.
<!---

As minimally and precisely as possible. Keep in mind we do not have access to your cluster or dags.

If you are using kubernetes, please attempt to recreate the issue using minikube or kind.

## Install minikube/kind

- Minikube https://minikube.sigs.k8s.io/docs/start/
- Kind https://kind.sigs.k8s.io/docs/user/quick-start/

If this is a UI bug, please provide a screenshot of the bug or a link to a youtube video of the bug in action

You can include images using the .md style of
![alt text](http://url/to/img.png)

To record a screencast, mac users can use QuickTime and then create an unlisted youtube video with the resulting .mov file.

--->


**Anything else we need to know**:
Willing to submit a PR; opened #17003 (WIP) with possible fix.

<!--

How often does this problem occur? Once? Every time etc?

Any relevant logs to include? Put them here in side a detail tag:
<details><summary>x.log</summary> lots of stuff </details>

-->



Discussion:

Resolving patch:
diff --git a/airflow/models/taskinstance.py b/airflow/models/taskinstance.py
--- a/airflow/models/taskinstance.py
+++ b/airflow/models/taskinstance.py
@@ -1066,6 +1066,14 @@ def next_retry_datetime(self):
             # we must round up prior to converting to an int, otherwise a divide by zero error
             # will occur in the modded_hash calculation.
             min_backoff = int(math.ceil(delay.total_seconds() * (2 ** (self.try_number - 2))))
+
+            # In the case when delay.total_seconds() is 0, min_backoff will not be rounded up to 1.
+            # To address this, we impose a lower bound of 1 on min_backoff. This effectively makes
+            # the ceiling function unnecessary, but the ceiling function was retained to avoid
+            # introducing a breaking change.
+            if min_backoff < 1:
+                min_backoff = 1
+
             # deterministic per task instance
             ti_hash = int(
                 hashlib.sha1(


Test patch:
diff --git a/tests/models/test_taskinstance.py b/tests/models/test_taskinstance.py
--- a/tests/models/test_taskinstance.py
+++ b/tests/models/test_taskinstance.py
@@ -621,13 +621,14 @@ def test_next_retry_datetime(self, dag_maker):
         date = ti.next_retry_datetime()
         assert date == ti.end_date + max_delay
 
-    def test_next_retry_datetime_short_intervals(self, dag_maker):
-        delay = datetime.timedelta(seconds=1)
+    @pytest.mark.parametrize("seconds", [0, 0.5, 1])
+    def test_next_retry_datetime_short_or_zero_intervals(self, dag_maker, seconds):
+        delay = datetime.timedelta(seconds=seconds)
         max_delay = datetime.timedelta(minutes=60)
 
         with dag_maker(dag_id='fail_dag'):
             task = BashOperator(
-                task_id='task_with_exp_backoff_and_short_time_interval',
+                task_id='task_with_exp_backoff_and_short_or_zero_time_interval',
                 bash_command='exit 1',
                 retries=3,
                 retry_delay=delay,
@@ -639,9 +640,7 @@ def test_next_retry_datetime_short_intervals(self, dag_maker):
         ti.end_date = pendulum.instance(timezone.utcnow())
 
         date = ti.next_retry_datetime()
-        # between 1 * 2^0.5 and 1 * 2^1 (15 and 30)
-        period = ti.end_date.add(seconds=15) - ti.end_date.add(seconds=1)
-        assert date in period
+        assert date == ti.end_date + datetime.timedelta(seconds=1)
 
     def test_reschedule_handling(self, dag_maker):
         """