-
Notifications
You must be signed in to change notification settings - Fork 14.5k
/
Copy pathtest_taskinstance.py
4314 lines (3625 loc) · 160 KB
/
test_taskinstance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# 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 contextlib
import datetime
import operator
import os
import pathlib
import pickle
import signal
import sys
import urllib
from traceback import format_exception
from typing import cast
from unittest import mock
from unittest.mock import call, mock_open, patch
from uuid import uuid4
import pendulum
import pytest
import time_machine
from airflow import settings
from airflow.decorators import task, task_group
from airflow.example_dags.plugins.workday import AfterWorkdayTimetable
from airflow.exceptions import (
AirflowException,
AirflowFailException,
AirflowRescheduleException,
AirflowSensorTimeout,
AirflowSkipException,
UnmappableXComLengthPushed,
UnmappableXComTypePushed,
XComForMappingNotPushed,
)
from airflow.models.connection import Connection
from airflow.models.dag import DAG
from airflow.models.dagbag import DagBag
from airflow.models.dagrun import DagRun
from airflow.models.dataset import DatasetDagRunQueue, DatasetEvent, DatasetModel
from airflow.models.expandinput import EXPAND_INPUT_EMPTY, NotFullyPopulated
from airflow.models.param import process_params
from airflow.models.pool import Pool
from airflow.models.renderedtifields import RenderedTaskInstanceFields
from airflow.models.serialized_dag import SerializedDagModel
from airflow.models.taskfail import TaskFail
from airflow.models.taskinstance import (
TaskInstance,
TaskInstance as TI,
TaskInstanceNote,
_run_finished_callback,
)
from airflow.models.taskmap import TaskMap
from airflow.models.taskreschedule import TaskReschedule
from airflow.models.variable import Variable
from airflow.models.xcom import LazyXComAccess, XCom
from airflow.operators.bash import BashOperator
from airflow.operators.empty import EmptyOperator
from airflow.operators.python import PythonOperator
from airflow.sensors.base import BaseSensorOperator
from airflow.sensors.python import PythonSensor
from airflow.serialization.serialized_objects import SerializedBaseOperator, SerializedDAG
from airflow.settings import TIMEZONE
from airflow.stats import Stats
from airflow.ti_deps.dep_context import DepContext
from airflow.ti_deps.dependencies_deps import REQUEUEABLE_DEPS, RUNNING_DEPS
from airflow.ti_deps.dependencies_states import RUNNABLE_STATES
from airflow.ti_deps.deps.base_ti_dep import TIDepStatus
from airflow.ti_deps.deps.trigger_rule_dep import TriggerRuleDep, _UpstreamTIStates
from airflow.utils import timezone
from airflow.utils.db import merge_conn
from airflow.utils.module_loading import qualname
from airflow.utils.session import create_session, provide_session
from airflow.utils.state import DagRunState, State, TaskInstanceState
from airflow.utils.task_group import TaskGroup
from airflow.utils.types import DagRunType
from airflow.utils.xcom import XCOM_RETURN_KEY
from tests.models import DEFAULT_DATE, TEST_DAGS_FOLDER
from tests.test_utils import db
from tests.test_utils.config import conf_vars
from tests.test_utils.db import clear_db_connections, clear_db_runs
from tests.test_utils.mock_operators import MockOperator
@pytest.fixture
def test_pool():
with create_session() as session:
test_pool = Pool(pool="test_pool", slots=1, include_deferred=False)
session.add(test_pool)
session.flush()
yield test_pool
session.rollback()
@pytest.fixture
def task_reschedules_for_ti():
def wrapper(ti):
with create_session() as session:
return session.scalars(TaskReschedule.stmt_for_task_instance(ti=ti, descending=False)).all()
return wrapper
class CallbackWrapper:
task_id: str | None = None
dag_id: str | None = None
execution_date: datetime.datetime | None = None
task_state_in_callback: str | None = None
callback_ran = False
def wrap_task_instance(self, ti):
self.task_id = ti.task_id
self.dag_id = ti.dag_id
self.execution_date = ti.execution_date
self.task_state_in_callback = ""
self.callback_ran = False
def success_handler(self, context):
self.callback_ran = True
self.task_state_in_callback = context["ti"].state
class TestTaskInstance:
@staticmethod
def clean_db():
db.clear_db_dags()
db.clear_db_pools()
db.clear_db_runs()
db.clear_db_task_fail()
db.clear_rendered_ti_fields()
db.clear_db_task_reschedule()
db.clear_db_datasets()
db.clear_db_xcom()
def setup_method(self):
self.clean_db()
# We don't want to store any code for (test) dags created in this file
with patch.object(settings, "STORE_DAG_CODE", False):
yield
def teardown_method(self):
self.clean_db()
def test_set_task_dates(self, dag_maker):
"""
Test that tasks properly take start/end dates from DAGs
"""
with dag_maker("dag", end_date=DEFAULT_DATE + datetime.timedelta(days=10)) as dag:
pass
op1 = EmptyOperator(task_id="op_1")
assert op1.start_date is None and op1.end_date is None
# dag should assign its dates to op1 because op1 has no dates
dag.add_task(op1)
dag_maker.create_dagrun()
assert op1.start_date == dag.start_date and op1.end_date == dag.end_date
op2 = EmptyOperator(
task_id="op_2",
start_date=DEFAULT_DATE - datetime.timedelta(days=1),
end_date=DEFAULT_DATE + datetime.timedelta(days=11),
)
# dag should assign its dates to op2 because they are more restrictive
dag.add_task(op2)
assert op2.start_date == dag.start_date and op2.end_date == dag.end_date
op3 = EmptyOperator(
task_id="op_3",
start_date=DEFAULT_DATE + datetime.timedelta(days=1),
end_date=DEFAULT_DATE + datetime.timedelta(days=9),
)
# op3 should keep its dates because they are more restrictive
dag.add_task(op3)
assert op3.start_date == DEFAULT_DATE + datetime.timedelta(days=1)
assert op3.end_date == DEFAULT_DATE + datetime.timedelta(days=9)
def test_current_state(self, create_task_instance, session):
ti = create_task_instance(session=session)
assert ti.current_state(session=session) is None
ti.run()
assert ti.current_state(session=session) == State.SUCCESS
def test_set_dag(self, dag_maker):
"""
Test assigning Operators to Dags, including deferred assignment
"""
with dag_maker("dag") as dag:
pass
with dag_maker("dag2") as dag2:
pass
op = EmptyOperator(task_id="op_1")
# no dag assigned
assert not op.has_dag()
with pytest.raises(AirflowException):
getattr(op, "dag")
# no improper assignment
with pytest.raises(TypeError):
op.dag = 1
op.dag = dag
# no reassignment
with pytest.raises(AirflowException):
op.dag = dag2
# but assigning the same dag is ok
op.dag = dag
assert op.dag is dag
assert op in dag.tasks
def test_infer_dag(self, create_dummy_dag):
op1 = EmptyOperator(task_id="test_op_1")
op2 = EmptyOperator(task_id="test_op_2")
dag, op3 = create_dummy_dag(task_id="test_op_3")
_, op4 = create_dummy_dag("dag2", task_id="test_op_4")
# double check dags
assert [i.has_dag() for i in [op1, op2, op3, op4]] == [False, False, True, True]
# can't combine operators with no dags
with pytest.raises(AirflowException):
op1.set_downstream(op2)
# op2 should infer dag from op1
op1.dag = dag
op1.set_downstream(op2)
assert op2.dag is dag
# can't assign across multiple DAGs
with pytest.raises(AirflowException):
op1.set_downstream(op4)
with pytest.raises(AirflowException):
op1.set_downstream([op3, op4])
def test_bitshift_compose_operators(self, dag_maker):
with dag_maker("dag"):
op1 = EmptyOperator(task_id="test_op_1")
op2 = EmptyOperator(task_id="test_op_2")
op3 = EmptyOperator(task_id="test_op_3")
op1 >> op2 << op3
dag_maker.create_dagrun()
# op2 should be downstream of both
assert op2 in op1.downstream_list
assert op2 in op3.downstream_list
def test_init_on_load(self, create_task_instance):
ti = create_task_instance()
# ensure log is correctly created for ORM ti
assert ti.log.name == "airflow.task"
assert not ti.test_mode
@patch.object(DAG, "get_concurrency_reached")
def test_requeue_over_dag_concurrency(self, mock_concurrency_reached, create_task_instance):
mock_concurrency_reached.return_value = True
ti = create_task_instance(
dag_id="test_requeue_over_dag_concurrency",
task_id="test_requeue_over_dag_concurrency_op",
max_active_runs=1,
max_active_tasks=2,
dagrun_state=State.QUEUED,
)
ti.run()
assert ti.state == State.NONE
def test_requeue_over_max_active_tis_per_dag(self, create_task_instance):
ti = create_task_instance(
dag_id="test_requeue_over_max_active_tis_per_dag",
task_id="test_requeue_over_max_active_tis_per_dag_op",
max_active_tis_per_dag=0,
max_active_runs=1,
max_active_tasks=2,
dagrun_state=State.QUEUED,
)
ti.run()
assert ti.state == State.NONE
def test_requeue_over_max_active_tis_per_dagrun(self, create_task_instance):
ti = create_task_instance(
dag_id="test_requeue_over_max_active_tis_per_dagrun",
task_id="test_requeue_over_max_active_tis_per_dagrun_op",
max_active_tis_per_dagrun=0,
max_active_runs=1,
max_active_tasks=2,
dagrun_state=State.QUEUED,
)
ti.run()
assert ti.state == State.NONE
def test_requeue_over_pool_concurrency(self, create_task_instance, test_pool):
ti = create_task_instance(
dag_id="test_requeue_over_pool_concurrency",
task_id="test_requeue_over_pool_concurrency_op",
max_active_tis_per_dag=0,
max_active_runs=1,
max_active_tasks=2,
)
with create_session() as session:
test_pool.slots = 0
session.flush()
ti.run()
assert ti.state == State.NONE
@pytest.mark.usefixtures("test_pool")
def test_not_requeue_non_requeueable_task_instance(self, dag_maker):
# Use BaseSensorOperator because sensor got
# one additional DEP in BaseSensorOperator().deps
with dag_maker(dag_id="test_not_requeue_non_requeueable_task_instance"):
task = BaseSensorOperator(
task_id="test_not_requeue_non_requeueable_task_instance_op",
pool="test_pool",
)
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
ti.state = State.QUEUED
with create_session() as session:
session.add(ti)
session.commit()
all_deps = RUNNING_DEPS | task.deps
all_non_requeueable_deps = all_deps - REQUEUEABLE_DEPS
patch_dict = {}
for dep in all_non_requeueable_deps:
class_name = dep.__class__.__name__
dep_patch = patch(f"{dep.__module__}.{class_name}.{dep._get_dep_statuses.__name__}")
method_patch = dep_patch.start()
method_patch.return_value = iter([TIDepStatus("mock_" + class_name, True, "mock")])
patch_dict[class_name] = (dep_patch, method_patch)
for class_name, (dep_patch, method_patch) in patch_dict.items():
method_patch.return_value = iter([TIDepStatus("mock_" + class_name, False, "mock")])
ti.run()
assert ti.state == State.QUEUED
dep_patch.return_value = TIDepStatus("mock_" + class_name, True, "mock")
for dep_patch, method_patch in patch_dict.values():
dep_patch.stop()
def test_mark_non_runnable_task_as_success(self, create_task_instance):
"""
test that running task with mark_success param update task state
as SUCCESS without running task despite it fails dependency checks.
"""
non_runnable_state = (set(State.task_states) - RUNNABLE_STATES - set(State.SUCCESS)).pop()
ti = create_task_instance(
dag_id="test_mark_non_runnable_task_as_success",
task_id="test_mark_non_runnable_task_as_success_op",
state=non_runnable_state,
)
ti.run(mark_success=True)
assert ti.state == State.SUCCESS
@pytest.mark.usefixtures("test_pool")
def test_run_pooling_task(self, create_task_instance):
"""
test that running a task in an existing pool update task state as SUCCESS.
"""
ti = create_task_instance(
dag_id="test_run_pooling_task",
task_id="test_run_pooling_task_op",
pool="test_pool",
)
ti.run()
assert ti.state == State.SUCCESS
@pytest.mark.usefixtures("test_pool")
def test_pool_slots_property(self):
"""
test that try to create a task with pool_slots less than 1
"""
with pytest.raises(ValueError, match="pool slots .* cannot be less than 1"):
dag = DAG(dag_id="test_run_pooling_task")
EmptyOperator(
task_id="test_run_pooling_task_op",
dag=dag,
pool="test_pool",
pool_slots=0,
)
@provide_session
def test_ti_updates_with_task(self, create_task_instance, session=None):
"""
test that updating the executor_config propagates to the TaskInstance DB
"""
ti = create_task_instance(
dag_id="test_run_pooling_task",
task_id="test_run_pooling_task_op",
executor_config={"foo": "bar"},
)
dag = ti.task.dag
ti.run(session=session)
tis = dag.get_task_instances()
assert {"foo": "bar"} == tis[0].executor_config
task2 = EmptyOperator(
task_id="test_run_pooling_task_op2",
executor_config={"bar": "baz"},
start_date=timezone.datetime(2016, 2, 1, 0, 0, 0),
dag=dag,
)
ti2 = TI(task=task2, run_id=ti.run_id)
session.add(ti2)
session.flush()
ti2.run(session=session)
# Ensure it's reloaded
ti2.executor_config = None
ti2.refresh_from_db(session)
assert {"bar": "baz"} == ti2.executor_config
session.rollback()
def test_run_pooling_task_with_mark_success(self, create_task_instance):
"""
test that running task in an existing pool with mark_success param
update task state as SUCCESS without running task
despite it fails dependency checks.
"""
ti = create_task_instance(
dag_id="test_run_pooling_task_with_mark_success",
task_id="test_run_pooling_task_with_mark_success_op",
)
ti.run(mark_success=True)
assert ti.state == State.SUCCESS
def test_run_pooling_task_with_skip(self, dag_maker):
"""
test that running task which returns AirflowSkipOperator will end
up in a SKIPPED state.
"""
def raise_skip_exception():
raise AirflowSkipException
with dag_maker(dag_id="test_run_pooling_task_with_skip"):
task = PythonOperator(
task_id="test_run_pooling_task_with_skip",
python_callable=raise_skip_exception,
)
dr = dag_maker.create_dagrun(execution_date=timezone.utcnow())
ti = dr.task_instances[0]
ti.task = task
ti.run()
assert State.SKIPPED == ti.state
def test_task_sigterm_calls_on_failure_callback(self, dag_maker, caplog):
"""
Test that ensures that tasks call on_failure_callback when they receive sigterm
"""
def task_function(ti):
os.kill(ti.pid, signal.SIGTERM)
with dag_maker():
task_ = PythonOperator(
task_id="test_on_failure",
python_callable=task_function,
on_failure_callback=lambda context: context["ti"].log.info("on_failure_callback called"),
)
dr = dag_maker.create_dagrun()
ti = dr.task_instances[0]
ti.task = task_
with pytest.raises(AirflowException):
ti.run()
assert "on_failure_callback called" in caplog.text
def test_task_sigterm_works_with_retries(self, dag_maker):
"""
Test that ensures that tasks are retried when they receive sigterm
"""
def task_function(ti):
os.kill(ti.pid, signal.SIGTERM)
with dag_maker("test_mark_failure_2"):
task = PythonOperator(
task_id="test_on_failure",
python_callable=task_function,
retries=1,
retry_delay=datetime.timedelta(seconds=2),
)
dr = dag_maker.create_dagrun()
ti = dr.task_instances[0]
ti.task = task
with pytest.raises(AirflowException):
ti.run()
ti.refresh_from_db()
assert ti.state == State.UP_FOR_RETRY
@pytest.mark.parametrize("state", [State.SUCCESS, State.FAILED, State.SKIPPED])
def test_task_sigterm_doesnt_change_state_of_finished_tasks(self, state, dag_maker):
session = settings.Session()
def task_function(ti):
ti.state = state
session.merge(ti)
session.commit()
raise AirflowException()
with dag_maker("test_mark_failure_2"):
task = PythonOperator(
task_id="test_on_failure",
python_callable=task_function,
)
dr = dag_maker.create_dagrun()
ti = dr.task_instances[0]
ti.task = task
ti.run()
ti.refresh_from_db()
ti.state == state
@pytest.mark.parametrize(
"state, exception, retries",
[
(State.FAILED, AirflowException, 0),
(State.SKIPPED, AirflowSkipException, 0),
(State.SUCCESS, None, 0),
(State.UP_FOR_RESCHEDULE, AirflowRescheduleException(timezone.utcnow()), 0),
(State.UP_FOR_RETRY, AirflowException, 1),
],
)
def test_task_wipes_next_fields(self, session, dag_maker, state, exception, retries):
"""
Test that ensures that tasks wipe their next_method and next_kwargs
when the TI enters one of the configured states.
"""
def _raise_if_exception():
if exception:
raise exception
with dag_maker("test_deferred_method_clear"):
task = PythonOperator(
task_id="test_deferred_method_clear_task",
python_callable=_raise_if_exception,
retries=retries,
retry_delay=datetime.timedelta(seconds=2),
)
dr = dag_maker.create_dagrun()
ti = dr.task_instances[0]
ti.next_method = "execute"
ti.next_kwargs = {}
session.merge(ti)
session.commit()
ti.task = task
if state in [State.FAILED, State.UP_FOR_RETRY]:
with pytest.raises(exception):
ti.run()
else:
ti.run()
ti.refresh_from_db()
assert ti.next_method is None
assert ti.next_kwargs is None
assert ti.state == state
def test_retry_delay(self, dag_maker, time_machine):
"""
Test that retry delays are respected
"""
time_machine.move_to("2021-09-19 04:56:35", tick=False)
with dag_maker(dag_id="test_retry_handling"):
task = BashOperator(
task_id="test_retry_handling_op",
bash_command="exit 1",
retries=1,
retry_delay=datetime.timedelta(seconds=3),
)
def run_with_error(ti):
with contextlib.suppress(AirflowException):
ti.run()
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
assert ti.try_number == 1
# first run -- up for retry
run_with_error(ti)
assert ti.state == State.UP_FOR_RETRY
assert ti.try_number == 2
# second run -- still up for retry because retry_delay hasn't expired
time_machine.coordinates.shift(3)
run_with_error(ti)
assert ti.state == State.UP_FOR_RETRY
# third run -- failed
time_machine.coordinates.shift(datetime.datetime.resolution)
run_with_error(ti)
assert ti.state == State.FAILED
def test_retry_handling(self, dag_maker):
"""
Test that task retries are handled properly
"""
expected_rendered_ti_fields = {"env": None, "bash_command": "echo test_retry_handling; exit 1"}
with dag_maker(dag_id="test_retry_handling") as dag:
task = BashOperator(
task_id="test_retry_handling_op",
bash_command="echo {{dag.dag_id}}; exit 1",
retries=1,
retry_delay=datetime.timedelta(seconds=0),
)
def run_with_error(ti):
with contextlib.suppress(AirflowException):
ti.run()
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
assert ti.try_number == 1
# first run -- up for retry
run_with_error(ti)
assert ti.state == State.UP_FOR_RETRY
assert ti._try_number == 1
assert ti.try_number == 2
# second run -- fail
run_with_error(ti)
assert ti.state == State.FAILED
assert ti._try_number == 2
assert ti.try_number == 3
# Clear the TI state since you can't run a task with a FAILED state without
# clearing it first
dag.clear()
# third run -- up for retry
run_with_error(ti)
assert ti.state == State.UP_FOR_RETRY
assert ti._try_number == 3
assert ti.try_number == 4
# fourth run -- fail
run_with_error(ti)
ti.refresh_from_db()
assert ti.state == State.FAILED
assert ti._try_number == 4
assert ti.try_number == 5
assert RenderedTaskInstanceFields.get_templated_fields(ti) == expected_rendered_ti_fields
def test_next_retry_datetime(self, dag_maker):
delay = datetime.timedelta(seconds=30)
max_delay = datetime.timedelta(minutes=60)
with dag_maker(dag_id="fail_dag"):
task = BashOperator(
task_id="task_with_exp_backoff_and_max_delay",
bash_command="exit 1",
retries=3,
retry_delay=delay,
retry_exponential_backoff=True,
max_retry_delay=max_delay,
)
ti = dag_maker.create_dagrun().task_instances[0]
ti.task = task
ti.end_date = pendulum.instance(timezone.utcnow())
date = ti.next_retry_datetime()
# between 30 * 2^0.5 and 30 * 2^1 (15 and 30)
period = ti.end_date.add(seconds=30) - ti.end_date.add(seconds=15)
assert date in period
ti.try_number = 3
date = ti.next_retry_datetime()
# between 30 * 2^2 and 30 * 2^3 (120 and 240)
period = ti.end_date.add(seconds=240) - ti.end_date.add(seconds=120)
assert date in period
ti.try_number = 5
date = ti.next_retry_datetime()
# between 30 * 2^4 and 30 * 2^5 (480 and 960)
period = ti.end_date.add(seconds=960) - ti.end_date.add(seconds=480)
assert date in period
ti.try_number = 9
date = ti.next_retry_datetime()
assert date == ti.end_date + max_delay
ti.try_number = 50
date = ti.next_retry_datetime()
assert date == ti.end_date + max_delay
@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_or_zero_time_interval",
bash_command="exit 1",
retries=3,
retry_delay=delay,
retry_exponential_backoff=True,
max_retry_delay=max_delay,
)
ti = dag_maker.create_dagrun().task_instances[0]
ti.task = task
ti.end_date = pendulum.instance(timezone.utcnow())
date = ti.next_retry_datetime()
assert date == ti.end_date + datetime.timedelta(seconds=1)
def test_reschedule_handling(self, dag_maker, task_reschedules_for_ti):
"""
Test that task reschedules are handled properly
"""
# Return values of the python sensor callable, modified during tests
done = False
fail = False
def func():
if fail:
raise AirflowException()
return done
with dag_maker(dag_id="test_reschedule_handling") as dag:
task = PythonSensor(
task_id="test_reschedule_handling_sensor",
poke_interval=0,
mode="reschedule",
python_callable=func,
retries=1,
retry_delay=datetime.timedelta(seconds=0),
)
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
assert ti._try_number == 0
assert ti.try_number == 1
def run_ti_and_assert(
run_date,
expected_start_date,
expected_end_date,
expected_duration,
expected_state,
expected_try_number,
expected_task_reschedule_count,
):
with time_machine.travel(run_date, tick=False):
try:
ti.run()
except AirflowException:
if not fail:
raise
ti.refresh_from_db()
assert ti.state == expected_state
assert ti._try_number == expected_try_number
assert ti.try_number == expected_try_number + 1
assert ti.start_date == expected_start_date
assert ti.end_date == expected_end_date
assert ti.duration == expected_duration
assert len(task_reschedules_for_ti(ti)) == expected_task_reschedule_count
date1 = timezone.utcnow()
date2 = date1 + datetime.timedelta(minutes=1)
date3 = date2 + datetime.timedelta(minutes=1)
date4 = date3 + datetime.timedelta(minutes=1)
# Run with multiple reschedules.
# During reschedule the try number remains the same, but each reschedule is recorded.
# The start date is expected to remain the initial date, hence the duration increases.
# When finished the try number is incremented and there is no reschedule expected
# for this try.
done, fail = False, False
run_ti_and_assert(date1, date1, date1, 0, State.UP_FOR_RESCHEDULE, 0, 1)
done, fail = False, False
run_ti_and_assert(date2, date1, date2, 60, State.UP_FOR_RESCHEDULE, 0, 2)
done, fail = False, False
run_ti_and_assert(date3, date1, date3, 120, State.UP_FOR_RESCHEDULE, 0, 3)
done, fail = True, False
run_ti_and_assert(date4, date1, date4, 180, State.SUCCESS, 1, 0)
# Clear the task instance.
dag.clear()
ti.refresh_from_db()
assert ti.state == State.NONE
assert ti._try_number == 1
# Run again after clearing with reschedules and a retry.
# The retry increments the try number, and for that try no reschedule is expected.
# After the retry the start date is reset, hence the duration is also reset.
done, fail = False, False
run_ti_and_assert(date1, date1, date1, 0, State.UP_FOR_RESCHEDULE, 1, 1)
done, fail = False, True
run_ti_and_assert(date2, date1, date2, 60, State.UP_FOR_RETRY, 2, 0)
done, fail = False, False
run_ti_and_assert(date3, date3, date3, 0, State.UP_FOR_RESCHEDULE, 2, 1)
done, fail = True, False
run_ti_and_assert(date4, date3, date4, 60, State.SUCCESS, 3, 0)
def test_mapped_reschedule_handling(self, dag_maker, task_reschedules_for_ti):
"""
Test that mapped task reschedules are handled properly
"""
# Return values of the python sensor callable, modified during tests
done = False
fail = False
def func():
if fail:
raise AirflowException()
return done
with dag_maker(dag_id="test_reschedule_handling") as dag:
task = PythonSensor.partial(
task_id="test_reschedule_handling_sensor",
mode="reschedule",
python_callable=func,
retries=1,
retry_delay=datetime.timedelta(seconds=0),
).expand(poke_interval=[0])
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
assert ti._try_number == 0
assert ti.try_number == 1
def run_ti_and_assert(
run_date,
expected_start_date,
expected_end_date,
expected_duration,
expected_state,
expected_try_number,
expected_task_reschedule_count,
):
ti.refresh_from_task(task)
with time_machine.travel(run_date, tick=False):
try:
ti.run()
except AirflowException:
if not fail:
raise
ti.refresh_from_db()
assert ti.state == expected_state
assert ti._try_number == expected_try_number
assert ti.try_number == expected_try_number + 1
assert ti.start_date == expected_start_date
assert ti.end_date == expected_end_date
assert ti.duration == expected_duration
assert len(task_reschedules_for_ti(ti)) == expected_task_reschedule_count
date1 = timezone.utcnow()
date2 = date1 + datetime.timedelta(minutes=1)
date3 = date2 + datetime.timedelta(minutes=1)
date4 = date3 + datetime.timedelta(minutes=1)
# Run with multiple reschedules.
# During reschedule the try number remains the same, but each reschedule is recorded.
# The start date is expected to remain the initial date, hence the duration increases.
# When finished the try number is incremented and there is no reschedule expected
# for this try.
done, fail = False, False
run_ti_and_assert(date1, date1, date1, 0, State.UP_FOR_RESCHEDULE, 0, 1)
done, fail = False, False
run_ti_and_assert(date2, date1, date2, 60, State.UP_FOR_RESCHEDULE, 0, 2)
done, fail = False, False
run_ti_and_assert(date3, date1, date3, 120, State.UP_FOR_RESCHEDULE, 0, 3)
done, fail = True, False
run_ti_and_assert(date4, date1, date4, 180, State.SUCCESS, 1, 0)
# Clear the task instance.
dag.clear()
ti.refresh_from_db()
assert ti.state == State.NONE
assert ti._try_number == 1
# Run again after clearing with reschedules and a retry.
# The retry increments the try number, and for that try no reschedule is expected.
# After the retry the start date is reset, hence the duration is also reset.
done, fail = False, False
run_ti_and_assert(date1, date1, date1, 0, State.UP_FOR_RESCHEDULE, 1, 1)
done, fail = False, True
run_ti_and_assert(date2, date1, date2, 60, State.UP_FOR_RETRY, 2, 0)
done, fail = False, False
run_ti_and_assert(date3, date3, date3, 0, State.UP_FOR_RESCHEDULE, 2, 1)
done, fail = True, False
run_ti_and_assert(date4, date3, date4, 60, State.SUCCESS, 3, 0)
@pytest.mark.usefixtures("test_pool")
def test_mapped_task_reschedule_handling_clear_reschedules(self, dag_maker, task_reschedules_for_ti):
"""
Test that mapped task reschedules clearing are handled properly
"""
# Return values of the python sensor callable, modified during tests
done = False
fail = False
def func():
if fail:
raise AirflowException()
return done
with dag_maker(dag_id="test_reschedule_handling") as dag:
task = PythonSensor.partial(
task_id="test_reschedule_handling_sensor",
mode="reschedule",
python_callable=func,
retries=1,
retry_delay=datetime.timedelta(seconds=0),
pool="test_pool",
).expand(poke_interval=[0])
ti = dag_maker.create_dagrun(execution_date=timezone.utcnow()).task_instances[0]
ti.task = task
assert ti._try_number == 0
assert ti.try_number == 1
def run_ti_and_assert(
run_date,
expected_start_date,
expected_end_date,
expected_duration,
expected_state,
expected_try_number,
expected_task_reschedule_count,
):
ti.refresh_from_task(task)
with time_machine.travel(run_date, tick=False):
try:
ti.run()
except AirflowException:
if not fail:
raise
ti.refresh_from_db()
assert ti.state == expected_state
assert ti._try_number == expected_try_number
assert ti.try_number == expected_try_number + 1
assert ti.start_date == expected_start_date
assert ti.end_date == expected_end_date
assert ti.duration == expected_duration
assert len(task_reschedules_for_ti(ti)) == expected_task_reschedule_count
date1 = timezone.utcnow()
done, fail = False, False
run_ti_and_assert(date1, date1, date1, 0, State.UP_FOR_RESCHEDULE, 0, 1)
# Clear the task instance.