Skip to content

Orchestration

RetryHandler is shared infrastructure in datacoolie.utils.retry; it is documented below but is no longer exported from datacoolie.orchestration.

driver

Main ETL driver coordinating all framework components.

DataCoolieDriver ties together metadata, watermark, engine, platform, loggers, job distribution, parallel execution, and retry handling through constructor injection.

Typical usage::

driver = create_driver(
    engine=spark_engine,
    platform=local_platform,
    metadata_provider=file_provider,
    job_num=4, job_index=0, max_workers=4,
)
result = driver.run(stage="bronze2silver")

DataCoolieDriver

DataCoolieDriver(
    engine: BaseEngine,
    platform: Optional[BasePlatform] = None,
    metadata_provider: Optional[
        BaseMetadataProvider
    ] = None,
    watermark_manager: Optional[
        BaseWatermarkManager
    ] = None,
    config: Optional[DataCoolieRunConfig] = None,
    secret_provider: Optional[BaseSecretProvider] = None,
    system_logger: Optional[SystemLogger] = None,
    execution_logger: Optional[ExecutionLogger] = None,
    artifact_base_path: Optional[str] = None,
    state_base_path: Optional[str] = None,
    metadata_base_path: Optional[str] = None,
    sql_base_path: str | Sequence[str] | None = None,
    log_base_path: Optional[str] = None,
    log_config: Optional[LogConfig] = None,
)

Main orchestration class for DataCoolie ETL pipelines.

Uses constructor injection for all dependencies. Supports:

  • ETL mode — read → transform → write with run or run_dataflow function.
  • Maintenance mode — optimize + vacuum on destinations with run_maintenance function.
  • Dry-run — logs planned work without side effects.
  • Context manager (with) for resource cleanup.

Parameters:

Name Type Description Default
engine BaseEngine

Data operation engine (e.g. PySpark).

required
platform Optional[BasePlatform]

Platform abstraction for file I/O.

None
metadata_provider Optional[BaseMetadataProvider]

Provides dataflow / connection metadata.

None
metadata_base_path Optional[str]

Optional metadata directory for an automatically created :class:~datacoolie.metadata.file_provider.FileProvider. When a provider is injected, the path is passed through the typed startup context so the provider can accept or reject it explicitly.

None
watermark_manager Optional[BaseWatermarkManager]

Reads and writes watermarks. When None and a metadata provider is resolved (injected or inferred), a :class:~datacoolie.watermark.watermark_manager.WatermarkManager is created automatically.

None
config Optional[DataCoolieRunConfig]

Execution parameters (includes job_id).

None
secret_provider Optional[BaseSecretProvider]

Resolves secrets in connection configs. If not provided, the resolved platform is used as the default provider.

None
system_logger Optional[SystemLogger]

Optional system-level logger.

None
execution_logger Optional[ExecutionLogger]

Optional structured execution logger.

None
artifact_base_path Optional[str]

Optional root for deployed metadata/SQL/artifacts. With no injected provider it also selects FileProvider artifact mode, whose metadata default is <artifact_base_path>/metadata. It remains available for relative SQL references when sql_base_path is absent and for explicit artifact:/ references.

None
state_base_path Optional[str]

Optional root for framework runtime state. It is used to derive logs and file-provider watermarks when their component-specific roots are absent.

None
sql_base_path str | Sequence[str] | None

Optional component root for relative SQL references. It takes precedence over artifact_base_path.

None
log_base_path Optional[str]

Base directory for auto-created loggers. When provided, SystemLogger and ExecutionLogger write under <log_base_path>/system_logs and <log_base_path>/execution_logs. Takes precedence over log_config.output_path.

None
log_config Optional[LogConfig]

Optional :class:LogConfig used as the template for auto-created loggers. If log_base_path is also given it overrides output_path; otherwise log_config.output_path is used as the base directory. All other persistence/capture fields are preserved.

None

close

close() -> None

Close driver and its accepted session loggers once.

load_dataflows

load_dataflows(
    stage: Optional[Union[str, List[str]]] = None,
    active_only: bool = True,
    attach_schema_hints: bool = True,
) -> List[DataFlow]

Load and filter dataflows for this Driver session.

load_maintenance_dataflows

load_maintenance_dataflows(
    connection: Optional[Union[str, List[str]]] = None,
    active_only: bool = True,
) -> List[DataFlow]

Load unique-destination dataflows eligible for maintenance.

run

run(
    stage: Optional[Union[str, List[str]]] = None,
    dataflows: Optional[List[DataFlow]] = None,
    column_name_mode: Union[ColumnCaseMode, str] = LOWER,
) -> ExecutionResult

Alias for :meth:run_dataflow.

run_dataflow

run_dataflow(
    stage: Optional[Union[str, List[str]]] = None,
    dataflows: Optional[List[DataFlow]] = None,
    column_name_mode: Union[ColumnCaseMode, str] = LOWER,
) -> ExecutionResult

Execute one admitted ETL operation.

run_maintenance

run_maintenance(
    connection: Optional[Union[str, List[str]]] = None,
    dataflows: Optional[List[DataFlow]] = None,
    do_compact: bool = True,
    do_cleanup: bool = True,
    *,
    compact_options=None,
    cleanup_options=None,
) -> ExecutionResult

Execute one admitted maintenance operation.

run_replay

run_replay(
    dataflows: Union[DataFlow, List[DataFlow]],
    replay: ReplayConfig,
    column_name_mode: Union[ColumnCaseMode, str] = LOWER,
) -> ExecutionResult

Execute one admitted replay operation.

factory

Convenience factory for constructing a configured DataCoolie Driver.

create_driver

create_driver(
    engine: BaseEngine,
    platform: Optional[BasePlatform] = None,
    metadata_provider: Optional[
        BaseMetadataProvider
    ] = None,
    watermark_manager: Optional[
        BaseWatermarkManager
    ] = None,
    job_id: Optional[str] = None,
    job_num: int = 1,
    job_index: int = 0,
    max_workers: int = DEFAULT_MAX_WORKERS,
    secret_provider: Optional[BaseSecretProvider] = None,
    system_logger: Optional[SystemLogger] = None,
    execution_logger: Optional[ExecutionLogger] = None,
    artifact_base_path: Optional[str] = None,
    state_base_path: Optional[str] = None,
    metadata_base_path: Optional[str] = None,
    sql_base_path: str | Sequence[str] | None = None,
    log_base_path: Optional[str] = None,
    log_config: Optional[LogConfig] = None,
    **kwargs: Any,
) -> DataCoolieDriver

Create a configured, provider-ready :class:DataCoolieDriver.

Metadata and artifact roots are forwarded unchanged to Driver, which owns provider inference, conflict validation, and cleanup for both construction entry points. sql_base_path remains the Driver session fallback; provider-declared SQL roots are preferred when present and must agree with an explicitly supplied Driver value.

runtime

Run and attempt observations, independent of pipeline control state.

ExecutionMetrics dataclass

ExecutionMetrics(
    rows_read: MetricValue = None,
    rows_written: MetricValue = None,
    rows_inserted: MetricValue = None,
    rows_updated: MetricValue = None,
    rows_deleted: MetricValue = None,
    files_added: MetricValue = None,
    files_removed: MetricValue = None,
    bytes_added: MetricValue = None,
    bytes_removed: MetricValue = None,
    bytes_saved: MetricValue = None,
)

Nullable execution measurements at one attempt or aggregate grain.

from_attempt classmethod

from_attempt(attempt: Any | None) -> 'ExecutionMetrics'

Project one attempt without treating an absent phase as zero.

sum classmethod

sum(
    metrics: Iterable["ExecutionMetrics"],
) -> "ExecutionMetrics"

Sum observed values independently, preserving unobserved fields.

AttemptRuntimeInfo dataclass

AttemptRuntimeInfo(
    start_time: datetime = utc_now(),
    end_time: Optional[datetime] = None,
    status: str = PENDING.value,
    message: Optional[str] = None,
    attempt_number: int = 1,
    source: Optional[SourceRuntimeInfo] = None,
    transform: Optional[TransformRuntimeInfo] = None,
    destination: Optional[DestinationRuntimeInfo] = None,
    watermark: Optional[WatermarkRuntimeInfo] = None,
)

Bases: RuntimeInfo

DataFlowRuntimeInfo dataclass

DataFlowRuntimeInfo(
    start_time: datetime = utc_now(),
    end_time: Optional[datetime] = None,
    status: str = PENDING.value,
    message: Optional[str] = None,
    dataflow_run_id: str = generate_unique_id(),
    dataflow_id: Optional[str] = None,
    operation_type: Optional[str] = None,
    read_request: Optional[SourceReadRequest] = None,
    attempts: list[AttemptRuntimeInfo] = list(),
)

Bases: RuntimeInfo

ReplayRuntimeInfo dataclass

ReplayRuntimeInfo(
    start_time: datetime = utc_now(),
    end_time: Optional[datetime] = None,
    status: str = PENDING.value,
    message: Optional[str] = None,
    dataflow_run_id: str = generate_unique_id(),
    dataflow_id: Optional[str] = None,
    operation_type: Optional[str] = None,
    chunk_run_ids: list[str] = list(),
    metrics: ExecutionMetrics = ExecutionMetrics(),
    retry_attempts: int = 0,
)

Bases: RuntimeInfo

runtime

Job-level observations and nullable ingestion totals.

JobRuntimeInfo dataclass

JobRuntimeInfo(
    start_time: datetime = utc_now(),
    end_time: Optional[datetime] = None,
    status: str = PENDING.value,
    message: Optional[str] = None,
    job_id: str = generate_unique_id(),
    job_num: int = 1,
    job_index: int = 0,
    workspace_id: Optional[str] = None,
    stages: Optional[str | list[str]] = None,
    engine_name: Optional[str] = None,
    platform_name: Optional[str] = None,
    metadata_provider_name: Optional[str] = None,
    watermark_manager_name: Optional[str] = None,
    max_workers: int = DEFAULT_MAX_WORKERS,
    stop_on_error: bool = False,
    retry_count: int = DEFAULT_RETRY_COUNT,
    retry_delay: float = DEFAULT_RETRY_DELAY,
    dry_run: bool = False,
    retention_hours: int = DEFAULT_RETENTION_HOURS,
    run_attributes: Optional[str] = None,
    log_records_dropped: int = 0,
    log_bytes_dropped: int = 0,
    message_truncated: bool = False,
    total_dataflows: int = 0,
    total_succeeded: int = 0,
    total_failed: int = 0,
    total_skipped: int = 0,
    total_running: Optional[int] = None,
    total_pending: Optional[int] = None,
    total_rows_read: Optional[int] = None,
    total_rows_written: Optional[int] = None,
    total_rows_inserted: Optional[int] = None,
    total_rows_updated: Optional[int] = None,
    total_rows_deleted: Optional[int] = None,
    total_files_added: Optional[int] = None,
    total_files_removed: Optional[int] = None,
    total_bytes_added: Optional[int] = None,
    total_bytes_removed: Optional[int] = None,
    operation_types: Optional[str | list[str]] = None,
)

Bases: RuntimeInfo

Driver transformer hook

Driver subclasses that need to alter the registered transformer pipeline can override the following narrow hook. Preserve both arguments when delegating to the base implementation so the run-specific identifier and configured column-name mode reach the pipeline.

_create_transformer_pipeline

_create_transformer_pipeline(
    dataflow_run_id: Optional[str] = None,
    column_name_mode: ColumnCaseMode = LOWER,
) -> TransformerPipeline

Create the default registered transformer pipeline.

job_distributor

Job distribution logic for parallel execution of dataflows.

JobDistributor assigns dataflows to jobs using either hash-based or group-based distribution, and groups them for sequential execution within a group.

Distribution rules
  • group_number is not None → group_number % job_num == job_index
  • group_number is None → int(MD5(dataflow_id), 16) % job_num == job_index

Within a group, dataflows are sorted by execution_order.

JobDistributor

JobDistributor(job_num: int = 1, job_index: int = 0)

Distribute dataflows across parallel jobs.

Example::

distributor = JobDistributor(job_num=4, job_index=0)
my_dataflows = distributor.filter_dataflows(all_dataflows)
groups = distributor.group_dataflows(my_dataflows)

filter_dataflows

filter_dataflows(
    dataflows: List[DataFlow], active_only: bool = True
) -> List[DataFlow]

Return the subset of dataflows assigned to this job.

Parameters:

Name Type Description Default
dataflows List[DataFlow]

All available dataflows.

required
active_only bool

Skip inactive dataflows.

True

Returns:

Type Description
List[DataFlow]

Filtered list of dataflows for this job.

get_grouped_dataflows

get_grouped_dataflows(
    dataflows: List[DataFlow],
) -> Dict[int, List[DataFlow]]

Return only grouped dataflows (group_number is not None).

Returns:

Type Description
Dict[int, List[DataFlow]]

Mapping of group_number → sorted list of dataflows.

get_independent_dataflows

get_independent_dataflows(
    dataflows: List[DataFlow],
) -> List[DataFlow]

Return dataflows with no group (group_number is None).

group_dataflows

group_dataflows(
    dataflows: List[DataFlow],
) -> Dict[Optional[int], List[DataFlow]]

Group dataflows by group_number, sorted by execution_order.

Dataflows with group_number = None are placed under the None key and can run independently in parallel.

Returns:

Type Description
Dict[Optional[int], List[DataFlow]]

Mapping of group_number → sorted list of dataflows.

should_process

should_process(dataflow: DataFlow) -> bool

Check whether this job should process the given dataflow.

Uses group_number when set, otherwise hash-based distribution.

parallel_executor

Bounded orchestration scheduler for dataflow operations.

The executor owns admission, ordering and result accounting. Pipeline code is kept outside this module and is supplied through process_fn. A single coordinator pool is used for normal grouped execution so max_workers is a global limit for one executor invocation.

ExecutionResult dataclass

ExecutionResult(
    total: int = 0,
    succeeded: int = 0,
    failed: int = 0,
    skipped: int = 0,
    running: int = 0,
    pending: int = 0,
    errors: Dict[str, str] = dict(),
    duration_seconds: float = 0.0,
)

Aggregate result for one executor invocation.

pending means work that was never admitted. A result is counted once, when its process callable completes; observer callback failures do not mutate these counters.

ParallelExecutor

ParallelExecutor(
    max_workers: Optional[int] = None,
    stop_on_error: bool = False,
)

Execute dataflows with bounded global concurrency.

Independent items are ready immediately. Grouped items are released by ascending execution_order buckets; ties in one bucket may run in parallel. With stop_on_error enabled, no new item is admitted after a failed terminal result is observed, while already admitted work is drained.

execute

execute(
    dataflows: List[DataFlow],
    process_fn: Callable[
        [DataFlow], DataFlowRuntimeInfo | ReplayRuntimeInfo
    ],
    callback: Optional[
        Callable[
            [DataFlowRuntimeInfo | ReplayRuntimeInfo], None
        ]
    ] = None,
    *,
    operation_type: Optional[str] = None,
) -> ExecutionResult

Execute independent dataflows with one bounded worker pool.

execute_sequential

execute_sequential(
    dataflows: List[DataFlow],
    process_fn: Callable[
        [DataFlow], DataFlowRuntimeInfo | ReplayRuntimeInfo
    ],
    callback: Optional[
        Callable[
            [DataFlowRuntimeInfo | ReplayRuntimeInfo], None
        ]
    ] = None,
    *,
    operation_type: Optional[str] = None,
) -> ExecutionResult

Execute items in input order, optionally stopping after failure.

execute_with_groups

execute_with_groups(
    groups: Dict[Optional[int], List[DataFlow]],
    process_fn: Callable[
        [DataFlow], DataFlowRuntimeInfo | ReplayRuntimeInfo
    ],
    callback: Optional[
        Callable[
            [DataFlowRuntimeInfo | ReplayRuntimeInfo], None
        ]
    ] = None,
    *,
    operation_type: Optional[str] = None,
) -> ExecutionResult

Execute independent and ordered grouped dataflows.

Normal execution always uses the coordinator below, avoiding nested pools and preserving the global cap.

retry

Small dependency-free retry utility used by runtime components.

RetryHandler

RetryHandler(
    retry_count: int = 0,
    retry_delay: float = 5.0,
    backoff_multiplier: float = 2.0,
    max_delay: float = 60.0,
)

Retry a callable with bounded exponential backoff.

max_attempts property

max_attempts: int

Total attempts, including the initial call.

compute_delay

compute_delay(attempt: int) -> float

Return the delay before retry attempt (zero-based).

execute

execute(
    func: Callable[..., T],
    *args: Any,
    on_retry: Callable[[int, int, Exception, float], None]
    | None = None,
    **kwargs: Any,
) -> tuple[T, int]

Execute func, retrying failures up to the configured budget.

on_retry is an optional caller-owned observation hook. The retry utility itself deliberately does not log or emit framework events so metadata/database retries cannot accidentally appear as dataflow lifecycle events.

maintenance

Shared helpers for orchestration-layer concerns.

Lives next to :mod:driver, :mod:job_distributor, :mod:parallel_executor, and :mod:datacoolie.utils.retry. Hosts small, reusable utilities that coordinate work across dataflows without pulling logic into the driver or model layer.

dedupe_by_destination

dedupe_by_destination(
    dataflows: List[DataFlow],
    *,
    engine: BaseEngine | None = None,
) -> List[DataFlow]

Return blocked dataflows and one runnable flow per physical destination.

Multiple dataflows may target the same table or storage path (fan-in topology). When the unit of work is the destination itself — e.g. running OPTIMIZE / VACUUM — executing the same work more than once would race or waste compute. Input is sorted by dataflow_id first so "first-meet wins" is deterministic across runs regardless of metadata ordering.

Engine-aware maintenance requires qualified physical equality and fails before dispatch for invalid or unknown targets. Engine-free calls retain the legacy inspection behavior, including warn-and-skip errors.