-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathtest_async_scheduler.py
More file actions
3674 lines (3069 loc) · 143 KB
/
test_async_scheduler.py
File metadata and controls
3674 lines (3069 loc) · 143 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
import logging
import time
from collections.abc import Callable
from types import SimpleNamespace
from typing import Any
from unittest.mock import MagicMock
import pytest
import data_designer.lazy_heavy_imports as lazy
from data_designer.config.base import SkipConfig
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.models import ChatCompletionInferenceParams, ModelConfig
from data_designer.config.sampler_params import SamplerType
from data_designer.config.scheduling import SchedulingMetadata
from data_designer.engine.column_generators.generators.base import (
ColumnGenerator,
ColumnGeneratorFullColumn,
ColumnGeneratorWithModelRegistry,
FromScratchColumnGenerator,
)
from data_designer.engine.column_generators.generators.custom import CustomColumnGenerator
from data_designer.engine.dataset_builders.async_scheduler import AsyncTaskScheduler
from data_designer.engine.dataset_builders.errors import DatasetGenerationError
from data_designer.engine.dataset_builders.scheduling.completion import CompletionTracker, FrontierDelta
from data_designer.engine.dataset_builders.scheduling.task_admission import TaskAdmissionConfig, TaskAdmissionLease
from data_designer.engine.dataset_builders.scheduling.task_model import Task
from data_designer.engine.dataset_builders.scheduling.task_policies import BoundedBorrowTaskAdmissionPolicyConfig
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 (
RETRYABLE_MODEL_ERRORS,
ModelInternalServerError,
ModelRateLimitError,
ModelTimeoutError,
)
from data_designer.engine.models.request_admission.config import RequestAdmissionConfig
from data_designer.engine.models.request_admission.controller import (
AdaptiveRequestAdmissionController,
RequestAdmissionLease,
)
from data_designer.engine.models.request_admission.outcomes import RequestReleaseOutcome
from data_designer.engine.models.request_admission.pressure import RequestPressureSnapshot
from data_designer.engine.models.request_admission.resources import (
RequestAdmissionItem,
RequestDomain,
RequestGroupSpec,
RequestResourceKey,
)
from data_designer.engine.models.resources import ProviderModelKey
from data_designer.engine.observability import InMemoryAdmissionEventSink
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 MockRootCellGenerator(ColumnGenerator[ExpressionColumnConfig]):
"""Root cell generator that records the shape it receives."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.call_types: list[str] = []
@staticmethod
def get_generation_strategy() -> GenerationStrategy:
return GenerationStrategy.CELL_BY_CELL
def generate(self, data: dict) -> dict:
self.call_types.append(type(data).__name__)
if not isinstance(data, dict):
raise TypeError(f"expected dict, got {type(data).__name__}")
data[self.config.name] = f"root_{len(self.call_types)}"
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 MockBuggyGenerator(ColumnGenerator[ExpressionColumnConfig]):
"""Generator that raises a bare built-in exception from generator code."""
@staticmethod
def get_generation_strategy() -> GenerationStrategy:
return GenerationStrategy.CELL_BY_CELL
def generate(self, _data: dict) -> dict:
raise KeyError("missing internal key")
class MockBuggyFromScratchGenerator(FromScratchColumnGenerator[ExpressionColumnConfig]):
"""From-scratch generator that raises a bare built-in exception from generator code."""
@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 AssertionError("invalid seed source")
class MockMalformedFromScratchGenerator(FromScratchColumnGenerator[ExpressionColumnConfig]):
"""From-scratch generator that returns a non-DataFrame object."""
@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) -> Any:
return [{"seed": index} for index in range(num_records)]
class MockBuggyFullColumnGenerator(ColumnGeneratorFullColumn[ExpressionColumnConfig]):
"""Full-column generator that raises a bare built-in exception from generator code."""
def generate(self, _data: lazy.pd.DataFrame) -> lazy.pd.DataFrame:
raise TypeError("bad batch shape")
class MockMalformedFullColumnGenerator(ColumnGeneratorFullColumn[ExpressionColumnConfig]):
"""Full-column generator that returns a non-DataFrame object."""
def generate(self, data: lazy.pd.DataFrame) -> Any:
return [{"seed": value, self.config.name: "bad"} for value in data.get("seed", [])]
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
class MockSelectiveFailGenerator(ColumnGenerator[ExpressionColumnConfig]):
"""Cell generator with deterministic per-seed behavior.
- Seeds in ``fail_on_seeds``: raise a non-retryable ``ValueError`` immediately.
- Seeds in ``slow_seeds``: block on ``asyncio.sleep`` so they remain
in-flight when the early-shutdown gate fires.
- All others: succeed.
Cell-by-cell only — exercised through ``agenerate`` from the async scheduler.
"""
def __init__(
self,
*args: Any,
fail_on_seeds: set[int] = frozenset(),
slow_seeds: set[int] = frozenset(),
slow_timeout_s: float = 5.0,
**kwargs: Any,
) -> None:
super().__init__(*args, **kwargs)
self._fail = set(fail_on_seeds)
self._slow = set(slow_seeds)
self._slow_timeout_s = slow_timeout_s
@staticmethod
def get_generation_strategy() -> GenerationStrategy:
return GenerationStrategy.CELL_BY_CELL
async def agenerate(self, data: dict) -> dict:
seed = data.get("seed")
if seed in self._fail:
raise ValueError(f"non-retryable on seed={seed}")
if seed in self._slow:
await asyncio.sleep(self._slow_timeout_s)
data[self.config.name] = f"ok_{seed}"
return data
def generate(self, data: dict) -> dict:
# Sync path: kept minimal because this mock is exercised exclusively
# through ``agenerate`` from the async scheduler. ``slow_seeds`` is
# intentionally not honored here — callers needing sync slow behavior
# should use a different fixture.
seed = data.get("seed")
if seed in self._fail:
raise ValueError(f"non-retryable on seed={seed}")
data[self.config.name] = f"ok_{seed}"
return data
class MockRetryableErrorGenerator(ColumnGenerator[ExpressionColumnConfig]):
"""Generator that raises a parametrizable retryable error then succeeds.
Declares model scheduling metadata because it mimics model-call behavior;
the scheduler's degraded-provider WARN window counts model-stage tasks.
"""
def __init__(
self,
*args: Any,
error_factory: Callable[[], Exception],
retryable_failures: int = 0,
**kwargs: Any,
) -> None:
super().__init__(*args, **kwargs)
self._error_factory = error_factory
self._retryable_failures = retryable_failures
self._calls = 0
@staticmethod
def get_generation_strategy() -> GenerationStrategy:
return GenerationStrategy.CELL_BY_CELL
def get_scheduling_metadata(self) -> SchedulingMetadata:
return SchedulingMetadata.custom_model("test", self.config.name, "v1")
def generate(self, data: dict) -> dict:
self._calls += 1
if self._calls <= self._retryable_failures:
raise self._error_factory()
data[self.config.name] = f"ok_{data.get('seed', '?')}"
return data
class _BrokenSchedulerSink:
def emit_scheduler_event(self, _event: object) -> None:
raise RuntimeError("sink boom")
# -- 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,
scheduler_event_sink: Any | 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,
scheduler_event_sink=scheduler_event_sink,
)
return scheduler, tracker
def _make_storage() -> MagicMock:
"""Standard mock storage for buffer-manager-backed scheduler tests."""
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"
return storage
def _seed_plus_cell_setup(
cell_generator: ColumnGenerator,
num_records: int,
) -> tuple[
dict[str, ColumnGenerator],
ExecutionGraph,
list[tuple[int, int]],
CompletionTracker,
RowGroupBufferManager,
MagicMock,
]:
"""Build the shared seed → LLM cell pipeline scaffolding (no scheduler yet).
Used by early-shutdown / WARN tests that need a real ``buffer_manager``
*before* constructing the scheduler (e.g. to wire a checkpoint callback
that closes over it).
"""
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": cell_generator,
}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, num_records)]
tracker = CompletionTracker.with_graph(graph, row_groups)
storage = _make_storage()
buffer_manager = RowGroupBufferManager(storage)
return generators, graph, row_groups, tracker, buffer_manager, storage
# -- 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_dispatches_root_cell_by_cell_columns_per_row() -> None:
provider = _mock_provider()
generator = MockRootCellGenerator(config=_expr_config("root_cell"), resource_provider=provider)
configs = [SamplerColumnConfig(name="root_cell", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]})]
strategies = {"root_cell": GenerationStrategy.CELL_BY_CELL}
graph = ExecutionGraph.create(configs, strategies)
row_groups = [(0, 3)]
tracker = CompletionTracker.with_graph(graph, row_groups)
scheduler = AsyncTaskScheduler(
generators={"root_cell": generator},
graph=graph,
tracker=tracker,
row_groups=row_groups,
trace=True,
)
await scheduler.run()
assert generator.call_types == ["dict", "dict", "dict"]
assert [trace.task_type for trace in scheduler.traces] == ["cell", "cell", "cell"]
assert not any(tracker.is_dropped(0, row_index) for row_index in range(3))
assert tracker.is_row_group_complete(0, 3, ["root_cell"])
@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"])
def test_scheduler_internal_bug_classifier_preserves_scheduler_builtin_failures() -> None:
scheduler, tracker = _build_simple_pipeline(num_records=1)
assert scheduler._is_internal_bug(KeyError("missing internal key"))
assert not scheduler._is_internal_bug(DatasetGenerationError("generator failure"))
assert not tracker.is_dropped(0, 0)
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_generator_builtin_exception_drops_cell_without_fatal_abort(
caplog: pytest.LogCaptureFixture,
) -> None:
provider = _mock_provider()
scheduler, tracker = _build_simple_pipeline(
num_records=1,
configs=[
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="buggy_col", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
],
strategies={
"seed": GenerationStrategy.FULL_COLUMN,
"buggy_col": GenerationStrategy.CELL_BY_CELL,
},
generators={
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"buggy_col": MockBuggyGenerator(config=_expr_config("buggy_col"), resource_provider=provider),
},
)
with caplog.at_level(logging.WARNING, logger="data_designer.engine.dataset_builders.async_scheduler"):
await scheduler.run()
assert tracker.is_dropped(0, 0)
assert isinstance(scheduler.first_non_retryable_error, DatasetGenerationError)
assert isinstance(scheduler.first_non_retryable_error.__cause__, KeyError)
assert "Unexpected fatal Non-retryable failure" not in caplog.text
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_generator_builtin_exception_drops_from_scratch_group_without_fatal_abort(
caplog: pytest.LogCaptureFixture,
) -> None:
provider = _mock_provider()
configs = [SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]})]
strategies = {"seed": GenerationStrategy.FULL_COLUMN}
generators = {"seed": MockBuggyFromScratchGenerator(config=_expr_config("seed"), resource_provider=provider)}
graph = ExecutionGraph.create(configs, strategies)
tracker = CompletionTracker.with_graph(graph, [(0, 2)])
scheduler = AsyncTaskScheduler(
generators=generators,
graph=graph,
tracker=tracker,
row_groups=[(0, 2)],
)
with caplog.at_level(logging.WARNING, logger="data_designer.engine.dataset_builders.async_scheduler"):
await scheduler.run()
assert tracker.is_dropped(0, 0)
assert tracker.is_dropped(0, 1)
assert isinstance(scheduler.first_non_retryable_error, DatasetGenerationError)
assert isinstance(scheduler.first_non_retryable_error.__cause__, AssertionError)
assert "Unexpected fatal Non-retryable failure" not in caplog.text
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_generator_builtin_exception_drops_batch_group_without_fatal_abort(
caplog: pytest.LogCaptureFixture,
) -> None:
provider = _mock_provider()
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="buggy_batch", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"buggy_batch": GenerationStrategy.FULL_COLUMN,
}
generators = {
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"buggy_batch": MockBuggyFullColumnGenerator(
config=_expr_config("buggy_batch"),
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,
buffer_manager=RowGroupBufferManager(_make_storage()),
)
with caplog.at_level(logging.WARNING, logger="data_designer.engine.dataset_builders.async_scheduler"):
await scheduler.run()
assert tracker.is_dropped(0, 0)
assert tracker.is_dropped(0, 1)
assert isinstance(scheduler.first_non_retryable_error, DatasetGenerationError)
assert isinstance(scheduler.first_non_retryable_error.__cause__, TypeError)
assert "Unexpected fatal Non-retryable failure" not in caplog.text
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_generator_malformed_from_scratch_return_drops_group_without_fatal_abort(
caplog: pytest.LogCaptureFixture,
) -> None:
provider = _mock_provider()
configs = [SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]})]
strategies = {"seed": GenerationStrategy.FULL_COLUMN}
generators = {"seed": MockMalformedFromScratchGenerator(config=_expr_config("seed"), 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,
buffer_manager=RowGroupBufferManager(_make_storage()),
)
with caplog.at_level(logging.WARNING, logger="data_designer.engine.dataset_builders.async_scheduler"):
await scheduler.run()
assert tracker.is_dropped(0, 0)
assert tracker.is_dropped(0, 1)
assert isinstance(scheduler.first_non_retryable_error, DatasetGenerationError)
assert "must return a DataFrame, got list" in str(scheduler.first_non_retryable_error)
assert "Unexpected fatal Non-retryable failure" not in caplog.text
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_generator_malformed_batch_return_drops_group_without_fatal_abort(
caplog: pytest.LogCaptureFixture,
) -> None:
provider = _mock_provider()
configs = [
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
LLMTextColumnConfig(name="malformed_batch", prompt="{{ seed }}", model_alias=MODEL_ALIAS),
]
strategies = {
"seed": GenerationStrategy.FULL_COLUMN,
"malformed_batch": GenerationStrategy.FULL_COLUMN,
}
generators = {
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"malformed_batch": MockMalformedFullColumnGenerator(
config=_expr_config("malformed_batch"),
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,
buffer_manager=RowGroupBufferManager(_make_storage()),
)
with caplog.at_level(logging.WARNING, logger="data_designer.engine.dataset_builders.async_scheduler"):
await scheduler.run()
assert tracker.is_dropped(0, 0)
assert tracker.is_dropped(0, 1)
assert isinstance(scheduler.first_non_retryable_error, DatasetGenerationError)
assert "must return a DataFrame, got list" in str(scheduler.first_non_retryable_error)
assert "Unexpected fatal Non-retryable failure" not in caplog.text
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_custom_generator_key_error_drops_row_without_fatal_abort(
caplog: pytest.LogCaptureFixture,
) -> None:
@custom_column_generator()
def failing_custom(row: dict) -> dict:
raise KeyError("missing user field")
provider = _mock_provider()
custom_config = CustomColumnConfig(name="custom_col", generator_function=failing_custom)
scheduler, tracker = _build_simple_pipeline(
num_records=1,
configs=[
SamplerColumnConfig(name="seed", sampler_type=SamplerType.CATEGORY, params={"values": ["A"]}),
custom_config,
],
strategies={
"seed": GenerationStrategy.FULL_COLUMN,
"custom_col": GenerationStrategy.CELL_BY_CELL,
},
generators={
"seed": MockSeedGenerator(config=_expr_config("seed"), resource_provider=provider),
"custom_col": CustomColumnGenerator(config=custom_config, resource_provider=provider),
},
)
with caplog.at_level(logging.WARNING):
await scheduler.run()
assert tracker.is_dropped(0, 0)
assert "This record will be skipped" in caplog.text
assert "Unexpected fatal Non-retryable failure" not in caplog.text
@pytest.mark.asyncio(loop_scope="session")
async def test_scheduler_logs_sink_failures(caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level(logging.WARNING, logger="data_designer.engine.dataset_builders.async_scheduler")
scheduler, tracker = _build_simple_pipeline(num_records=1, scheduler_event_sink=_BrokenSchedulerSink())
await scheduler.run()
assert tracker.is_row_group_complete(0, 1, ["seed", "cell_out"])
assert "Scheduler admission event sink raised; dropping event." in caplog.text
@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_in_flight_tasks() -> None:
"""In-flight task count respects max_in_flight_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_in_flight_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),
}