-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathdataset_builder.py
More file actions
1605 lines (1406 loc) · 76.8 KB
/
dataset_builder.py
File metadata and controls
1605 lines (1406 loc) · 76.8 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) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import contextlib
import functools
import json
import logging
import os
import time
import uuid
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable
from pydantic import ValidationError
import data_designer.lazy_heavy_imports as lazy
from data_designer.config.column_types import ColumnConfigT, DataDesignerColumnType
from data_designer.config.config_builder import BuilderConfig
from data_designer.config.data_designer_config import DataDesignerConfig
from data_designer.config.processors import (
DropColumnsProcessorConfig,
ProcessorConfig,
ProcessorType,
)
from data_designer.config.utils.type_helpers import StrEnum
from data_designer.config.utils.warning_helpers import warn_at_caller
from data_designer.config.version import get_library_version
from data_designer.engine.column_generators.generators.base import (
ColumnGenerator,
ColumnGeneratorWithModel,
GenerationStrategy,
)
from data_designer.engine.column_generators.utils.generator_classification import column_type_is_model_generated
from data_designer.engine.compiler import compile_data_designer_config
from data_designer.engine.dataset_builders.errors import DatasetGenerationError
from data_designer.engine.dataset_builders.multi_column_configs import MultiColumnConfig
from data_designer.engine.dataset_builders.utils.concurrency import ConcurrentThreadExecutor
from data_designer.engine.dataset_builders.utils.config_compiler import compile_dataset_builder_column_configs
from data_designer.engine.dataset_builders.utils.dataset_batch_manager import DatasetBatchManager
from data_designer.engine.dataset_builders.utils.execution_graph import ExecutionGraph
from data_designer.engine.dataset_builders.utils.processor_runner import ProcessorRunner, ProcessorStage
from data_designer.engine.dataset_builders.utils.progress_tracker import ProgressTracker
from data_designer.engine.dataset_builders.utils.skip_evaluator import should_skip_column_for_record
from data_designer.engine.dataset_builders.utils.skip_tracker import (
SKIPPED_COLUMNS_RECORD_KEY,
apply_skip_to_record,
prepare_records_for_skip_metadata_round_trip,
restore_skip_metadata,
strip_skip_metadata_from_records,
)
from data_designer.engine.dataset_builders.utils.sticky_progress_bar import StickyProgressBar
from data_designer.engine.models.telemetry import InferenceEvent, NemoSourceEnum, TaskStatusEnum, TelemetryHandler
from data_designer.engine.processing.processors.base import Processor
from data_designer.engine.processing.processors.drop_columns import DropColumnsProcessor
from data_designer.engine.registry.data_designer_registry import DataDesignerRegistry
from data_designer.engine.resources.resource_provider import ResourceProvider
from data_designer.engine.storage.artifact_storage import (
METADATA_FILENAME,
SDG_CONFIG_FILENAME,
ArtifactStorage,
ResumeMode,
)
from data_designer.engine.storage.media_storage import StorageMode
if TYPE_CHECKING:
import pandas as pd
from data_designer.config.run_config import RunConfig
from data_designer.engine.column_generators.generators.base import ColumnGeneratorWithModelRegistry
from data_designer.engine.dataset_builders.utils.task_model import TaskTrace
from data_designer.engine.models.usage import ModelUsageStats
logger = logging.getLogger(__name__)
# Async engine is the default execution path. Set ``DATA_DESIGNER_ASYNC_ENGINE=0``
# to opt back into the legacy sync engine for one transitional release; the sync
# path is scheduled for removal afterwards.
DATA_DESIGNER_ASYNC_ENGINE = os.environ.get("DATA_DESIGNER_ASYNC_ENGINE", "1") == "1"
if DATA_DESIGNER_ASYNC_ENGINE:
import asyncio
from data_designer.engine.dataset_builders.async_scheduler import (
DEFAULT_TASK_POOL_SIZE,
GLOBAL_LLM_WAIT_POOL_HEADROOM_MULTIPLIER,
AsyncTaskScheduler,
)
from data_designer.engine.dataset_builders.utils.async_concurrency import (
AsyncConcurrentExecutor,
ensure_async_engine_loop,
)
from data_designer.engine.dataset_builders.utils.completion_tracker import CompletionTracker, FrontierDelta
from data_designer.engine.dataset_builders.utils.row_group_buffer import RowGroupBufferManager
_CLIENT_VERSION: str = get_library_version()
def _is_async_trace_enabled(settings: RunConfig) -> bool:
return settings.async_trace or os.environ.get("DATA_DESIGNER_ASYNC_TRACE", "0") == "1"
class _ConfigCompatibility(StrEnum):
COMPATIBLE = "compatible"
INCOMPATIBLE = "incompatible"
NO_PRIOR_DATASET = "no_prior_dataset"
@dataclass
class _ResumeState:
num_completed_batches: int
actual_num_records: int
buffer_size: int
target_num_records: int
original_target_num_records: int
completed_row_groups: dict[int, int]
class DatasetBuilder:
def __init__(
self,
data_designer_config: DataDesignerConfig,
resource_provider: ResourceProvider,
registry: DataDesignerRegistry | None = None,
):
self.batch_manager = DatasetBatchManager(resource_provider.artifact_storage)
self._resource_provider = resource_provider
self._records_to_drop: set[int] = set()
self._cell_resize_results: list[dict | list[dict] | None] = []
self._cell_resize_mode = False
self._task_traces: list[TaskTrace] = []
self._registry = registry or DataDesignerRegistry()
self._graph: ExecutionGraph | None = None
self._use_async: bool = DATA_DESIGNER_ASYNC_ENGINE
# Structured signal: set by _build_async if the scheduler hit early shutdown.
# Stays at defaults for sync-engine and successful async runs. Reset at
# the start of each public run path so reused builder instances don't
# leak state across runs.
self._early_shutdown: bool = False
self._partial_row_groups: tuple[int, ...] = ()
# Number of records actually written by the most recent async run.
# ``-1`` means "no async run has executed yet" so callers can
# distinguish "0 records produced" from "never ran".
self._actual_num_records: int = -1
# First non-retryable error captured by the scheduler in the most recent
# async run, if any. Used by the interface to surface the original cause
# when a run produces 0 records due to deterministic failures.
self._first_non_retryable_error: Exception | None = None
self._data_designer_config = compile_data_designer_config(data_designer_config, resource_provider)
self._column_configs = compile_dataset_builder_column_configs(self._data_designer_config)
processors = self._initialize_processors(self._data_designer_config.processors or [])
self._processor_runner = ProcessorRunner(
processors=processors,
artifact_storage=resource_provider.artifact_storage,
)
self._validate_column_configs()
@property
def artifact_storage(self) -> ArtifactStorage:
return self._resource_provider.artifact_storage
@property
def processors(self) -> tuple[Processor, ...]:
return self._processor_runner.processors
@property
def task_traces(self) -> list[TaskTrace]:
return self._task_traces
@property
def early_shutdown(self) -> bool:
"""True if the most recent async run terminated via the early-shutdown gate."""
return self._early_shutdown
@property
def partial_row_groups(self) -> tuple[int, ...]:
"""Row group ids that were partially salvaged after early shutdown (most recent run)."""
return self._partial_row_groups
@property
def actual_num_records(self) -> int:
"""Records actually written by the most recent async run (-1 if no run yet)."""
return self._actual_num_records
@property
def first_non_retryable_error(self) -> Exception | None:
"""First non-retryable error captured by the scheduler in the most recent run."""
return self._first_non_retryable_error
def set_processor_runner(self, processors: list[Processor]) -> None:
"""Replace the processor runner with a new one using the given processors."""
self._processor_runner = ProcessorRunner(
processors=processors,
artifact_storage=self.artifact_storage,
)
@functools.cached_property
def single_column_configs(self) -> list[ColumnConfigT]:
configs = []
for config in self._column_configs:
if isinstance(config, MultiColumnConfig):
configs.extend(config.columns)
else:
configs.append(config)
return configs
@functools.cached_property
def single_column_config_by_name(self) -> dict[str, ColumnConfigT]:
return {config.name: config for config in self.single_column_configs}
@functools.cached_property
def llm_generated_column_configs(self) -> list[ColumnConfigT]:
return [config for config in self.single_column_configs if column_type_is_model_generated(config.column_type)]
def build(
self,
*,
num_records: int,
on_batch_complete: Callable[[Path], None] | None = None,
save_multimedia_to_disk: bool = True,
resume: ResumeMode = ResumeMode.NEVER,
) -> Path:
"""Build the dataset.
Args:
num_records: Number of records to generate.
on_batch_complete: Optional callback function called when each batch completes.
save_multimedia_to_disk: Whether to save generated multimedia (images, audio, video) to disk.
If False, multimedia is stored directly in the DataFrame (e.g., images as base64).
Default is True.
resume: Controls how interrupted runs are handled.
- ``ResumeMode.NEVER`` (default): always start a fresh generation run.
- ``ResumeMode.ALWAYS``: resume from the last completed batch (sync) or row group
(async). ``buffer_size`` must match the original run. ``num_records`` may be
equal to or greater than what was already generated (you can extend the dataset);
``num_records`` less than actual records so far raises ``DatasetGenerationError``.
If no checkpoint exists yet (interrupted before the first batch finished), silently
restarts from the beginning. Raises if the stored config is incompatible.
- ``ResumeMode.IF_POSSIBLE``: like ``ALWAYS`` when the current config fingerprint
matches the stored config; otherwise starts a fresh run without raising an error.
In all resume modes, in-flight partial results from the interrupted run are
discarded before generation continues.
Returns:
Path to the generated dataset directory.
"""
self._reset_run_state()
self._run_model_health_check_if_needed()
self._run_mcp_tool_check_if_needed()
# For IF_POSSIBLE and ALWAYS: check config compatibility before touching the artifact
# directory. _check_resume_config_compatibility() must NOT access base_dataset_path
# (which would cache resolved_dataset_name prematurely). After the decision, sync
# artifact_storage.resume so that resolved_dataset_name picks up the right semantics
# on its first real access.
#
# Also invalidate any stale resolved_dataset_name cache: ArtifactStorage's Pydantic
# validator accesses base_dataset_path at construction time, which caches resolved_dataset_name
# under the original resume mode semantics. Popping it forces a fresh resolution.
if resume in (ResumeMode.IF_POSSIBLE, ResumeMode.ALWAYS):
compat = self._check_resume_config_compatibility()
if resume == ResumeMode.ALWAYS and compat == _ConfigCompatibility.INCOMPATIBLE:
raise DatasetGenerationError(
"🛑 Cannot resume: the current config does not match the config used in the interrupted run. "
"Use resume=ResumeMode.IF_POSSIBLE to start fresh automatically, or "
"resume=ResumeMode.NEVER to force a new run."
)
if resume == ResumeMode.IF_POSSIBLE:
if compat != _ConfigCompatibility.COMPATIBLE:
if compat == _ConfigCompatibility.INCOMPATIBLE:
logger.info(
"▶️ Config has changed since the last run — starting a fresh generation (resume=IF_POSSIBLE)."
)
resume = ResumeMode.NEVER
self.artifact_storage.resume = ResumeMode.NEVER
self.artifact_storage.__dict__.pop("resolved_dataset_name", None)
self.artifact_storage.refresh_media_storage_path()
else:
resume = ResumeMode.ALWAYS
self.artifact_storage.resume = ResumeMode.ALWAYS
self.artifact_storage.__dict__.pop("resolved_dataset_name", None)
self._set_metadata_defaults()
if self._post_generation_processed_resume_result(resume, num_records) is not None:
return self.artifact_storage.final_dataset_path
self._write_builder_config()
# Set media storage mode based on parameters
if self._has_image_columns():
mode = StorageMode.DISK if save_multimedia_to_disk else StorageMode.DATAFRAME
self.artifact_storage.set_media_storage_mode(mode)
generators, self._graph = self._initialize_generators_and_graph()
start_time = time.perf_counter()
buffer_size = self._resource_provider.run_config.buffer_size
if resume == ResumeMode.ALWAYS and not self.artifact_storage.metadata_file_path.exists():
# No metadata.json means the previous run was interrupted before any batch (sync) or
# row group (async) completed. Nothing to resume — discard any leftover partial
# results and start fresh.
logger.info(
"▶️ No metadata.json found — the previous run was interrupted before any batch "
"completed. Starting generation from the beginning."
)
self.artifact_storage.clear_partial_results()
resume = ResumeMode.NEVER
self.artifact_storage.resume = ResumeMode.NEVER
if resume == ResumeMode.ALWAYS and self._has_allow_resize_columns():
raise DatasetGenerationError(
"🛑 Cannot resume when any column has allow_resize=True. Resized batches change row boundaries, "
"so the original batch plan cannot be reconstructed safely. Use resume=ResumeMode.NEVER to "
"start a new generation run."
)
self._use_async = DATA_DESIGNER_ASYNC_ENGINE and self._resolve_async_compatibility()
if self._use_async:
self._build_async(generators, num_records, buffer_size, on_batch_complete, resume=resume)
elif resume == ResumeMode.ALWAYS:
self._build_with_resume(generators, num_records, buffer_size, on_batch_complete)
else:
group_id = uuid.uuid4().hex
self.batch_manager.start(num_records=num_records, buffer_size=buffer_size)
for batch_idx in range(self.batch_manager.num_batches):
logger.info(f"⏳ Processing batch {batch_idx + 1} of {self.batch_manager.num_batches}")
self._run_batch(
generators,
batch_mode="batch",
group_id=group_id,
current_batch_number=batch_idx,
on_batch_complete=on_batch_complete,
)
self.batch_manager.finish()
# After-generation processors run unconditionally on the on-disk dataset
# (not gated on ``generated``). When resume sees every row group already
# on disk, ``_build_*`` returns ``False`` without writing the "started"
# marker; gating after-generation on ``generated`` would then leave a
# complete dataset with after-generation processors permanently unrun if
# the original process crashed in the narrow window between the final
# parquet write and the "started" marker write.
#
# The short-circuits inside ``_post_generation_processed_resume_result``
# cover the already-processed cases (``post_generation_processed`` /
# ``post_generation_state == "complete"`` → return early;
# ``post_generation_state == "started"`` → raise as ambiguous), so by
# the time we reach this point after-generation has demonstrably not
# been applied to the dataset on disk.
has_after_generation_processors = self._processor_runner.has_processors_for(ProcessorStage.AFTER_GENERATION)
if has_after_generation_processors:
self.artifact_storage.update_metadata(
{"post_generation_state": "started", "post_generation_processed": False}
)
self._processor_runner.run_after_generation(buffer_size)
self.artifact_storage.update_metadata(
{"post_generation_state": "complete", "post_generation_processed": True}
)
self._resource_provider.model_registry.log_model_usage(time.perf_counter() - start_time)
return self.artifact_storage.final_dataset_path
def _set_metadata_defaults(self) -> None:
"""Attach config identity fields to every metadata write in this build."""
self.artifact_storage.set_metadata_defaults(self._data_designer_config.fingerprint())
def _has_allow_resize_columns(self) -> bool:
return any(getattr(config, "allow_resize", False) for config in self.single_column_configs)
def _post_generation_processed_resume_result(self, resume: ResumeMode, num_records: int) -> Path | None:
"""Decide whether to short-circuit resume based on after-generation processor state.
Returns:
* ``None`` if normal resume should proceed (no metadata, not in resume mode, or
after-generation processors have not run yet).
* ``final_dataset_path`` for the no-op case (dataset is already complete and
post-processed and the caller asked for the same target).
Raises:
DatasetGenerationError: If after-generation processing started but did not
complete (parquet files may already be rewritten), if the terminal
metadata is missing required fields (``target_num_records``), or if the
caller asked for a different target than the one this terminal dataset
was built for.
"""
if resume != ResumeMode.ALWAYS or not self.artifact_storage.metadata_file_path.exists():
return None
try:
metadata = self.artifact_storage.read_metadata()
except (FileNotFoundError, json.JSONDecodeError):
return None
post_generation_state = metadata.get("post_generation_state")
if post_generation_state == "started":
raise DatasetGenerationError(
"🛑 Cannot resume: process_after_generation started but did not complete for this dataset. "
"The final parquet files may already have been rewritten, so resuming would risk mixing pre- "
"and post-processor records. Use resume=ResumeMode.NEVER to start a new generation run."
)
if not metadata.get("post_generation_processed", False) and post_generation_state != "complete":
return None
prior_target = metadata.get("target_num_records")
if prior_target is None:
raise DatasetGenerationError(
"🛑 Cannot resume: metadata.json is missing required field 'target_num_records'. "
"Start a fresh run with resume=ResumeMode.NEVER, or restore a valid metadata.json."
)
if num_records == prior_target:
logger.warning("▶️ Dataset is already complete and post-processed; nothing to resume.")
return self.artifact_storage.final_dataset_path
if num_records < prior_target:
raise DatasetGenerationError(
f"🛑 Cannot resume: num_records={num_records} is less than the {prior_target} records "
"already generated and post-processed for this dataset. Use num_records >= "
f"{prior_target}, or resume=ResumeMode.NEVER to start a new generation run."
)
raise DatasetGenerationError(
"🛑 Cannot resume: process_after_generation has already been applied to this dataset "
f"(original target {prior_target}, requested {num_records}). Extending would mix pre- and "
"post-processor records. Use resume=ResumeMode.NEVER to start a new generation run."
)
def _load_resume_state(self, num_records: int, buffer_size: int) -> _ResumeState:
"""Read and validate resume state from metadata + the filesystem.
``metadata.json`` is the source of truth for the run *configuration*
(``buffer_size``, ``target_num_records``, ``original_target_num_records``,
config fingerprint). The filesystem (``parquet-files/batch_*.parquet``) is
the source of truth for run *progress* (``num_completed_batches``,
``actual_num_records``). Splitting the two sources is what lets resume
survive a crash between writing a batch and updating metadata: the
filesystem reflects the durable state even when metadata lags by a step.
``num_records`` must be >= the number of records already on disk (you may
extend a dataset, but cannot shrink it below what has been written).
``buffer_size`` must match the original run because it determines row-group
boundaries. The sync engine additionally requires contiguous batch IDs;
the async engine tolerates holes from out-of-order completion.
Raises:
DatasetGenerationError: If metadata is missing or incompatible, or if
the filesystem state is inconsistent with the engine in use.
"""
try:
metadata = self.artifact_storage.read_metadata()
except FileNotFoundError as exc:
raise DatasetGenerationError(
"🛑 Cannot resume: metadata.json not found in the existing dataset directory. "
"Run without resume=ResumeMode.ALWAYS to start a new generation."
) from exc
except json.JSONDecodeError as exc:
raise DatasetGenerationError(
"🛑 Cannot resume: metadata.json is corrupt or partially written. "
"Start a fresh run with resume=ResumeMode.NEVER, or restore a valid metadata.json."
) from exc
num_completed_batches, actual_num_records, completed_row_groups = self._recover_progress_from_disk(
allow_holes=self._use_async,
)
if num_records < actual_num_records:
raise DatasetGenerationError(
f"🛑 Cannot resume: num_records={num_records} is less than the {actual_num_records} "
"records already generated. Use num_records >= actual_num_records, "
"or start a new run without resume=ResumeMode.ALWAYS."
)
target_num_records = metadata.get("target_num_records")
if target_num_records is None:
raise DatasetGenerationError(
"🛑 Cannot resume: metadata.json is missing required field 'target_num_records'. "
"Start a fresh run with resume=ResumeMode.NEVER, or restore a valid metadata.json."
)
if num_records < target_num_records:
raise DatasetGenerationError(
f"🛑 Cannot resume: num_records={num_records} is less than the original target "
f"({target_num_records}). To resume, use num_records >= {target_num_records} "
"(you may extend the dataset beyond the original target). "
"Use resume=ResumeMode.NEVER to start a new run."
)
meta_buffer_size = metadata.get("buffer_size")
if meta_buffer_size != buffer_size:
raise DatasetGenerationError(
f"🛑 Cannot resume: buffer_size={buffer_size} does not match the original run's "
f"buffer_size={meta_buffer_size}. Use the same buffer_size as the interrupted run, "
"or start a new run without resume=ResumeMode.ALWAYS."
)
return _ResumeState(
num_completed_batches=num_completed_batches,
actual_num_records=actual_num_records,
buffer_size=buffer_size,
target_num_records=target_num_records,
original_target_num_records=metadata.get("original_target_num_records", target_num_records),
completed_row_groups=completed_row_groups,
)
def _build_with_resume(
self,
generators: list[ColumnGenerator],
num_records: int,
buffer_size: int,
on_batch_complete: Callable[[Path], None] | None,
) -> bool:
"""Resume generation from the last completed batch.
Returns:
False if the dataset was already complete (no new records generated),
True after successfully generating the remaining batches.
"""
state = self._load_resume_state(num_records, buffer_size)
# Compute the correct per-batch sizes. ceil(num_records/bs) is wrong for a
# non-aligned extension: original groups are immutable, so any extension always
# adds new groups beyond num_original_batches.
original_target = state.original_target_num_records
num_original_batches = -(-original_target // buffer_size)
extension_records = num_records - original_target
num_extension_batches = -(-extension_records // buffer_size)
original_sizes = [min(buffer_size, original_target - i * buffer_size) for i in range(num_original_batches)]
extension_sizes = [min(buffer_size, extension_records - i * buffer_size) for i in range(num_extension_batches)]
self.batch_manager.start(
num_records=num_records,
buffer_size=buffer_size,
start_batch=state.num_completed_batches,
initial_actual_num_records=state.actual_num_records,
num_records_list=original_sizes + extension_sizes,
original_target_num_records=original_target,
)
if state.num_completed_batches >= self.batch_manager.num_batches:
logger.warning(
"⚠️ Dataset is already complete — all batches were found in the existing artifact directory. "
"Nothing to resume. Use resume=ResumeMode.NEVER if you want to generate a new dataset."
)
return False
logger.info(
f"▶️ Resuming from batch {state.num_completed_batches + 1} of {self.batch_manager.num_batches} "
f"({state.actual_num_records} records already generated)."
)
self.artifact_storage.clear_partial_results()
group_id = uuid.uuid4().hex
for batch_idx in range(state.num_completed_batches, self.batch_manager.num_batches):
logger.info(f"⏳ Processing batch {batch_idx + 1} of {self.batch_manager.num_batches}")
self._run_batch(
generators,
batch_mode="batch",
group_id=group_id,
current_batch_number=batch_idx,
on_batch_complete=on_batch_complete,
)
self.batch_manager.finish()
return True
def build_preview(self, *, num_records: int) -> pd.DataFrame:
self._reset_run_state()
self._run_model_health_check_if_needed()
self._run_mcp_tool_check_if_needed()
# Set media storage to DATAFRAME mode for preview - base64 stored directly in DataFrame
if self._has_image_columns():
self.artifact_storage.set_media_storage_mode(StorageMode.DATAFRAME)
generators, self._graph = self._initialize_generators_and_graph()
start_time = time.perf_counter()
self._use_async = DATA_DESIGNER_ASYNC_ENGINE and self._resolve_async_compatibility()
if self._use_async:
dataset = self._build_async_preview(generators, num_records)
else:
group_id = uuid.uuid4().hex
self.batch_manager.start(num_records=num_records, buffer_size=num_records)
self._run_batch(generators, batch_mode="preview", save_partial_results=False, group_id=group_id)
dataset = self.batch_manager.get_current_batch(as_dataframe=True)
self.batch_manager.reset()
self._resource_provider.model_registry.log_model_usage(time.perf_counter() - start_time)
return dataset
def _reset_run_state(self) -> None:
"""Clear per-run signals so reused builder instances don't leak state across runs."""
self._early_shutdown = False
self._partial_row_groups = ()
self._actual_num_records = -1
self._first_non_retryable_error = None
self._task_traces = []
def _build_async_preview(self, generators: list[ColumnGenerator], num_records: int) -> pd.DataFrame:
"""Async preview path - single row group, no disk writes, returns in-memory DataFrame."""
logger.info("⚡ DATA_DESIGNER_ASYNC_ENGINE is enabled - using async task-queue preview")
settings = self._resource_provider.run_config
trace_enabled = _is_async_trace_enabled(settings)
scheduler, buffer_manager = self._prepare_async_run(
generators,
num_records,
buffer_size=num_records,
run_post_batch_in_scheduler=False,
trace=trace_enabled,
)
loop = ensure_async_engine_loop()
future = asyncio.run_coroutine_threadsafe(scheduler.run(), loop)
try:
future.result()
finally:
self._task_traces = scheduler.traces
self._early_shutdown = scheduler.early_shutdown
self._partial_row_groups = scheduler.partial_row_groups
self._actual_num_records = buffer_manager.actual_num_records
self._first_non_retryable_error = scheduler.first_non_retryable_error
if not buffer_manager.has_row_group(0):
return lazy.pd.DataFrame()
dataset = buffer_manager.get_dataframe(0)
buffer_manager.free_row_group(0)
return dataset
def _resolve_async_compatibility(self) -> bool:
"""Check if the async engine can be used; auto-fallback to sync if not.
Returns True if async is usable, False if allow_resize forces sync fallback.
"""
offending = [config.name for config in self.single_column_configs if getattr(config, "allow_resize", False)]
if offending:
msg = (
f"allow_resize=True detected on column(s) {offending}. "
"Falling back to sync engine for this run. "
"allow_resize is deprecated and will be removed in a future release; "
"use workflow chaining instead (see issue #552)."
)
logger.warning(f"⚠️ {msg}")
# ``warn_at_caller`` rather than ``warnings.warn(stacklevel=N)`` so
# attribution lands on the user's call site instead of an internal
# ``DatasetBuilder.build`` / ``data_designer.interface`` frame.
# The exact internal-frame depth from this method up to user code
# depends on which entry point invoked the builder (build vs.
# build_preview, sync vs. async wrapping), so a hard-coded
# ``stacklevel`` is brittle; ``warn_at_caller`` walks past every
# ``data_designer.*`` frame regardless of chain shape. Library
# attribution would also be silenced under Python's default
# ``ignore::DeprecationWarning`` filter. See PR #594 review.
warn_at_caller(msg, DeprecationWarning)
return False
return True
def _find_completed_row_groups(self) -> dict[int, int]:
"""Scan final parquet files and return row-group IDs with persisted row counts.
Returns:
Mapping of row-group ID (batch number) to actual parquet row count.
"""
final_path = self.artifact_storage.final_dataset_path
if not final_path.exists():
return {}
row_groups: dict[int, int] = {}
for p in final_path.glob("batch_*.parquet"):
try:
row_group_id = int(p.stem.split("_", 1)[1])
row_groups[row_group_id] = lazy.pq.read_metadata(p).num_rows
except (ValueError, IndexError, OSError):
logger.warning("⚠️ Ignoring unreadable row-group file during resume: %s", p)
continue
return row_groups
def _recover_progress_from_disk(self, *, allow_holes: bool) -> tuple[int, int, dict[int, int]]:
"""Derive resume progress counters from completed parquet files on disk.
The filesystem is the source of truth for ``num_completed_batches`` and
``actual_num_records`` because a crash between
``move_partial_result_to_final_file_path`` and the metadata write that follows
can leave parquet files on disk while metadata still reports stale counters.
Both engines use the same scan so resume semantics stay consistent.
Args:
allow_holes: ``True`` for the async engine, which schedules row groups
concurrently and may complete them out of order. ``False`` for the sync
engine, which writes batches sequentially — a non-contiguous set of IDs
indicates external mutation or a directory written by an incompatible
engine and is rejected with ``DatasetGenerationError``.
Returns:
``(num_completed_batches, actual_num_records, completed_row_groups)``.
"""
completed_row_groups = self._find_completed_row_groups()
if completed_row_groups and not allow_holes:
ids = sorted(completed_row_groups)
if ids != list(range(len(ids))):
raise DatasetGenerationError(
"🛑 Cannot resume: completed batch files on disk are non-contiguous "
f"(found row group IDs {ids}). The dataset directory may have been "
"written by an incompatible engine or modified externally. Use "
"resume=ResumeMode.NEVER to start a new run."
)
return len(completed_row_groups), sum(completed_row_groups.values()), completed_row_groups
def _check_resume_config_compatibility(self) -> _ConfigCompatibility:
"""Compare the current config fingerprint against stored resume identity.
Returns:
NO_PRIOR_DATASET — directory absent or empty (no prior run to resume from).
COMPATIBLE — fingerprints match.
INCOMPATIBLE — fingerprints differ; continuing would mix records from two configs.
Uses artifact_path / dataset_name directly — NOT base_dataset_path — to avoid
prematurely triggering the resolved_dataset_name cached_property before the
caller has had a chance to decide whether to resume or start fresh.
"""
dataset_dir = Path(self.artifact_storage.artifact_path) / self.artifact_storage.dataset_name
if not dataset_dir.exists() or not any(dataset_dir.iterdir()):
return _ConfigCompatibility.NO_PRIOR_DATASET
current_fp = self._data_designer_config.fingerprint()
metadata_path = dataset_dir / METADATA_FILENAME
if metadata_path.exists():
try:
metadata = json.loads(metadata_path.read_text())
except json.JSONDecodeError as exc:
raise DatasetGenerationError(
"🛑 Cannot resume: metadata.json is corrupt or partially written. "
"Start a fresh run with resume=ResumeMode.NEVER, or restore a valid metadata.json."
) from exc
except OSError:
logger.warning(
"⚠️ Could not read metadata at %s for config compatibility check — treating as incompatible.",
metadata_path,
)
return _ConfigCompatibility.INCOMPATIBLE
stored_hash = metadata.get("config_hash")
stored_version = metadata.get("config_hash_version")
if stored_hash is not None:
if stored_version != current_fp["config_hash_version"]:
logger.warning(
"⚠️ Stored config_hash_version=%s does not match current version=%s.",
stored_version,
current_fp["config_hash_version"],
)
return _ConfigCompatibility.INCOMPATIBLE
return (
_ConfigCompatibility.COMPATIBLE
if stored_hash == current_fp["config_hash"]
else _ConfigCompatibility.INCOMPATIBLE
)
config_path = dataset_dir / SDG_CONFIG_FILENAME
if not config_path.exists():
logger.warning(
"⚠️ No builder_config.json found in %s — skipping config compatibility check on resume.",
dataset_dir,
)
return _ConfigCompatibility.COMPATIBLE
try:
stored_data = json.loads(config_path.read_text())
stored_config = BuilderConfig.model_validate(stored_data)
stored_fp = stored_config.data_designer.fingerprint()["config_hash"]
return (
_ConfigCompatibility.COMPATIBLE
if current_fp["config_hash"] == stored_fp
else _ConfigCompatibility.INCOMPATIBLE
)
except (OSError, json.JSONDecodeError, ValidationError):
logger.warning(
"⚠️ Could not read stored config at %s for compatibility check — assuming compatible.",
config_path,
)
return _ConfigCompatibility.COMPATIBLE
def _build_async(
self,
generators: list[ColumnGenerator],
num_records: int,
buffer_size: int,
on_batch_complete: Callable[[Path], None] | None = None,
*,
resume: ResumeMode = ResumeMode.NEVER,
) -> bool:
"""Async task-queue builder path - dispatches tasks based on dependency readiness.
Returns:
False if the dataset was already complete (no new records generated),
True after successfully running the scheduler.
"""
logger.info("⚡ DATA_DESIGNER_ASYNC_ENGINE is enabled - using async task-queue builder")
settings = self._resource_provider.run_config
trace_enabled = _is_async_trace_enabled(settings)
precomputed_row_groups: list[tuple[int, int]] | None = None
initial_actual_num_records = 0
initial_total_num_batches = 0
original_target = num_records # immutable original target; overridden on resume
if resume == ResumeMode.ALWAYS:
state = self._load_resume_state(num_records, buffer_size)
# _load_resume_state already scans the filesystem for completed row groups
# and exposes them via state.completed_row_groups. The filesystem is the
# source of truth for progress (metadata may lag by one row group between
# move_partial_result_to_final_file_path and write_metadata).
completed_row_groups = state.completed_row_groups
completed_ids = set(completed_row_groups)
initial_total_num_batches = state.num_completed_batches
initial_actual_num_records = state.actual_num_records
# Use the original target (not the new num_records) so the last row group of a
# non-aligned run gets its true size, not buffer_size.
original_target = state.original_target_num_records
num_original_groups = -(-original_target // buffer_size) # ceil(original_target/buffer_size)
def _rg_size(rg_id: int) -> int:
if rg_id < num_original_groups:
return min(buffer_size, original_target - rg_id * buffer_size)
ext_group_idx = rg_id - num_original_groups
return min(buffer_size, (num_records - original_target) - ext_group_idx * buffer_size)
self.artifact_storage.clear_partial_results()
# Original groups are immutable; any extension always needs new groups beyond
# num_original_groups — ceil(num_records/bs) gives the wrong count when the
# original run was non-aligned and the extension fits in the last group's slack.
extension_records = num_records - original_target
total_row_groups = num_original_groups + -(-extension_records // buffer_size)
if len(completed_ids) >= total_row_groups:
logger.warning(
"⚠️ Dataset is already complete — all row groups were found in the existing artifact "
"directory. Nothing to resume. Use resume=ResumeMode.NEVER if you want to generate a new dataset."
)
return False
logger.info(
f"▶️ Resuming async run: {len(completed_ids)} of {total_row_groups} row group(s) already "
f"complete ({initial_actual_num_records} records), skipping them."
)
# Pre-compute the full row-group list with correct per-group sizes so that
# non-aligned skipped groups deduct their actual on-disk record count rather
# than buffer_size, keeping extension group sizes accurate.
precomputed_row_groups = [
(rg_id, _rg_size(rg_id)) for rg_id in range(total_row_groups) if rg_id not in completed_ids
]
def finalize_row_group(rg_id: int) -> None:
def on_complete(final_path: Path | str | None) -> None:
if final_path is not None and on_batch_complete:
on_batch_complete(final_path)
buffer_manager.checkpoint_row_group(rg_id, on_complete=on_complete)
# Write incremental metadata after each row group so interrupted runs can be resumed.
buffer_manager.write_metadata(
target_num_records=num_records,
original_target_num_records=original_target,
buffer_size=buffer_size,
)
scheduler, buffer_manager = self._prepare_async_run(
generators,
num_records,
buffer_size,
on_finalize_row_group=finalize_row_group,
shutdown_error_rate=settings.shutdown_error_rate,
shutdown_error_window=settings.shutdown_error_window,
disable_early_shutdown=settings.disable_early_shutdown,
trace=trace_enabled,
precomputed_row_groups=precomputed_row_groups,
initial_actual_num_records=initial_actual_num_records,
initial_total_num_batches=initial_total_num_batches,
)
# Telemetry snapshot
group_id = uuid.uuid4().hex
pre_batch_snapshot = self._resource_provider.model_registry.get_model_usage_snapshot()
# Run on background event loop. Capture scheduler state in `finally`
# so the structured signal is preserved even if `scheduler.run()`
# raises during the salvage path - otherwise callers see a generic
# error and lose the early-shutdown context.
loop = ensure_async_engine_loop()
future = asyncio.run_coroutine_threadsafe(scheduler.run(), loop)
try:
future.result()
finally:
self._task_traces = scheduler.traces
self._early_shutdown = scheduler.early_shutdown
self._partial_row_groups = scheduler.partial_row_groups
self._actual_num_records = buffer_manager.actual_num_records
self._first_non_retryable_error = scheduler.first_non_retryable_error
# Emit telemetry
try:
usage_deltas = self._resource_provider.model_registry.get_usage_deltas(pre_batch_snapshot)
self._emit_batch_inference_events("batch", usage_deltas, group_id)
except Exception:
logger.debug("Failed to emit batch telemetry for async run", exc_info=True)
# Write final metadata (overwrites the last incremental write with identical content).
buffer_manager.write_metadata(
target_num_records=num_records,
original_target_num_records=original_target,
buffer_size=buffer_size,
)
# Surface partial completion
actual = self._actual_num_records
if actual < num_records:
pct = actual / num_records * 100 if num_records > 0 else 0
base = f"⚠️ Generated {actual} of {num_records} requested records ({pct:.0f}%). "
if scheduler.early_shutdown:
partial = scheduler.partial_row_groups
detail = (
f"Early shutdown was triggered (non-retryable error rate exceeded threshold); "
f"{len(partial)} row group(s) salvaged with partial rows."
if partial
else "Early shutdown was triggered (non-retryable error rate exceeded threshold)."
)
logger.warning(base + detail)
else:
logger.warning(base + "The dataset may be incomplete due to dropped rows.")
return True
def _prepare_async_run(
self,
generators: list[ColumnGenerator],
num_records: int,
buffer_size: int,
*,
on_finalize_row_group: Callable[[int], None] | None = None,
run_post_batch_in_scheduler: bool = True,
shutdown_error_rate: float = 0.5,
shutdown_error_window: int = 10,
disable_early_shutdown: bool = False,
trace: bool = False,
precomputed_row_groups: list[tuple[int, int]] | None = None,
initial_actual_num_records: int = 0,
initial_total_num_batches: int = 0,
) -> tuple[AsyncTaskScheduler, RowGroupBufferManager]:
"""Build a fully-wired scheduler and buffer manager for async generation.
Shared setup for both build and preview paths. Processor hooks are always
wired when the config has processors, so callers cannot accidentally omit them.
"""
strategies: dict[str, GenerationStrategy] = {}
gen_map: dict[str, ColumnGenerator] = {}
for gen in generators:
if isinstance(gen.config, MultiColumnConfig):
for sub in gen.config.columns:
strategies[sub.name] = gen.get_generation_strategy()
gen_map[sub.name] = gen
else:
strategies[gen.config.name] = gen.get_generation_strategy()
gen_map[gen.config.name] = gen
graph = ExecutionGraph.create(self._column_configs, strategies)
for gen in generators:
gen.log_pre_generation()
if precomputed_row_groups is not None:
row_groups = precomputed_row_groups
else:
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)
buffer_manager = RowGroupBufferManager(
self.artifact_storage,
initial_actual_num_records=initial_actual_num_records,
initial_total_num_batches=initial_total_num_batches,
)
# Pre-batch processor callback: runs after seed tasks complete for a row group.
# If it raises, the scheduler propagates the error as DatasetGenerationError (fail-fast).
def on_seeds_complete(rg_id: int, rg_size: int) -> FrontierDelta:
df = buffer_manager.get_dataframe(rg_id)