-
Notifications
You must be signed in to change notification settings - Fork 373
Expand file tree
/
Copy pathtest_scheduler.py
More file actions
1215 lines (1068 loc) · 40.4 KB
/
test_scheduler.py
File metadata and controls
1215 lines (1068 loc) · 40.4 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
import typing as t
import pytest
from pytest_mock.plugin import MockerFixture
from sqlglot import parse_one, parse
from sqlglot.helper import first
from sqlmesh.core.context import Context, ExecutionContext
from sqlmesh.core.environment import EnvironmentNamingInfo
from sqlmesh.core.macros import RuntimeStage
from sqlmesh.core.model import load_sql_based_model
from sqlmesh.core.model.definition import AuditResult, SqlModel
from sqlmesh.core.model.kind import (
IncrementalByTimeRangeKind,
IncrementalByUniqueKeyKind,
TimeColumn,
SCDType2ByColumnKind,
)
from sqlmesh.core.node import IntervalUnit
from sqlmesh.core.scheduler import (
Scheduler,
interval_diff,
compute_interval_params,
SnapshotToIntervals,
EvaluateNode,
SchedulingUnit,
DummyNode,
)
from sqlmesh.core.signal import signal
from sqlmesh.core.snapshot import (
Snapshot,
SnapshotEvaluator,
SnapshotChangeCategory,
DeployabilityIndex,
snapshots_to_dag,
)
from sqlmesh.utils.date import to_datetime, to_timestamp, DatetimeRanges, TimeLike
from sqlmesh.utils.errors import CircuitBreakerError, NodeAuditsErrors
@pytest.fixture
def scheduler(sushi_context_fixed_date: Context) -> Scheduler:
return sushi_context_fixed_date.scheduler()
@pytest.fixture
def orders(sushi_context_fixed_date: Context) -> Snapshot:
return sushi_context_fixed_date.get_snapshot("sushi.orders", raise_if_missing=True)
@pytest.fixture
def waiter_names(sushi_context_fixed_date: Context) -> Snapshot:
return sushi_context_fixed_date.get_snapshot("sushi.waiter_names", raise_if_missing=True)
@pytest.mark.slow
def test_interval_params(scheduler: Scheduler, sushi_context_fixed_date: Context, orders: Snapshot):
waiter_revenue = sushi_context_fixed_date.get_snapshot(
"sushi.waiter_revenue_by_day", raise_if_missing=True
)
start_ds = "2022-01-01"
end_ds = "2022-02-05"
assert compute_interval_params([orders, waiter_revenue], start=start_ds, end=end_ds) == {
orders: [
(to_timestamp(start_ds), to_timestamp("2022-02-06")),
],
waiter_revenue: [
(to_timestamp(start_ds), to_timestamp("2022-02-06")),
],
}
@pytest.fixture
def get_batched_missing_intervals(
mocker: MockerFixture,
) -> t.Callable[[Scheduler, TimeLike, TimeLike, t.Optional[TimeLike]], SnapshotToIntervals]:
def _get_batched_missing_intervals(
scheduler: Scheduler,
start: TimeLike,
end: TimeLike,
execution_time: t.Optional[TimeLike] = None,
) -> SnapshotToIntervals:
merged_intervals = scheduler.merged_missing_intervals(start, end, execution_time)
return scheduler.batch_intervals(merged_intervals, mocker.Mock(), mocker.Mock())
return _get_batched_missing_intervals
def test_interval_params_nonconsecutive(scheduler: Scheduler, orders: Snapshot):
start_ds = "2022-01-01"
end_ds = "2022-02-05"
orders.add_interval("2022-01-10", "2022-01-15")
assert compute_interval_params([orders], start=start_ds, end=end_ds) == {
orders: [
(to_timestamp(start_ds), to_timestamp("2022-01-10")),
(to_timestamp("2022-01-16"), to_timestamp("2022-02-06")),
]
}
@pytest.mark.slow
def test_interval_params_missing(scheduler: Scheduler, sushi_context_fixed_date: Context):
waiters = sushi_context_fixed_date.get_snapshot(
"sushi.waiter_as_customer_by_day", raise_if_missing=True
)
start_ds = "2022-01-01"
end_ds = "2022-03-01"
assert compute_interval_params(
sushi_context_fixed_date.snapshots.values(), start=start_ds, end=end_ds
)[waiters] == [
(to_timestamp(start_ds), to_timestamp("2022-03-02")),
]
@pytest.mark.slow
def test_run(sushi_context_fixed_date: Context, scheduler: Scheduler):
adapter = sushi_context_fixed_date.engine_adapter
snapshot = sushi_context_fixed_date.get_snapshot("sushi.items", raise_if_missing=True)
scheduler.run(
EnvironmentNamingInfo(),
"2022-01-01",
"2022-01-03",
"2022-01-30",
)
assert adapter.fetchone(
f"""
SELECT id, name, price FROM sqlmesh__sushi.sushi__items__{snapshot.version} ORDER BY event_date LIMIT 1
"""
) == (0, "Hotate", 5.99)
def test_incremental_by_unique_key_kind_dag(
mocker: MockerFixture, make_snapshot, get_batched_missing_intervals
):
"""
Test that when given a week of data that it batches dates together.
"""
start = to_datetime("2023-01-01")
end = to_datetime("2023-01-07")
unique_by_key_snapshot: Snapshot = make_snapshot(
SqlModel(
name="name",
kind=IncrementalByUniqueKeyKind(unique_key=["id"]),
owner="owner",
dialect="",
cron="@daily",
start=start,
query=parse_one("SELECT id FROM VALUES (1), (2) AS t(id)"),
),
)
snapshot_evaluator = SnapshotEvaluator(adapters=mocker.MagicMock(), ddl_concurrent_tasks=1)
mock_state_sync = mocker.MagicMock()
scheduler = Scheduler(
snapshots=[unique_by_key_snapshot],
snapshot_evaluator=snapshot_evaluator,
state_sync=mock_state_sync,
max_workers=2,
default_catalog=None,
)
batches = get_batched_missing_intervals(scheduler, start, end, end)
dag = scheduler._dag(batches)
assert dag.graph == {
EvaluateNode(
unique_by_key_snapshot.name,
interval=(to_timestamp("2023-01-01"), to_timestamp("2023-01-07")),
batch_index=0,
): set(),
}
def test_incremental_time_self_reference_dag(
mocker: MockerFixture, make_snapshot, get_batched_missing_intervals
):
"""
Test that we always process a day at a time and all future days rely on the previous day
"""
start = to_datetime("2023-01-01")
end = to_datetime("2023-01-07")
incremental_self_snapshot: Snapshot = make_snapshot(
SqlModel(
name="name",
kind=IncrementalByTimeRangeKind(time_column=TimeColumn(column="ds"), batch_size=1),
owner="owner",
dialect="",
cron="@daily",
start=start,
query=parse_one("SELECT id, @end_ds as ds FROM name"),
),
)
incremental_self_snapshot.add_interval("2023-01-02", "2023-01-02")
incremental_self_snapshot.add_interval("2023-01-05", "2023-01-05")
snapshot_evaluator = SnapshotEvaluator(adapters=mocker.MagicMock(), ddl_concurrent_tasks=1)
scheduler = Scheduler(
snapshots=[incremental_self_snapshot],
snapshot_evaluator=snapshot_evaluator,
state_sync=mocker.MagicMock(),
max_workers=2,
default_catalog=None,
)
batches = get_batched_missing_intervals(scheduler, start, end, end)
dag = scheduler._dag(batches)
assert dag.graph == {
# Only run one day at a time and each day relies on the previous days
EvaluateNode(
incremental_self_snapshot.name,
interval=(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
batch_index=0,
): set(),
EvaluateNode(
incremental_self_snapshot.name,
interval=(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
batch_index=1,
): {
EvaluateNode(
snapshot_name=incremental_self_snapshot.name,
interval=(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
batch_index=0,
),
},
EvaluateNode(
incremental_self_snapshot.name,
interval=(to_timestamp("2023-01-04"), to_timestamp("2023-01-05")),
batch_index=2,
): {
EvaluateNode(
snapshot_name=incremental_self_snapshot.name,
interval=(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
batch_index=1,
),
},
EvaluateNode(
snapshot_name=incremental_self_snapshot.name,
interval=(to_timestamp("2023-01-06"), to_timestamp("2023-01-07")),
batch_index=3,
): {
EvaluateNode(
snapshot_name=incremental_self_snapshot.name,
interval=(to_timestamp("2023-01-04"), to_timestamp("2023-01-05")),
batch_index=2,
),
},
DummyNode(snapshot_name=incremental_self_snapshot.name): {
EvaluateNode(
snapshot_name=incremental_self_snapshot.name,
interval=(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
batch_index=0,
),
EvaluateNode(
snapshot_name=incremental_self_snapshot.name,
interval=(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
batch_index=1,
),
EvaluateNode(
snapshot_name=incremental_self_snapshot.name,
interval=(to_timestamp("2023-01-04"), to_timestamp("2023-01-05")),
batch_index=2,
),
EvaluateNode(
snapshot_name=incremental_self_snapshot.name,
interval=(to_timestamp("2023-01-06"), to_timestamp("2023-01-07")),
batch_index=3,
),
},
}
@pytest.mark.parametrize(
"batch_size, batch_concurrency, expected_graph",
[
(
2,
2,
{
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-01"), to_timestamp("2023-01-03")),
batch_index=0,
): set(),
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-03"), to_timestamp("2023-01-05")),
batch_index=1,
): set(),
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-05"), to_timestamp("2023-01-07")),
batch_index=2,
): {
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-01"), to_timestamp("2023-01-03")),
batch_index=0,
),
},
},
),
(
1,
3,
{
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
batch_index=0,
): set(),
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-02"), to_timestamp("2023-01-03")),
batch_index=1,
): set(),
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
batch_index=2,
): set(),
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-04"), to_timestamp("2023-01-05")),
batch_index=3,
): {
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
batch_index=0,
),
},
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-05"), to_timestamp("2023-01-06")),
batch_index=4,
): {
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-02"), to_timestamp("2023-01-03")),
batch_index=1,
),
},
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-06"), to_timestamp("2023-01-07")),
batch_index=5,
): {
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
batch_index=2,
),
},
},
),
(
1,
10,
{
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
batch_index=0,
): set(),
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-02"), to_timestamp("2023-01-03")),
batch_index=1,
): set(),
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
batch_index=2,
): set(),
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-04"), to_timestamp("2023-01-05")),
batch_index=3,
): set(),
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-05"), to_timestamp("2023-01-06")),
batch_index=4,
): set(),
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-06"), to_timestamp("2023-01-07")),
batch_index=5,
): set(),
},
),
(
10,
10,
{
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-01"), to_timestamp("2023-01-07")),
batch_index=0,
): set(),
},
),
(
10,
1,
{
EvaluateNode(
snapshot_name='"test_model"',
interval=(to_timestamp("2023-01-01"), to_timestamp("2023-01-07")),
batch_index=0,
): set(),
},
),
],
)
def test_incremental_batch_concurrency(
mocker: MockerFixture,
make_snapshot,
get_batched_missing_intervals,
batch_size: int,
batch_concurrency: int,
expected_graph: t.Dict[SchedulingUnit, t.Set[SchedulingUnit]],
):
start = to_datetime("2023-01-01")
end = to_datetime("2023-01-07")
snapshot: Snapshot = make_snapshot(
SqlModel(
name="test_model",
kind=IncrementalByTimeRangeKind(
time_column="ds", batch_size=batch_size, batch_concurrency=batch_concurrency
),
cron="@daily",
start=start,
query=parse_one("SELECT 1, ds FROM source"),
),
)
snapshot_evaluator = SnapshotEvaluator(adapters=mocker.MagicMock(), ddl_concurrent_tasks=1)
mock_state_sync = mocker.MagicMock()
scheduler = Scheduler(
snapshots=[snapshot],
snapshot_evaluator=snapshot_evaluator,
state_sync=mock_state_sync,
max_workers=4,
default_catalog=None,
)
batches = get_batched_missing_intervals(scheduler, start, end, end)
dag = scheduler._dag(batches)
graph = {k: v for k, v in dag.graph.items() if isinstance(k, EvaluateNode)}
assert graph == expected_graph
def test_circuit_breaker(scheduler: Scheduler):
with pytest.raises(CircuitBreakerError):
scheduler.run(
EnvironmentNamingInfo(),
"2022-01-01",
"2022-01-03",
"2022-01-30",
circuit_breaker=lambda: True,
)
def test_intervals_with_end_date_on_model(
mocker: MockerFixture, make_snapshot, get_batched_missing_intervals
):
snapshot: Snapshot = make_snapshot(
SqlModel(
name="name",
kind=IncrementalByTimeRangeKind(time_column="ds", batch_size=1),
interval_unit=IntervalUnit.DAY,
start="2023-01-01",
end="2023-01-31",
query=parse_one("SELECT ds FROM parent.tbl"),
)
)
snapshot_evaluator = SnapshotEvaluator(adapters=mocker.MagicMock(), ddl_concurrent_tasks=1)
scheduler = Scheduler(
snapshots=[snapshot],
snapshot_evaluator=snapshot_evaluator,
state_sync=mocker.MagicMock(),
max_workers=2,
default_catalog=None,
)
# generate for 1 year to show that the returned batches should only cover
# the range defined on the model itself
batches = get_batched_missing_intervals(scheduler, start="2023-01-01", end="2024-01-01")[
snapshot
]
assert len(batches) == 31 # days in Jan 2023
assert batches[0] == (to_timestamp("2023-01-01"), to_timestamp("2023-01-02"))
assert batches[-1] == (to_timestamp("2023-01-31"), to_timestamp("2023-02-01"))
# generate for less than 1 month to ensure that the scheduler end date
# takes precedence over the model end date
batches = get_batched_missing_intervals(scheduler, start="2023-01-01", end="2023-01-10")[
snapshot
]
assert len(batches) == 10
assert batches[0] == (to_timestamp("2023-01-01"), to_timestamp("2023-01-02"))
assert batches[-1] == (to_timestamp("2023-01-10"), to_timestamp("2023-01-11"))
# generate for the last day of range
batches = get_batched_missing_intervals(scheduler, start="2023-01-31", end="2023-01-31")[
snapshot
]
assert len(batches) == 1
assert batches[0] == (to_timestamp("2023-01-31"), to_timestamp("2023-02-01"))
# generate for future days to ensure no future batches are loaded
snapshot_to_batches = get_batched_missing_intervals(
scheduler, start="2023-02-01", end="2023-02-28"
)
assert len(snapshot_to_batches) == 0
def test_external_model_audit(mocker, make_snapshot):
model = load_sql_based_model(
parse( # type: ignore
"""
MODEL (
name test_schema.test_model,
kind EXTERNAL,
columns (id int),
audits not_null(columns := id)
);
SELECT 1;
"""
),
)
snapshot = make_snapshot(model)
snapshot.categorize_as(SnapshotChangeCategory.BREAKING)
evaluator = SnapshotEvaluator(adapters=mocker.MagicMock())
spy = mocker.spy(evaluator, "_audit")
scheduler = Scheduler(
snapshots=[snapshot],
snapshot_evaluator=evaluator,
state_sync=mocker.MagicMock(),
max_workers=2,
default_catalog=None,
)
scheduler.run(
EnvironmentNamingInfo(),
"2022-01-01",
"2022-01-01",
"2022-01-30",
)
spy.assert_called_once()
def test_audit_failure_notifications(
scheduler: Scheduler, waiter_names: Snapshot, mocker: MockerFixture
):
evaluator_evaluate_mock = mocker.Mock()
mocker.patch("sqlmesh.core.scheduler.SnapshotEvaluator.evaluate", evaluator_evaluate_mock)
evaluator_audit_mock = mocker.Mock()
mocker.patch("sqlmesh.core.scheduler.SnapshotEvaluator.audit", evaluator_audit_mock)
notify_user_mock = mocker.Mock()
mocker.patch(
"sqlmesh.core.notification_target.NotificationTargetManager.notify_user", notify_user_mock
)
notify_mock = mocker.Mock()
mocker.patch("sqlmesh.core.notification_target.NotificationTargetManager.notify", notify_mock)
audit = first(waiter_names.model.audit_definitions.values())
query = waiter_names.model.render_query()
def _evaluate():
scheduler.evaluate(
waiter_names,
to_datetime("2022-01-01"),
to_datetime("2022-01-02"),
to_datetime("2022-01-03"),
DeployabilityIndex.all_deployable(),
0,
)
evaluator_audit_mock.return_value = [
AuditResult(
audit=audit,
audit_args={},
model=waiter_names.model,
query=query,
count=0,
skipped=False,
)
]
_evaluate()
assert notify_user_mock.call_count == 0
assert notify_mock.call_count == 0
evaluator_audit_mock.return_value = [
AuditResult(
audit=audit,
audit_args={},
model=waiter_names.model,
query=query,
count=None,
skipped=True,
)
]
_evaluate()
assert notify_user_mock.call_count == 0
assert notify_mock.call_count == 0
evaluator_audit_mock.return_value = [
AuditResult(
audit=audit,
audit_args={},
model=waiter_names.model,
query=query,
count=1,
skipped=False,
blocking=False,
)
]
_evaluate()
assert notify_user_mock.call_count == 1
assert notify_mock.call_count == 1
notify_user_mock.reset_mock()
notify_mock.reset_mock()
evaluator_audit_mock.return_value = [
AuditResult(
audit=audit,
audit_args={},
model=waiter_names.model,
query=query,
count=1,
skipped=False,
)
]
with pytest.raises(NodeAuditsErrors):
_evaluate()
assert notify_user_mock.call_count == 1
assert notify_mock.call_count == 1
def test_interval_diff():
assert interval_diff([(1, 2)], []) == [(1, 2)]
assert interval_diff([(1, 2)], [(1, 2)]) == []
assert interval_diff([(1, 2)], [(0, 2)]) == []
assert interval_diff([(1, 2)], [(2, 3)]) == [(1, 2)]
assert interval_diff([(1, 2)], [(0, 1)]) == [(1, 2)]
assert interval_diff([(1, 2), (2, 3), (3, 4)], [(1, 4)]) == []
assert interval_diff([(1, 2), (2, 3), (3, 4)], [(1, 2)]) == [(2, 3), (3, 4)]
assert interval_diff([(4, 5)], [(1, 2), (2, 3)]) == [(4, 5)]
assert interval_diff(
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)],
[(2, 3), (4, 6)],
) == [(1, 2), (3, 4)]
assert interval_diff(
[(1, 2), (2, 3), (3, 4)],
[(1, 3)],
) == [(3, 4)]
assert interval_diff(
[(1, 3), (3, 4)],
[(1, 2), (2, 3)],
) == [(3, 4)]
assert interval_diff([(1, 2), (2, 3)], [(1, 2)], uninterrupted=True) == []
assert interval_diff([(1, 2), (2, 3)], [(3, 4)], uninterrupted=True) == [(1, 2), (2, 3)]
assert interval_diff([(1, 2), (2, 3)], [(2, 3)], uninterrupted=True) == [(1, 2)]
def test_signal_intervals(mocker: MockerFixture, make_snapshot, get_batched_missing_intervals):
@signal()
def signal_a(batch: DatetimeRanges, context: ExecutionContext):
if not hasattr(context, "engine_adapter"):
raise
return [batch[0], batch[1]]
@signal()
def signal_b(batch: DatetimeRanges):
return batch[-49:]
signals = signal.get_registry()
a = make_snapshot(
load_sql_based_model(
parse( # type: ignore
"""
MODEL (
name a,
kind FULL,
start '2023-01-01',
signals SIGNAL_A(),
);
SELECT 1 x;
"""
),
signal_definitions=signals,
),
)
b = make_snapshot(
load_sql_based_model(
parse( # type: ignore
"""
MODEL (
name b,
kind FULL,
cron '@hourly',
start '2023-01-01',
signals SIGNAL_B(),
);
SELECT 2 x;
"""
),
signal_definitions=signals,
),
nodes={a.name: a.model},
)
c = make_snapshot(
load_sql_based_model(
parse( # type: ignore
"""
MODEL (
name c,
kind FULL,
start '2023-01-01',
);
SELECT * FROM a UNION SELECT * FROM b
"""
),
signal_definitions=signals,
),
nodes={a.name: a.model, b.name: b.model},
)
d = make_snapshot(
load_sql_based_model(
parse( # type: ignore
"""
MODEL (
name d,
kind FULL,
start '2023-01-01',
);
SELECT * FROM c UNION SELECT * FROM d
"""
),
signal_definitions=signals,
),
nodes={a.name: a.model, b.name: b.model, c.name: c.model},
)
snapshot_evaluator = SnapshotEvaluator(adapters=mocker.MagicMock(), ddl_concurrent_tasks=1)
scheduler = Scheduler(
snapshots=[a, b, c, d],
snapshot_evaluator=snapshot_evaluator,
state_sync=mocker.MagicMock(),
max_workers=2,
default_catalog=None,
)
batches = get_batched_missing_intervals(scheduler, "2023-01-01", "2023-01-03", None)
assert batches == {
a: [(to_timestamp("2023-01-01"), to_timestamp("2023-01-03"))],
b: [(to_timestamp("2023-01-01 23:00:00"), to_timestamp("2023-01-04"))],
# Full models and models that depend on past can't run for a discontinuous range
c: [],
d: [],
}
def test_signals_snapshots_out_of_order(
mocker: MockerFixture, make_snapshot, get_batched_missing_intervals
):
@signal()
def signal_base(batch: DatetimeRanges):
return [batch[0]]
signals = signal.get_registry()
snapshot_a = make_snapshot(
load_sql_based_model(
parse( # type: ignore
"""
MODEL (
name a,
kind INCREMENTAL_BY_TIME_RANGE(
lookback 1,
time_column dt,
),
start '2023-01-01',
signals SIGNAL_BASE(),
);
SELECT @start_date AS dt;
"""
),
signal_definitions=signals,
),
)
snapshot_b = make_snapshot(
load_sql_based_model(
parse( # type: ignore
"""
MODEL (
name b,
kind INCREMENTAL_BY_TIME_RANGE(
lookback 1,
time_column dt,
),
start '2023-01-01'
);
SELECT @start_date AS dt;
"""
),
signal_definitions=signals,
)
)
snapshot_c = make_snapshot(
load_sql_based_model(
parse( # type: ignore
"""
MODEL (
name c,
kind INCREMENTAL_BY_TIME_RANGE(
lookback 1,
time_column dt,
),
start '2023-01-01',
);
SELECT * FROM a UNION SELECT * FROM b
"""
),
signal_definitions=signals,
),
nodes={snapshot_a.name: snapshot_a.model, snapshot_b.name: snapshot_b.model},
)
snapshot_evaluator = SnapshotEvaluator(adapters=mocker.MagicMock(), ddl_concurrent_tasks=1)
scheduler = Scheduler(
snapshots=[snapshot_c, snapshot_b, snapshot_a], # reverse order
snapshot_evaluator=snapshot_evaluator,
state_sync=mocker.MagicMock(),
max_workers=2,
default_catalog=None,
)
batches = get_batched_missing_intervals(scheduler, "2023-01-01", "2023-01-03", None)
assert batches == {
snapshot_a: [(to_timestamp("2023-01-01"), to_timestamp("2023-01-02"))],
snapshot_b: [(to_timestamp("2023-01-01"), to_timestamp("2023-01-04"))],
snapshot_c: [(to_timestamp("2023-01-01"), to_timestamp("2023-01-02"))],
}
@pytest.mark.parametrize(
"batch_size, expected_batches",
[
(
1,
[
(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
(to_timestamp("2023-01-02"), to_timestamp("2023-01-03")),
(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
],
),
(
None,
[
(to_timestamp("2023-01-01"), to_timestamp("2023-01-04")),
],
),
],
)
def test_scd_type_2_batch_size(
mocker: MockerFixture,
make_snapshot,
get_batched_missing_intervals,
batch_size: t.Optional[int],
expected_batches: t.List[t.Tuple[int, int]],
):
"""
Test that SCD_TYPE_2_BY_COLUMN models are batched correctly based on batch_size.
With batch_size=1, we expect 3 separate batches for 3 days.
Without a specified batch_size, we expect a single batch for the entire period.
"""
start = to_datetime("2023-01-01")
end = to_datetime("2023-01-04")
# Configure kind params
kind_params = {}
if batch_size is not None:
kind_params["batch_size"] = batch_size
# Create the model and snapshot
model = SqlModel(
name="test_scd_model",
kind=SCDType2ByColumnKind(columns="valid_to", unique_key=["id"], **kind_params),
cron="@daily",
start=start,
query=parse_one("SELECT id, valid_from, valid_to FROM source"),
)
snapshot = make_snapshot(model)
# Setup scheduler
snapshot_evaluator = SnapshotEvaluator(adapters=mocker.MagicMock(), ddl_concurrent_tasks=1)
scheduler = Scheduler(
snapshots=[snapshot],
snapshot_evaluator=snapshot_evaluator,
state_sync=mocker.MagicMock(),
max_workers=2,
default_catalog=None,
)
# Get batches for the time period
batches = get_batched_missing_intervals(scheduler, start, end, end)[snapshot]
# Verify batches match expectations
assert batches == expected_batches
def test_before_all_environment_statements_called_first(mocker: MockerFixture, make_snapshot):
model = SqlModel(
name="test.model_items",
query=parse_one("SELECT id, ds FROM raw.items"),
kind=IncrementalByTimeRangeKind(time_column=TimeColumn(column="ds")),
)
snapshot = make_snapshot(model)
# to track the order of calls
call_order = []
mock_state_sync = mocker.MagicMock()
mock_state_sync.get_environment_statements.return_value = [
("CREATE TABLE IF NOT EXISTS test_table (id INT)", RuntimeStage.BEFORE_ALL)
]
def record_get_environment_statements(*args, **kwargs):
call_order.append("get_environment_statements")
return mock_state_sync.get_environment_statements.return_value
mock_state_sync.get_environment_statements.side_effect = record_get_environment_statements
mock_snapshot_evaluator = mocker.MagicMock()
mock_adapter = mocker.MagicMock()
mock_snapshot_evaluator.adapter = mock_adapter
def record_get_snapshots_to_create(*args, **kwargs):
call_order.append("get_snapshots_to_create")
return []
mock_snapshot_evaluator.get_snapshots_to_create.side_effect = record_get_snapshots_to_create
mock_execute_env_statements = mocker.patch(
"sqlmesh.core.scheduler.execute_environment_statements"
)
def record_execute_environment_statements(*args, **kwargs):
call_order.append("execute_environment_statements")
mock_execute_env_statements.side_effect = record_execute_environment_statements
scheduler = Scheduler(
snapshots=[snapshot],
snapshot_evaluator=mock_snapshot_evaluator,
state_sync=mock_state_sync,
default_catalog=None,
)
merged_intervals = {
snapshot: [
(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
],
}
deployability_index = DeployabilityIndex.create([snapshot])
environment_naming_info = EnvironmentNamingInfo(name="test_env")
scheduler.run_merged_intervals(
merged_intervals=merged_intervals,
deployability_index=deployability_index,
environment_naming_info=environment_naming_info,
run_environment_statements=True,
)