-
Notifications
You must be signed in to change notification settings - Fork 17k
Expand file tree
/
Copy pathtest_supervisor.py
More file actions
3492 lines (3114 loc) · 127 KB
/
test_supervisor.py
File metadata and controls
3492 lines (3114 loc) · 127 KB
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 inspect
import json
import logging
import os
import re
import selectors
import signal
import socket
import subprocess
import sys
import time
from contextlib import nullcontext
from dataclasses import dataclass, field
from datetime import datetime, timezone as dt_timezone
from operator import attrgetter
from random import randint
from textwrap import dedent
from time import sleep
from typing import TYPE_CHECKING, Any
from unittest import mock
from unittest.mock import MagicMock, patch
import httpx
import msgspec
import psutil
import pytest
import structlog
from pytest_unordered import unordered
from task_sdk import FAKE_BUNDLE, make_client
from uuid6 import uuid7
from airflow.executors.workloads import BundleInfo
from airflow.sdk import BaseOperator, timezone
from airflow.sdk.api import client as sdk_client
from airflow.sdk.api.client import ServerResponseError
from airflow.sdk.api.datamodels._generated import (
AssetEventResponse,
AssetProfile,
AssetResponse,
DagRun,
DagRunState,
DagRunType,
PreviousTIResponse,
TaskInstance,
TaskInstanceState,
)
from airflow.sdk.exceptions import AirflowRuntimeError, ErrorType, TaskAlreadyRunningError
from airflow.sdk.execution_time import supervisor, task_runner
from airflow.sdk.execution_time.comms import (
AssetEventsResult,
AssetResult,
CommsDecoder,
ConnectionResult,
CreateHITLDetailPayload,
DagResult,
DagRunResult,
DagRunStateResult,
DeferTask,
DeleteVariable,
DeleteXCom,
DRCount,
ErrorResponse,
GetAssetByName,
GetAssetByUri,
GetAssetEventByAsset,
GetAssetEventByAssetAlias,
GetConnection,
GetDag,
GetDagRun,
GetDagRunState,
GetDRCount,
GetHITLDetailResponse,
GetPreviousDagRun,
GetPreviousTI,
GetPrevSuccessfulDagRun,
GetTaskBreadcrumbs,
GetTaskRescheduleStartDate,
GetTaskStates,
GetTICount,
GetVariable,
GetXCom,
GetXComCount,
GetXComSequenceItem,
GetXComSequenceSlice,
HITLDetailRequestResult,
InactiveAssetsResult,
MaskSecret,
OKResponse,
PreviousDagRunResult,
PreviousTIResult,
PrevSuccessfulDagRunResult,
PutVariable,
RescheduleTask,
ResendLoggingFD,
RetryTask,
SentFDs,
SetRenderedFields,
SetRenderedMapIndex,
SetXCom,
SkipDownstreamTasks,
SucceedTask,
TaskBreadcrumbsResult,
TaskRescheduleStartDate,
TaskState,
TaskStatesResult,
TICount,
ToSupervisor,
TriggerDagRun,
UpdateHITLDetail,
ValidateInletsAndOutlets,
VariableResult,
XComCountResponse,
XComResult,
XComSequenceIndexResult,
XComSequenceSliceResult,
_RequestFrame,
_ResponseFrame,
)
from airflow.sdk.execution_time.supervisor import (
ActivitySubprocess,
InProcessSupervisorComms,
InProcessTestSupervisor,
_make_process_nondumpable,
_remote_logging_conn,
in_process_api_server,
process_log_messages_from_subprocess,
set_supervisor_comms,
supervise_task,
)
from airflow.sdk.execution_time.task_runner import run
from tests_common.test_utils.config import conf_vars
if TYPE_CHECKING:
import kgb
log = logging.getLogger(__name__)
TI_ID = uuid7()
def lineno():
"""Returns the current line number in our program."""
return inspect.currentframe().f_back.f_lineno
def local_dag_bundle_cfg(path, name="my-bundle"):
return {
"AIRFLOW__DAG_PROCESSOR__DAG_BUNDLE_CONFIG_LIST": json.dumps(
[
{
"name": name,
"classpath": "airflow.dag_processing.bundles.local.LocalDagBundle",
"kwargs": {"path": str(path), "refresh_interval": 1},
}
]
)
}
@pytest.fixture
def client_with_ti_start(make_ti_context):
client = MagicMock(spec=sdk_client.Client)
client.task_instances.start.return_value = make_ti_context()
return client
@pytest.mark.usefixtures("disable_capturing")
class TestSupervisor:
@pytest.mark.parametrize(
("server", "dry_run", "expectation"),
[
("/execution/", False, pytest.raises(ValueError, match="Invalid execution API server URL")),
("", False, pytest.raises(ValueError, match="Invalid execution API server URL")),
("http://localhost:8080", True, pytest.raises(ValueError, match="Can only specify one of")),
(None, True, nullcontext()),
("http://localhost:8080/execution/", False, nullcontext()),
("https://localhost:8080/execution/", False, nullcontext()),
],
)
def test_supervise(
self,
server,
dry_run,
expectation,
test_dags_dir,
client_with_ti_start,
):
"""
Test that the supervisor validates server URL and dry_run parameter combinations correctly.
"""
ti = TaskInstance(
id=uuid7(),
task_id="async",
dag_id="super_basic_deferred_run",
run_id="d",
try_number=1,
dag_version_id=uuid7(),
)
bundle_info = BundleInfo(name="my-bundle", version=None)
kw = {
"ti": ti,
"dag_rel_path": "super_basic_deferred_run.py",
"token": "",
"bundle_info": bundle_info,
"dry_run": dry_run,
"server": server,
}
if isinstance(expectation, nullcontext):
kw["client"] = client_with_ti_start
with patch.dict(os.environ, local_dag_bundle_cfg(test_dags_dir, bundle_info.name)):
with expectation:
supervise_task(**kw)
@pytest.mark.usefixtures("disable_capturing")
class TestWatchedSubprocess:
@pytest.fixture(autouse=True)
def disable_log_upload(self, spy_agency):
spy_agency.spy_on(ActivitySubprocess._upload_logs, call_original=False)
@pytest.fixture(autouse=True)
def use_real_secrets_backends(self, monkeypatch):
"""
Ensure that real secrets backend instances are used instead of mocks.
This prevents Python 3.13 RuntimeWarning when hasattr checks async methods
on mocked backends. The warning occurs because hasattr on AsyncMock creates
unawaited coroutines.
This fixture ensures test isolation when running in parallel with pytest-xdist,
regardless of what other tests patch.
"""
import importlib
import airflow.sdk.execution_time.secrets.execution_api as execution_api_module
from airflow.secrets.environment_variables import EnvironmentVariablesBackend
fresh_execution_backend = importlib.reload(execution_api_module).ExecutionAPISecretsBackend
# Ensure downstream imports see the restored class instead of any AsyncMock left by other tests
import airflow.sdk.execution_time.secrets as secrets_package
monkeypatch.setattr(secrets_package, "ExecutionAPISecretsBackend", fresh_execution_backend)
monkeypatch.setattr(
"airflow.sdk.execution_time.supervisor.ensure_secrets_backend_loaded",
lambda: [EnvironmentVariablesBackend(), fresh_execution_backend()],
)
def test_reading_from_pipes(self, captured_logs, time_machine, client_with_ti_start):
def subprocess_main():
# This is run in the subprocess!
# Ensure we follow the "protocol" and get the startup message before we do anything else
CommsDecoder()._get_response()
import logging
import warnings
print("I'm a short message")
sys.stdout.write("Message ")
print("stderr message", file=sys.stderr)
# We need a short sleep for the main process to process things. I worry this timing will be
# fragile, but I can't think of a better way. This lets the stdout be read (partial line) and the
# stderr full line be read
sleep(0.1)
sys.stdout.write("split across two writes\n")
logging.getLogger("airflow.foobar").error("An error message")
warnings.warn("Warning should be appear from the correct callsite", stacklevel=1)
line = lineno() - 2 # Line the error should be on
instant = timezone.datetime(2024, 11, 7, 12, 34, 56, 78901)
time_machine.move_to(instant, tick=False)
proc = ActivitySubprocess.start(
dag_rel_path=os.devnull,
bundle_info=FAKE_BUNDLE,
what=TaskInstance(
id="4d828a62-a417-4936-a7a6-2b3fabacecab",
task_id="b",
dag_id="c",
run_id="d",
try_number=1,
dag_version_id=uuid7(),
),
client=client_with_ti_start,
target=subprocess_main,
)
rc = proc.wait()
assert rc == 0
assert captured_logs == unordered(
[
{
"logger": "task.stdout",
"event": "I'm a short message",
"level": "info",
"timestamp": "2024-11-07T12:34:56.078901Z",
},
{
"logger": "task.stderr",
"event": "stderr message",
"level": "error",
"timestamp": "2024-11-07T12:34:56.078901Z",
},
{
"logger": "task.stdout",
"event": "Message split across two writes",
"level": "info",
"timestamp": "2024-11-07T12:34:56.078901Z",
},
{
"event": "An error message",
"level": "error",
"logger": "airflow.foobar",
"timestamp": instant,
"loc": mock.ANY,
},
{
"category": "UserWarning",
"event": "Warning should be appear from the correct callsite",
"filename": __file__,
"level": "warning",
"lineno": line,
"logger": "py.warnings",
"timestamp": instant,
},
]
)
@pytest.mark.flaky(reruns=3)
def test_reopen_log_fd(self, captured_logs, client_with_ti_start):
def subprocess_main():
# This is run in the subprocess!
# Ensure we follow the "protocol" and get the startup message before we do anything else
comms = CommsDecoder()
comms._get_response()
logs = comms.send(ResendLoggingFD())
assert isinstance(logs, SentFDs)
logging.root.info("Log on old socket")
with os.fdopen(logs.fds[0], "w") as fd:
json.dump({"level": "info", "event": "Log on new socket"}, fp=fd)
fd.write("\n")
line = lineno() - 5 # Line the error should be on
proc = ActivitySubprocess.start(
dag_rel_path=os.devnull,
bundle_info=FAKE_BUNDLE,
what=TaskInstance(
id="4d828a62-a417-4936-a7a6-2b3fabacecab",
task_id="b",
dag_id="c",
run_id="d",
try_number=1,
dag_version_id=uuid7(),
),
client=client_with_ti_start,
target=subprocess_main,
)
rc = proc.wait()
assert rc == 0
assert captured_logs == unordered(
[
{
"event": "Log on new socket",
"level": "info",
"logger": "task",
"timestamp": mock.ANY,
# Since this is set as json, without filename or linno, we _should_ not add any.
},
{
"event": "Log on old socket",
"level": "info",
"logger": "root",
"timestamp": mock.ANY,
"loc": f"{os.path.basename(__file__)}:{line}",
},
]
)
def test_on_kill_hook_called_when_sigkilled(
self,
client_with_ti_start,
mocked_parse,
make_ti_context,
mock_supervisor_comms,
create_runtime_ti,
make_ti_context_dict,
capfd,
):
main_pid = os.getpid()
ti_id = "4d828a62-a417-4936-a7a6-2b3fabacecab"
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{ti_id}/heartbeat":
return httpx.Response(
status_code=409,
json={
"detail": {
"reason": "not_running",
"message": "TI is no longer in the 'running' state. Task state might be externally set and task should terminate",
"current_state": "failed",
}
},
)
if request.url.path == f"/task-instances/{ti_id}/run":
return httpx.Response(200, json=make_ti_context_dict())
return httpx.Response(status_code=204)
def subprocess_main():
# Ensure we follow the "protocol" and get the startup message before we do anything
CommsDecoder()._get_response()
class CustomOperator(BaseOperator):
def execute(self, context):
for i in range(1000):
print(f"Iteration {i}")
sleep(1)
def on_kill(self) -> None:
print("On kill hook called!")
task = CustomOperator(task_id="print-params")
runtime_ti = create_runtime_ti(
dag_id="c",
task=task,
conf={
"x": 3,
"text": "Hello World!",
"flag": False,
"a_simple_list": ["one", "two", "three", "actually one value is made per line"],
},
)
run(runtime_ti, context=runtime_ti.get_template_context(), log=mock.MagicMock())
assert os.getpid() != main_pid
os.kill(os.getpid(), signal.SIGTERM)
# Ensure that the signal is serviced before we finish and exit the subprocess.
sleep(0.5)
proc = ActivitySubprocess.start(
dag_rel_path=os.devnull,
bundle_info=FAKE_BUNDLE,
what=TaskInstance(
id=ti_id,
task_id="b",
dag_id="c",
run_id="d",
try_number=1,
dag_version_id=uuid7(),
),
client=make_client(transport=httpx.MockTransport(handle_request)),
target=subprocess_main,
)
proc.wait()
captured = capfd.readouterr()
assert "On kill hook called!" in captured.out
def test_subprocess_sigkilled(self, client_with_ti_start):
main_pid = os.getpid()
def subprocess_main():
# Ensure we follow the "protocol" and get the startup message before we do anything
CommsDecoder()._get_response()
assert os.getpid() != main_pid
os.kill(os.getpid(), signal.SIGKILL)
proc = ActivitySubprocess.start(
dag_rel_path=os.devnull,
bundle_info=FAKE_BUNDLE,
what=TaskInstance(
id="4d828a62-a417-4936-a7a6-2b3fabacecab",
task_id="b",
dag_id="c",
run_id="d",
try_number=1,
dag_version_id=uuid7(),
),
client=client_with_ti_start,
target=subprocess_main,
)
rc = proc.wait()
assert rc == -9
@pytest.mark.parametrize(
"start_date",
[
pytest.param(None, id="start_date_is_none"),
pytest.param(timezone.datetime(2025, 3, 28, tzinfo=timezone.utc), id="start_date_from_context"),
],
)
def test_last_chance_exception_handling(self, capfd, start_date, make_ti_context):
def subprocess_main():
# The real main() in task_runner catches exceptions! This is what would happen if we had a syntax
# or import error for instance - a very early exception
raise RuntimeError("Fake syntax error")
mock_client = MagicMock(spec=sdk_client.Client)
mock_client.task_instances.start.return_value = make_ti_context(start_date=start_date)
proc = ActivitySubprocess.start(
dag_rel_path=os.devnull,
bundle_info=FAKE_BUNDLE,
what=TaskInstance(
id=uuid7(), task_id="b", dag_id="c", run_id="d", try_number=1, dag_version_id=uuid7()
),
client=mock_client,
target=subprocess_main,
)
rc = proc.wait()
assert rc == 126
captured = capfd.readouterr()
assert "Last chance exception handler" in captured.err
assert "RuntimeError: Fake syntax error" in captured.err
@pytest.mark.parametrize(
"start_date",
[
pytest.param(timezone.datetime(2025, 3, 28, tzinfo=timezone.utc), id="start_date_from_context"),
pytest.param(None, id="start_date_missing_in_context"),
],
)
def test_resume_start_date_from_context(self, mocker, make_ti_context, start_date, time_machine):
"""Verify that start_date from ti_context (e.g. for deferral resume) is used in the
StartupDetails message instead of computing a new datetime.now(). This test is kept
separate from test_last_chance_exception_handling as their purposes do not overlap.
"""
fallback_now = timezone.datetime(2026, 1, 1, tzinfo=timezone.utc)
time_machine.move_to(fallback_now, tick=False)
mock_client = MagicMock(spec=sdk_client.Client)
ti_context = make_ti_context()
ti_context.start_date = start_date
mock_client.task_instances.start.return_value = ti_context
mock_send = mocker.patch.object(ActivitySubprocess, "send_msg", autospec=True)
proc = ActivitySubprocess.start(
dag_rel_path=os.devnull,
bundle_info=FAKE_BUNDLE,
what=TaskInstance(
id=uuid7(),
task_id="b",
dag_id="c",
run_id="d",
try_number=1,
dag_version_id=uuid7(),
),
client=mock_client,
target=lambda: None,
)
rc = proc.wait()
assert rc == 0
# The startup message is sent via send_msg(StartupDetails(...), request_id=0)
startup_calls = [
c for c in mock_send.call_args_list if len(c.args) > 1 and hasattr(c.args[1], "start_date")
]
assert len(startup_calls) >= 1
msg = startup_calls[0].args[1]
expected_start_date = start_date or fallback_now
assert msg.start_date == expected_start_date
def test_regular_heartbeat(self, spy_agency: kgb.SpyAgency, monkeypatch, mocker, make_ti_context):
"""Test that the WatchedSubprocess class regularly sends heartbeat requests, up to a certain frequency"""
import airflow.sdk.execution_time.supervisor
monkeypatch.setattr(airflow.sdk.execution_time.supervisor, "MIN_HEARTBEAT_INTERVAL", 0.1)
def subprocess_main():
CommsDecoder()._get_response()
for _ in range(5):
print("output", flush=True)
sleep(0.05)
ti_id = uuid7()
_ = mocker.patch.object(sdk_client.TaskInstanceOperations, "start", return_value=make_ti_context())
spy = spy_agency.spy_on(sdk_client.TaskInstanceOperations.heartbeat)
proc = ActivitySubprocess.start(
dag_rel_path=os.devnull,
bundle_info=FAKE_BUNDLE,
what=TaskInstance(
id=ti_id, task_id="b", dag_id="c", run_id="d", try_number=1, dag_version_id=uuid7()
),
client=sdk_client.Client(base_url="", dry_run=True, token=""),
target=subprocess_main,
)
assert proc.wait() == 0
assert spy.called_with(ti_id, pid=proc.pid) # noqa: PGH005
# The exact number we get will depend on timing behaviour, so be a little lenient
assert 1 <= len(spy.calls) <= 4
def test_no_heartbeat_in_overtime(self, spy_agency: kgb.SpyAgency, monkeypatch, mocker, make_ti_context):
"""Test that we don't try and send heartbeats for task that are in "overtime"."""
import airflow.sdk.execution_time.supervisor
monkeypatch.setattr(airflow.sdk.execution_time.supervisor, "MIN_HEARTBEAT_INTERVAL", 0.1)
def subprocess_main():
CommsDecoder()._get_response()
for _ in range(5):
print("output", flush=True)
sleep(0.05)
ti_id = uuid7()
_ = mocker.patch.object(sdk_client.TaskInstanceOperations, "start", return_value=make_ti_context())
@spy_agency.spy_for(ActivitySubprocess._on_child_started)
def _on_child_started(self, *args, **kwargs):
# Set it up so we are in overtime straight away
self._terminal_state = TaskInstanceState.SUCCESS
ActivitySubprocess._on_child_started.call_original(self, *args, **kwargs)
heartbeat_spy = spy_agency.spy_on(sdk_client.TaskInstanceOperations.heartbeat)
proc = ActivitySubprocess.start(
dag_rel_path=os.devnull,
bundle_info=FAKE_BUNDLE,
what=TaskInstance(
id=ti_id, task_id="b", dag_id="c", run_id="d", try_number=1, dag_version_id=uuid7()
),
client=sdk_client.Client(base_url="", dry_run=True, token=""),
target=subprocess_main,
)
assert proc.wait() == 0
spy_agency.assert_spy_not_called(heartbeat_spy)
def test_run_simple_dag(self, test_dags_dir, captured_logs, time_machine, mocker, client_with_ti_start):
"""Test running a simple DAG in a subprocess and capturing the output."""
instant = timezone.datetime(2024, 11, 7, 12, 34, 56, 78901)
time_machine.move_to(instant, tick=False)
dagfile_path = test_dags_dir
ti = TaskInstance(
id=uuid7(),
task_id="hello",
dag_id="super_basic_run",
run_id="c",
try_number=1,
dag_version_id=uuid7(),
)
bundle_info = BundleInfo(name="my-bundle", version=None)
with patch.dict(os.environ, local_dag_bundle_cfg(test_dags_dir, bundle_info.name)):
exit_code = supervise_task(
ti=ti,
dag_rel_path=dagfile_path,
token="",
server="",
dry_run=True,
client=client_with_ti_start,
bundle_info=bundle_info,
)
assert exit_code == 0, captured_logs
# We should have a log from the task!
assert {
"logger": "task.stdout",
"event": "Hello World hello!",
"level": "info",
"timestamp": "2024-11-07T12:34:56.078901Z",
} in captured_logs
def test_supervise_handles_deferred_task(
self, test_dags_dir, captured_logs, time_machine, mocker, make_ti_context
):
"""
Test that the supervisor handles a deferred task correctly.
This includes ensuring the task starts and executes successfully, and that the task is deferred (via
the API client) with the expected parameters.
"""
instant = timezone.datetime(2024, 11, 7, 12, 34, 56, 0)
ti = TaskInstance(
id=uuid7(),
task_id="async",
dag_id="super_basic_deferred_run",
run_id="d",
try_number=1,
dag_version_id=uuid7(),
)
# Create a mock client to assert calls to the client
# We assume the implementation of the client is correct and only need to check the calls
mock_client = mocker.Mock(spec=sdk_client.Client)
mock_client.task_instances.start.return_value = make_ti_context()
time_machine.move_to(instant, tick=False)
current = 1_000_000.0
def mock_monotonic():
return current
bundle_info = BundleInfo(name="my-bundle", version=None)
with (
patch.dict(os.environ, local_dag_bundle_cfg(test_dags_dir, bundle_info.name)),
patch("airflow.sdk.execution_time.supervisor.time.monotonic", side_effect=mock_monotonic),
):
exit_code = supervise_task(
ti=ti,
dag_rel_path="super_basic_deferred_run.py",
token="",
client=mock_client,
bundle_info=bundle_info,
)
assert exit_code == 0, captured_logs
# Validate calls to the client
mock_client.task_instances.start.assert_called_once_with(ti.id, mocker.ANY, mocker.ANY)
mock_client.task_instances.heartbeat.assert_called_once_with(ti.id, pid=mocker.ANY)
mock_client.task_instances.defer.assert_called_once_with(
ti.id,
# Since the message as serialized in the client upon sending, we expect it to be already encoded
DeferTask(
classpath="airflow.providers.standard.triggers.temporal.DateTimeTrigger",
next_method="execute_complete",
trigger_kwargs={
"moment": {
"__classname__": "pendulum.datetime.DateTime",
"__version__": 2,
"__data__": {
"timestamp": 1730982899.0,
"tz": {
"__classname__": "builtins.tuple",
"__version__": 1,
"__data__": ["UTC", "pendulum.tz.timezone.Timezone", 1, True],
},
},
},
"end_from_trigger": False,
},
trigger_timeout=None,
next_kwargs={},
),
)
# We are asserting the log messages here to ensure the task ran successfully
# and mainly to get the final state of the task matches one in the DB.
assert {
"exit_code": 0,
"duration": 0.0,
"final_state": "deferred",
"event": "Workload finished",
"workload_type": "ExecuteTask",
"workload_id": str(ti.id),
"timestamp": mocker.ANY,
"level": "info",
"logger": "supervisor",
"loc": mocker.ANY,
} in captured_logs
@pytest.mark.parametrize("captured_logs", [logging.ERROR], indirect=True, ids=["log_level=error"])
def test_state_conflict_on_heartbeat(self, captured_logs, monkeypatch, mocker, make_ti_context_dict):
"""
Test that ensures that the Supervisor does not cause the task to fail if the Task Instance is no longer
in the running state. Instead, it logs the error and terminates the task process if it
might be running in a different state or has already completed -- or running on a different worker.
Also verifies that the supervisor does not try to send the finish request (update_state) to the API server.
"""
import airflow.sdk.execution_time.supervisor
# Heartbeat every time around the loop
monkeypatch.setattr(airflow.sdk.execution_time.supervisor, "MIN_HEARTBEAT_INTERVAL", 0.0)
def subprocess_main():
CommsDecoder()._get_response()
sleep(5)
# Shouldn't get here
exit(5)
ti_id = uuid7()
# Track the number of requests to simulate mixed responses
request_count = {"count": 0}
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{ti_id}/heartbeat":
request_count["count"] += 1
if request_count["count"] == 1:
# First request succeeds
return httpx.Response(status_code=204)
# Second request returns a conflict status code
return httpx.Response(
409,
json={
"reason": "not_running",
"message": "TI is no longer in the 'running' state. Task state might be externally set and task should terminate",
"current_state": "success",
},
)
if request.url.path == f"/task-instances/{ti_id}/run":
return httpx.Response(200, json=make_ti_context_dict())
if request.url.path == f"/task-instances/{ti_id}/state":
pytest.fail("Should not have sent a state update request")
# Return a 204 for all other requests
return httpx.Response(status_code=204)
proc = ActivitySubprocess.start(
dag_rel_path=os.devnull,
what=TaskInstance(
id=ti_id, task_id="b", dag_id="c", run_id="d", try_number=1, dag_version_id=uuid7()
),
client=make_client(transport=httpx.MockTransport(handle_request)),
target=subprocess_main,
bundle_info=FAKE_BUNDLE,
)
# Wait for the subprocess to finish -- it should have been terminated with SIGTERM
assert proc.wait() == -signal.SIGTERM
assert proc._exit_code == -signal.SIGTERM
assert proc.final_state == "SERVER_TERMINATED"
assert request_count["count"] == 2
# Verify the error was logged
assert captured_logs == [
{
"detail": {
"reason": "not_running",
"message": "TI is no longer in the 'running' state. Task state might be externally set and task should terminate",
"current_state": "success",
},
"event": "Server indicated the task shouldn't be running anymore",
"level": "error",
"status_code": 409,
"logger": "supervisor",
"timestamp": mocker.ANY,
"ti_id": ti_id,
"loc": mocker.ANY,
},
{
"detail": {
"current_state": "success",
"message": "TI is no longer in the 'running' state. Task state might be externally set and task should terminate",
"reason": "not_running",
},
"event": "Server indicated the task shouldn't be running anymore. Terminating process",
"level": "error",
"logger": "task",
"timestamp": mocker.ANY,
"loc": mocker.ANY,
},
{
"event": "Task killed!",
"level": "error",
"logger": "task",
"timestamp": mocker.ANY,
"loc": mocker.ANY,
},
]
def test_start_raises_task_already_running_and_kills_subprocess(self):
"""Test that ActivitySubprocess.start() raises TaskAlreadyRunningError and kills the child
when the API returns 409 with previous_state='running'."""
ti_id = uuid7()
def handle_request(request: httpx.Request) -> httpx.Response:
if request.url.path == f"/task-instances/{ti_id}/run":
return httpx.Response(
409,
json={
"detail": {
"reason": "invalid_state",
"message": "TI was not in a state where it could be marked as running",
"previous_state": "running",
}
},
)
return httpx.Response(status_code=204)
def subprocess_main():
# Ensure we follow the "protocol" and get the startup message before we do anything
CommsDecoder()._get_response()
with pytest.raises(TaskAlreadyRunningError, match="already running"):
ActivitySubprocess.start(
dag_rel_path=os.devnull,
bundle_info=FAKE_BUNDLE,
what=TaskInstance(
id=ti_id, task_id="b", dag_id="c", run_id="d", try_number=1, dag_version_id=uuid7()
),
client=make_client(transport=httpx.MockTransport(handle_request)),
target=subprocess_main,
)
@pytest.mark.parametrize("captured_logs", [logging.WARNING], indirect=True)
def test_heartbeat_failures_handling(self, monkeypatch, mocker, captured_logs, time_machine):
"""
Test that ensures the WatchedSubprocess kills the process after
MAX_FAILED_HEARTBEATS are exceeded.
"""
max_failed_heartbeats = 3
min_heartbeat_interval = 5
monkeypatch.setattr(
"airflow.sdk.execution_time.supervisor.MAX_FAILED_HEARTBEATS", max_failed_heartbeats
)
monkeypatch.setattr(
"airflow.sdk.execution_time.supervisor.MIN_HEARTBEAT_INTERVAL", min_heartbeat_interval
)
mock_process = mocker.Mock()
mock_process.pid = 12345
# Mock the client heartbeat method to raise an exception
mock_client_heartbeat = mocker.Mock(side_effect=Exception("Simulated heartbeat failure"))
client = mocker.Mock()
client.task_instances.heartbeat = mock_client_heartbeat
# Patch the kill method at the class level so we can assert it was called with the correct signal
mock_kill = mocker.patch("airflow.sdk.execution_time.supervisor.WatchedSubprocess.kill")
proc = ActivitySubprocess(
process_log=mocker.MagicMock(),
id=TI_ID,
pid=mock_process.pid,
stdin=mocker.MagicMock(),
client=client,
process=mock_process,
)
current = min_heartbeat_interval
def mock_monotonic():
return current
with patch(
"airflow.sdk.execution_time.supervisor.time.monotonic",
side_effect=mock_monotonic,
):
time_now = timezone.datetime(2024, 11, 28, 12, 0, 0)
time_machine.move_to(time_now, tick=False)
# Simulate sending heartbeats and ensure the process gets killed after max retries
for i in range(1, max_failed_heartbeats):
proc._send_heartbeat_if_needed()
assert proc.failed_heartbeats == i # Increment happens after failure
mock_client_heartbeat.assert_called_with(TI_ID, pid=mock_process.pid)
# Ensure the retry log is present
expected_log = {
"event": "Failed to send heartbeat. Will be retried",
"failed_heartbeats": i,
"ti_id": TI_ID,
"max_retries": max_failed_heartbeats,
"level": "warning",
"logger": "supervisor",
"timestamp": mocker.ANY,
"exc_info": mocker.ANY,
"loc": mocker.ANY,
}
assert expected_log in captured_logs
# Advance time by `min_heartbeat_interval` to allow the next heartbeat
# time_machine.shift(min_heartbeat_interval)
current += min_heartbeat_interval
# On the final failure, the process should be killed
proc._send_heartbeat_if_needed()