-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathtest_async_scheduler.py
More file actions
1598 lines (1296 loc) · 59.7 KB
/
test_async_scheduler.py
File metadata and controls
1598 lines (1296 loc) · 59.7 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
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import asyncio
from typing import Any
from unittest.mock import MagicMock
import pytest
import data_designer.lazy_heavy_imports as lazy
from data_designer.config.column_configs import (
CustomColumnConfig,
ExpressionColumnConfig,
GenerationStrategy,
LLMTextColumnConfig,
SamplerColumnConfig,
)
from data_designer.config.custom_column import custom_column_generator
from data_designer.config.sampler_params import SamplerType
from data_designer.engine.column_generators.generators.base import (
ColumnGenerator,
ColumnGeneratorFullColumn,
FromScratchColumnGenerator,
)
from data_designer.engine.column_generators.generators.custom import CustomColumnGenerator
from data_designer.engine.dataset_builders.async_scheduler import AsyncTaskScheduler, build_llm_bound_lookup
from data_designer.engine.dataset_builders.utils.completion_tracker import CompletionTracker
from data_designer.engine.dataset_builders.utils.execution_graph import ExecutionGraph
from data_designer.engine.dataset_builders.utils.row_group_buffer import RowGroupBufferManager
from data_designer.engine.models.errors import ModelInternalServerError, ModelRateLimitError
from data_designer.engine.resources.resource_provider import ResourceProvider
MODEL_ALIAS = "stub"
# -- Mock generators -----------------------------------------------------------
def _mock_provider() -> MagicMock:
return MagicMock(spec=ResourceProvider)
def _expr_config(name: str = "test") -> ExpressionColumnConfig:
return ExpressionColumnConfig(name=name, expr="{{ x }}", dtype="str")
class MockSeedGenerator(FromScratchColumnGenerator[ExpressionColumnConfig]):
"""Mock from-scratch generator that produces a DataFrame."""
@staticmethod
def get_generation_strategy() -> GenerationStrategy:
return GenerationStrategy.FULL_COLUMN
def generate(self, data: lazy.pd.DataFrame) -> lazy.pd.DataFrame:
return data
def generate_from_scratch(self, num_records: int) -> lazy.pd.DataFrame:
return lazy.pd.DataFrame({self.config.name: list(range(num_records))})
class MockCellGenerator(ColumnGenerator[ExpressionColumnConfig]):
"""Mock cell-by-cell generator."""
@staticmethod
def get_generation_strategy() -> GenerationStrategy:
return GenerationStrategy.CELL_BY_CELL
def generate(self, data: dict) -> dict:
data[self.config.name] = f"processed_{data.get('seed', '?')}"
return data
class MockFullColumnGenerator(ColumnGeneratorFullColumn[ExpressionColumnConfig]):
"""Mock full-column generator."""
def generate(self, data: lazy.pd.DataFrame) -> lazy.pd.DataFrame:
data[self.config.name] = "batch_val"
return data
class MockStatefulSeed(FromScratchColumnGenerator[ExpressionColumnConfig]):
"""Stateful mock seed generator."""
@property
def is_order_dependent(self) -> bool:
return True
@staticmethod
def get_generation_strategy() -> GenerationStrategy:
return GenerationStrategy.FULL_COLUMN
def generate(self, data: lazy.pd.DataFrame) -> lazy.pd.DataFrame:
return data
def generate_from_scratch(self, num_records: int) -> lazy.pd.DataFrame:
return lazy.pd.DataFrame({self.config.name: list(range(num_records))})
class MockFailingSeedGenerator(FromScratchColumnGenerator[ExpressionColumnConfig]):
"""Seed generator that always fails with a non-retryable error."""
@staticmethod
def get_generation_strategy() -> GenerationStrategy:
return GenerationStrategy.FULL_COLUMN
def generate(self, data: lazy.pd.DataFrame) -> lazy.pd.DataFrame:
return data
def generate_from_scratch(self, num_records: int) -> lazy.pd.DataFrame:
raise ValueError("permanent seed failure")
async def agenerate_from_scratch(self, num_records: int) -> lazy.pd.DataFrame:
raise ValueError("permanent seed failure")
class MockFailingGenerator(ColumnGenerator[ExpressionColumnConfig]):
"""Generator that fails with a configurable error.
By default fails permanently. Set ``transient_failures`` to make the first
N calls fail with a retryable 503 error before succeeding.
"""
def __init__(self, *args: Any, transient_failures: int = 0, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._transient_failures = transient_failures
self._calls = 0
@staticmethod
def get_generation_strategy() -> GenerationStrategy:
return GenerationStrategy.CELL_BY_CELL
def generate(self, data: dict) -> dict:
self._calls += 1
if self._transient_failures > 0 and self._calls <= self._transient_failures:
raise ModelInternalServerError("503 Service Unavailable")
if self._transient_failures == 0:
raise ValueError("permanent failure")
data[self.config.name] = f"recovered_{data.get('seed', '?')}"
return data
class MockRateLimitGenerator(ColumnGenerator[ExpressionColumnConfig]):
"""Generator that fails with rate-limit errors before succeeding.
The first ``rate_limit_failures`` calls raise ``ModelRateLimitError``,
then all subsequent calls succeed.
"""
def __init__(self, *args: Any, rate_limit_failures: int = 0, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._rate_limit_failures = rate_limit_failures
self._calls = 0
@staticmethod
def get_generation_strategy() -> GenerationStrategy:
return GenerationStrategy.CELL_BY_CELL
def generate(self, data: dict) -> dict:
self._calls += 1
if self._calls <= self._rate_limit_failures:
raise ModelRateLimitError("429 Too Many Requests")
data[self.config.name] = f"ok_{data.get('seed', '?')}"
return data
# -- Helper to build graph + scheduler ----------------------------------------
def _build_simple_pipeline(
num_records: int = 3,
buffer_size: int = 3,
trace: bool = False,
generators: dict[str, ColumnGenerator] | None = None,
configs: list[SamplerColumnConfig | LLMTextColumnConfig | ExpressionColumnConfig] | None = None,
strategies: dict[str, GenerationStrategy] | None = None,
) -> tuple[AsyncTaskScheduler, CompletionTracker]:
"""Build a simple seed → cell pipeline for testing."""
if configs is None:
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="cell_out", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
]
if strategies is None:
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"cell_out": GenerationStrategy.CELL_BY_CELL,
}
if generators is None:
provider = _mock_provider()
generators = {
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"cell_out": MockCellGenerator(config=_expr_config("cell_out"), resource_provider=provider),
}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, num_records)] if num_records <= buffer_size else []
if not row_groups:
remaining = num_records
rg_id = 0
while remaining > 0:
size = min(buffer_size, remaining)
row_groups.append((rg_id, size))
remaining -= size
rg_id += 1
tracker = CompletionTracker.with_graph(graph, row_groups)
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
trace=trace,
)
return scheduler, tracker
# -- Tests --------------------------------------------------------------------
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_dispatches_seeds_first() -> None:
"""Seeds (no upstream) are dispatched before downstream columns."""
scheduler, tracker = _build_simple_pipeline(num_records=2, trace=True)
await scheduler.run()
# All tasks should be complete
assert tracker.is_row_group_complete(0, 2, ["seed", "cell_out"])
# Verify dispatch order: seeds before cells
seed_traces = [t for t in scheduler.traces if t.column == "seed"]
cell_traces = [t for t in scheduler.traces if t.column == "cell_out"]
assert len(seed_traces) == 1 # one batch task
assert len(cell_traces) == 2 # two cell tasks
assert seed_traces[0].dispatched_at < cell_traces[0].dispatched_at
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_with_buffer_manager() -> None:
"""Scheduler writes results to buffer manager and checkpoints."""
storage = MagicMock()
storage.dataset_name = "test"
storage.get_file_paths.return_value = {}
storage.write_batch_to_parquet_file.return_value = "/fake.parquet"
storage.move_partial_result_to_final_file_path.return_value = "/fake_final.parquet"
buffer_mgr = RowGroupBufferManager(storage)
provider = _mock_provider()
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="cell_out", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"cell_out": GenerationStrategy.CELL_BY_CELL,
}
generators = {
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"cell_out": MockCellGenerator(config=_expr_config("cell_out"), resource_provider=provider),
}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 2)]
tracker = CompletionTracker.with_graph(graph, row_groups)
checkpointed: list[int] = []
def finalize(rg_id: int) -> None:
buffer_mgr.checkpoint_row_group(rg_id)
checkpointed.append(rg_id)
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
buffer_manager=buffer_mgr,
on_finalize_row_group=finalize,
)
await scheduler.run()
assert 0 in checkpointed
assert buffer_mgr.actual_num_records == 2
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_multiple_row_groups() -> None:
"""Scheduler handles multiple row groups."""
scheduler, tracker = _build_simple_pipeline(num_records=5, buffer_size=2, trace=True)
await scheduler.run()
# 3 row groups: (0, 2), (1, 2), (2, 1)
assert tracker.is_row_group_complete(0, 2, ["seed", "cell_out"])
assert tracker.is_row_group_complete(1, 2, ["seed", "cell_out"])
assert tracker.is_row_group_complete(2, 1, ["seed", "cell_out"])
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_non_retryable_failure_drops_row() -> None:
"""Non-retryable failure drops the row."""
provider = _mock_provider()
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="fail_col", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"fail_col": GenerationStrategy.CELL_BY_CELL,
}
generators = {
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"fail_col": MockFailingGenerator(config=_expr_config("fail_col"), resource_provider=provider),
}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 2)]
tracker = CompletionTracker.with_graph(graph, row_groups)
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
)
await scheduler.run()
# All rows should be dropped since all fail non-retryably
assert tracker.is_dropped(0, 0)
assert tracker.is_dropped(0, 1)
# Row group is "complete" because all non-dropped rows have all columns
# (there are no non-dropped rows)
assert tracker.is_row_group_complete(0, 2, ["seed", "fail_col"])
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_stateful_generator_serializes() -> None:
"""Stateful generators serialize across row groups."""
provider = _mock_provider()
gen = MockStatefulSeed(config=_expr_config("seed"), resource_provider=provider)
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
]
strategies = {"seed": GenerationStrategy.FULL_COLUMN}
generators = {"seed": gen}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 2), (1, 2)]
tracker = CompletionTracker.with_graph(graph, row_groups)
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
trace=True,
)
await scheduler.run()
# Both row groups should complete
assert tracker.is_row_group_complete(0, 2, ["seed"])
assert tracker.is_row_group_complete(1, 2, ["seed"])
# Stateful: verify both row groups completed (the lock ensures serial
# execution, but sub-microsecond mock generators make timestamp-based
# ordering assertions flaky)
assert len(scheduler.traces) == 2
rg_ids = [t.row_group for t in scheduler.traces]
assert set(rg_ids) == {0, 1}
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_bounded_submission() -> None:
"""Submitted task count respects max_submitted_tasks."""
provider = _mock_provider()
# Use a pipeline with many cells and low submission limit
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="cell_out", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"cell_out": GenerationStrategy.CELL_BY_CELL,
}
generators = {
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"cell_out": MockCellGenerator(config=_expr_config("cell_out"), resource_provider=provider),
}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 5)]
tracker = CompletionTracker.with_graph(graph, row_groups)
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
max_submitted_tasks=2,
)
await scheduler.run()
assert tracker.is_row_group_complete(0, 5, ["seed", "cell_out"])
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_trace_disabled_by_default() -> None:
"""Traces are empty when trace=False (default)."""
scheduler, _ = _build_simple_pipeline(num_records=2)
await scheduler.run()
assert len(scheduler.traces) == 0
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_trace_enabled() -> None:
"""Traces are populated when trace=True."""
scheduler, _ = _build_simple_pipeline(num_records=2, trace=True)
await scheduler.run()
assert len(scheduler.traces) > 0
for t in scheduler.traces:
assert t.dispatched_at > 0
assert t.completed_at >= t.dispatched_at
assert t.status in ("ok", "error")
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_three_column_pipeline() -> None:
"""Test a three-column pipeline: seed → cell → full_column."""
provider = _mock_provider()
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="cell_out", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
ExpressionColumnConfig(name="full_out", expr="{{ cell_out }}"),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"cell_out": GenerationStrategy.CELL_BY_CELL,
"full_out": GenerationStrategy.FULL_COLUMN,
}
generators = {
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"cell_out": MockCellGenerator(config=_expr_config("cell_out"), resource_provider=provider),
"full_out": MockFullColumnGenerator(config=_expr_config("full_out"), resource_provider=provider),
}
scheduler, tracker = _build_simple_pipeline(
num_records=3,
generators=generators,
configs=configs,
strategies=strategies,
trace=True,
)
await scheduler.run()
assert tracker.is_row_group_complete(0, 3, ["seed", "cell_out", "full_out"])
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_retryable_failure_recovers_in_salvage() -> None:
"""Transient (retryable) failures are retried in salvage rounds and succeed."""
provider = _mock_provider()
# Fail the first 2 calls with 503, then succeed
fail_gen = MockFailingGenerator(config=_expr_config("fail_col"), resource_provider=provider, transient_failures=2)
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="fail_col", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"fail_col": GenerationStrategy.CELL_BY_CELL,
}
generators: dict[str, ColumnGenerator] = {
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"fail_col": fail_gen,
}
scheduler, tracker = _build_simple_pipeline(
num_records=2, generators=generators, configs=configs, strategies=strategies
)
await scheduler.run()
# Rows should NOT be dropped - salvage recovered them
assert not tracker.is_dropped(0, 0)
assert not tracker.is_dropped(0, 1)
assert tracker.is_row_group_complete(0, 2, ["seed", "fail_col"])
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_eager_row_drop_skips_downstream_of_failed_column() -> None:
"""When fail_col drops a row, a downstream column never processes it."""
provider = _mock_provider()
# Pipeline: seed -> fail_col (cell, permanent failure) -> downstream (cell)
# downstream depends on fail_col, so its tasks only enter the frontier
# after fail_col completes for each row. Since fail_col always fails,
# the row is dropped before downstream is ever enqueued.
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="fail_col", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
LLMTextColumnConfig(name="downstream", prompt="{{ fail_col }}", model_alias=MODEL_ALIAS),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"fail_col": GenerationStrategy.CELL_BY_CELL,
"downstream": GenerationStrategy.CELL_BY_CELL,
}
generators: dict[str, ColumnGenerator] = {
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"fail_col": MockFailingGenerator(config=_expr_config("fail_col"), resource_provider=provider),
"downstream": MockCellGenerator(config=_expr_config("downstream"), resource_provider=provider),
}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 2)]
tracker = CompletionTracker.with_graph(graph, row_groups)
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
trace=True,
num_records=2,
buffer_size=2,
)
await scheduler.run()
# All rows dropped by fail_col
assert tracker.is_dropped(0, 0)
assert tracker.is_dropped(0, 1)
# downstream was never dispatched for the dropped rows
downstream_traces = [t for t in scheduler.traces if t.column == "downstream"]
assert len(downstream_traces) == 0
# Row group is still "complete" (no non-dropped rows remain)
assert tracker.is_row_group_complete(0, 2, ["seed", "fail_col", "downstream"])
assert scheduler._reporter is not None
assert scheduler._reporter._trackers["fail_col"].failed == 2
assert scheduler._reporter._trackers["downstream"].skipped == 2
assert scheduler._reporter._trackers["downstream"].completed == 2
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_non_retryable_seed_failure_no_keyerror_on_downstream() -> None:
"""Non-retryable seed failure does not cause KeyError on vacuously-ready downstream.
Pipeline: seed (full_column) -> cell_out (cell_by_cell) -> full_out (full_column).
When seed fails non-retryably, all rows are dropped. cell_out's cell tasks
become vacuously complete (all rows dropped), which makes full_out ready.
full_out must not crash with a KeyError when its row group buffer has been
checkpointed.
"""
provider = _mock_provider()
storage = MagicMock()
storage.dataset_name = "test"
storage.get_file_paths.return_value = {}
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="cell_out", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
ExpressionColumnConfig(name="full_out", expr="{{ cell_out }}"),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"cell_out": GenerationStrategy.CELL_BY_CELL,
"full_out": GenerationStrategy.FULL_COLUMN,
}
generators: dict[str, ColumnGenerator] = {
"seed": MockFailingSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"cell_out": MockCellGenerator(config=_expr_config("cell_out"), resource_provider=provider),
"full_out": MockFullColumnGenerator(config=_expr_config("full_out"), resource_provider=provider),
}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 3)]
tracker = CompletionTracker.with_graph(graph, row_groups)
buffer_mgr = RowGroupBufferManager(storage)
finalized: list[int] = []
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
buffer_manager=buffer_mgr,
on_finalize_row_group=lambda rg: finalized.append(rg),
trace=True,
num_records=3,
buffer_size=3,
)
await scheduler.run()
# All rows dropped due to seed failure
for ri in range(3):
assert tracker.is_dropped(0, ri)
# Row group is NOT finalized when all rows are dropped (freed instead)
assert 0 not in finalized
# full_out was either never dispatched or silently skipped (no KeyError)
full_out_errors = [t for t in scheduler.traces if t.column == "full_out" and t.status == "error"]
assert len(full_out_errors) == 0
assert scheduler._reporter is not None
assert scheduler._reporter._trackers["cell_out"].skipped == 3
assert scheduler._reporter._trackers["cell_out"].completed == 3
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_pre_batch_failure_marks_downstream_tasks_skipped() -> None:
"""Pre-batch row-group drops count downstream cell tasks as skipped."""
provider = _mock_provider()
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="cell_out", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"cell_out": GenerationStrategy.CELL_BY_CELL,
}
generators = {
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"cell_out": MockCellGenerator(config=_expr_config("cell_out"), resource_provider=provider),
}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 3)]
tracker = CompletionTracker.with_graph(graph, row_groups)
def fail_pre_batch(row_group: int, row_group_size: int) -> None:
raise ValueError(f"pre-batch failed for {row_group}/{row_group_size}")
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
on_seeds_complete=fail_pre_batch,
num_records=3,
buffer_size=3,
)
await scheduler.run()
for row_index in range(3):
assert tracker.is_dropped(0, row_index)
assert scheduler._reporter is not None
assert scheduler._reporter._trackers["cell_out"].skipped == 3
assert scheduler._reporter._trackers["cell_out"].completed == 3
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_error_rate_shutdown() -> None:
"""Early shutdown triggers when error rate exceeds threshold."""
provider = _mock_provider()
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="fail_col", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"fail_col": GenerationStrategy.CELL_BY_CELL,
}
generators = {
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"fail_col": MockFailingGenerator(config=_expr_config("fail_col"), resource_provider=provider),
}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 10)]
tracker = CompletionTracker.with_graph(graph, row_groups)
storage = MagicMock()
storage.dataset_name = "test"
storage.get_file_paths.return_value = {}
storage.write_batch_to_parquet_file.return_value = "/fake.parquet"
storage.move_partial_result_to_final_file_path.return_value = "/fake_final.parquet"
buffer_mgr = RowGroupBufferManager(storage)
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
buffer_manager=buffer_mgr,
shutdown_error_rate=0.5,
shutdown_error_window=2,
)
await scheduler.run()
# Early shutdown: not all rows should be checkpointed (some row groups incomplete)
assert buffer_mgr.actual_num_records < 10
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_early_shutdown_disabled() -> None:
"""shutdown_error_rate=1.0 prevents shutdown even at 100% error rate."""
provider = _mock_provider()
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="fail_col", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"fail_col": GenerationStrategy.CELL_BY_CELL,
}
generators = {
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"fail_col": MockFailingGenerator(config=_expr_config("fail_col"), resource_provider=provider),
}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 5)]
tracker = CompletionTracker.with_graph(graph, row_groups)
storage = MagicMock()
storage.dataset_name = "test"
storage.get_file_paths.return_value = {}
buffer_mgr = RowGroupBufferManager(storage)
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
buffer_manager=buffer_mgr,
shutdown_error_rate=1.0,
)
await scheduler.run()
# All rows dropped (all fail) but no early shutdown - all row groups processed
assert all(tracker.is_dropped(0, ri) for ri in range(5))
assert tracker.is_row_group_complete(0, 5, ["seed", "fail_col"])
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_sliding_window_error_rate_recovers() -> None:
"""Transient errors diluted by successes do not trigger early shutdown."""
provider = _mock_provider()
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="col", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"col": GenerationStrategy.CELL_BY_CELL,
}
# First 2 calls fail (retryable 503), rest succeed.
# With window=10 and 10 cell tasks, at most 2/10 = 20% error rate
# when the window first fills - well below the 0.4 threshold.
generators = {
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"col": MockFailingGenerator(config=_expr_config("col"), resource_provider=provider, transient_failures=2),
}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 10)]
tracker = CompletionTracker.with_graph(graph, row_groups)
storage = MagicMock()
storage.dataset_name = "test"
storage.get_file_paths.return_value = {}
storage.write_batch_to_parquet_file.return_value = "/fake.parquet"
storage.move_partial_result_to_final_file_path.return_value = "/fake_final.parquet"
buffer_mgr = RowGroupBufferManager(storage)
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
buffer_manager=buffer_mgr,
shutdown_error_rate=0.4,
shutdown_error_window=10,
)
await scheduler.run()
# No early shutdown - transient errors recovered in salvage
assert not scheduler._early_shutdown
assert tracker.is_row_group_complete(0, 10, ["seed", "col"])
@pytest.mark.asyncio(loop_scope="session")
async def test_rate_limit_errors_do_not_trigger_early_shutdown() -> None:
"""Rate-limit (429) errors are expected AIMD behavior and must not count toward early shutdown."""
provider = _mock_provider()
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="col", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"col": GenerationStrategy.CELL_BY_CELL,
}
generators = {
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"col": MockRateLimitGenerator(config=_expr_config("col"), resource_provider=provider, rate_limit_failures=8),
}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 10)]
tracker = CompletionTracker.with_graph(graph, row_groups)
storage = MagicMock()
storage.dataset_name = "test"
storage.get_file_paths.return_value = {}
storage.write_batch_to_parquet_file.return_value = "/fake.parquet"
storage.move_partial_result_to_final_file_path.return_value = "/fake_final.parquet"
buffer_mgr = RowGroupBufferManager(storage)
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
buffer_manager=buffer_mgr,
shutdown_error_rate=0.5,
shutdown_error_window=10,
)
await scheduler.run()
assert not scheduler._early_shutdown
assert tracker.is_row_group_complete(0, 10, ["seed", "col"])
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_on_before_checkpoint_callback() -> None:
"""on_before_checkpoint is called before each row group is checkpointed."""
provider = _mock_provider()
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
]
strategies = {"seed": GenerationStrategy.FULL_COLUMN}
generators = {"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider)}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 3), (1, 2)]
tracker = CompletionTracker.with_graph(graph, row_groups)
storage = MagicMock()
storage.dataset_name = "test"
storage.get_file_paths.return_value = {}
storage.write_batch_to_parquet_file.return_value = "/fake.parquet"
storage.move_partial_result_to_final_file_path.return_value = "/fake_final.parquet"
buffer_mgr = RowGroupBufferManager(storage)
callback_log: list[tuple[int, int]] = []
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
buffer_manager=buffer_mgr,
on_before_checkpoint=lambda rg, sz: callback_log.append((rg, sz)),
)
await scheduler.run()
assert sorted(callback_log) == [(0, 3), (1, 2)]
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_on_finalize_row_group_callback_fires() -> None:
"""on_finalize_row_group is called for each completed row group."""
provider = _mock_provider()
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
]
strategies = {"seed": GenerationStrategy.FULL_COLUMN}
generators = {"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider)}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 3)]
tracker = CompletionTracker.with_graph(graph, row_groups)
storage = MagicMock()
storage.dataset_name = "test"
storage.get_file_paths.return_value = {}
storage.write_batch_to_parquet_file.return_value = "/fake.parquet"
storage.move_partial_result_to_final_file_path.return_value = "/fake_final.parquet"
buffer_mgr = RowGroupBufferManager(storage)
finalized: list[int] = []
def finalize_row_group(rg_id: int) -> None:
buffer_mgr.checkpoint_row_group(rg_id)
finalized.append(rg_id)
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
buffer_manager=buffer_mgr,
on_finalize_row_group=finalize_row_group,
)
await scheduler.run()
assert finalized == [0]
assert storage.write_batch_to_parquet_file.call_count == 1
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_on_finalize_skips_empty_row_group() -> None:
"""on_finalize_row_group is not called when all rows are dropped."""
provider = _mock_provider()
storage = MagicMock()
storage.dataset_name = "test"
storage.get_file_paths.return_value = {}
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
]
strategies = {"seed": GenerationStrategy.FULL_COLUMN}
generators = {
"seed": MockFailingSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 3)]
tracker = CompletionTracker.with_graph(graph, row_groups)
buffer_mgr = RowGroupBufferManager(storage)
callback = MagicMock()
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
buffer_manager=buffer_mgr,
on_finalize_row_group=callback,
)
await scheduler.run()
callback.assert_not_called()
storage.write_batch_to_parquet_file.assert_not_called()
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_pre_batch_failure_skips_row_group() -> None:
"""Pre-batch processor failure drops all rows in the row group; other row groups continue."""
provider = _mock_provider()
seed_gen = MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider)
cell_gen = MockCellGenerator(config=_expr_config("cell_out"), resource_provider=provider)
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="cell_out", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"cell_out": GenerationStrategy.CELL_BY_CELL,
}
generators = {"seed": seed_gen, "cell_out": cell_gen}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 3), (1, 2)]
tracker = CompletionTracker.with_graph(graph, row_groups)
storage = MagicMock()
storage.dataset_name = "test"
storage.get_file_paths.return_value = {}
storage.write_batch_to_parquet_file.return_value = "/fake.parquet"
storage.move_partial_result_to_final_file_path.return_value = "/fake_final.parquet"
buffer_mgr = RowGroupBufferManager(storage)
def failing_pre_batch(rg_id: int, rg_size: int) -> None:
if rg_id == 0:
raise RuntimeError("pre-batch processor failed")
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=row_groups,
buffer_manager=buffer_mgr,
on_seeds_complete=failing_pre_batch,
)
await scheduler.run()
# Row group 0: all rows dropped due to pre-batch failure
assert all(tracker.is_dropped(0, ri) for ri in range(3))
# Row group 1: completed normally
assert tracker.is_row_group_complete(1, 2, ["seed", "cell_out"])
class _SlowSeedGenerator(FromScratchColumnGenerator[ExpressionColumnConfig]):
"""Seed generator whose async cost scales with row count.
Both RGs' seed tasks run concurrently. The task with fewer rows sleeps for
less real time, causing its downstream to be dispatched and completed first.
"""
@staticmethod
def get_generation_strategy() -> GenerationStrategy:
return GenerationStrategy.FULL_COLUMN