Skip to content

Documentation for Execution class in DerivaML

Execution management for DerivaML.

Provides the Execution lifecycle, workflow tracking, hydra-zen configuration helpers (BaseConfig, notebook_config, run_notebook), and multirun support for running reproducible ML experiments with full provenance tracking.

AssetSpec

Bases: BaseModel

Specification for an asset in execution configurations.

Used to reference assets as inputs to executions, similar to how DatasetSpec is used for datasets. Supports optional checksum-based caching for large assets like model weights.

Attributes:

Name Type Description
rid RID

Resource Identifier of the asset.

asset_role Literal['Input', 'Output']

Role of the asset ("Input" or "Output"). Defaults to "Input". Literal-typed so a typo ("Imput") or case mismatch ("input") is rejected by Pydantic validation rather than silently flowing through to the catalog as a free-form string and either no-op'ing or failing on FK lookup. The two values match the Asset_Role controlled-vocabulary terms seeded by initialize_ml_schema.

cache bool

If True, cache the downloaded asset by MD5 checksum in the DerivaML cache directory. Cached assets are reused across executions when the checksum matches, avoiding repeated downloads of large files.

Example

spec = AssetSpec(rid="3JSE") spec = AssetSpec(rid="3JSE", cache=True) # enable caching spec = AssetSpec(rid="3JSE", asset_role="Output") # mark as output

Source code in src/deriva_ml/asset/aux_classes.py
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
class AssetSpec(BaseModel):
    """Specification for an asset in execution configurations.

    Used to reference assets as inputs to executions, similar to how
    DatasetSpec is used for datasets. Supports optional checksum-based
    caching for large assets like model weights.

    Attributes:
        rid: Resource Identifier of the asset.
        asset_role: Role of the asset (``"Input"`` or ``"Output"``).
            Defaults to ``"Input"``. ``Literal``-typed so a typo
            (``"Imput"``) or case mismatch (``"input"``) is
            rejected by Pydantic validation rather than silently
            flowing through to the catalog as a free-form string
            and either no-op'ing or failing on FK lookup. The two
            values match the ``Asset_Role`` controlled-vocabulary
            terms seeded by ``initialize_ml_schema``.
        cache: If True, cache the downloaded asset by MD5 checksum in the
            DerivaML cache directory. Cached assets are reused across executions
            when the checksum matches, avoiding repeated downloads of large files.

    Example:
        >>> spec = AssetSpec(rid="3JSE")
        >>> spec = AssetSpec(rid="3JSE", cache=True)  # enable caching
        >>> spec = AssetSpec(rid="3JSE", asset_role="Output")  # mark as output
    """

    rid: RID
    asset_role: Literal["Input", "Output"] = "Input"
    cache: bool = False

    model_config = VALIDATION_CONFIG

    @model_validator(mode="before")
    @classmethod
    def _check_bare_rid(cls, data: Any) -> dict[str, str | bool]:
        """Allow bare RID string as shorthand."""
        return {"rid": data} if isinstance(data, str) else data

AssetSpecConfig

Hydra-zen configuration interface for AssetSpec.

Exposes the asset attributes that are meaningful to configure: the asset rid and whether to cache it. It deliberately does not expose asset_role — an asset's role (Input / Output) is determined by context, not by configuration: an asset referenced in an execution's input configuration is an input, and assets written via commit_output_assets are outputs. AssetSpec.asset_role therefore keeps its "Input" default here and is set by the producing/consuming operation, never by the config author.

(Exposing asset_role as a configurable, Literal-typed field also broke structured-config registration under omegaconf < 2.4, which cannot serialize Literal annotations — another reason it does not belong on this interface.)

Use in hydra-zen store definitions to specify assets, optionally cached:

>>> from hydra_zen import store  # doctest: +SKIP
>>> asset_store = store(group="assets")  # doctest: +SKIP
>>> asset_store(  # doctest: +SKIP
...     [AssetSpecConfig(rid="6-EPNR", cache=True)],
...     name="cached_weights",
... )

Attributes:

Name Type Description
rid str

Resource Identifier of the asset. Mirrors AssetSpec.rid.

cache bool

If True, cache the downloaded asset by MD5 checksum in the DerivaML cache directory. Mirrors AssetSpec.cache.

Source code in src/deriva_ml/asset/aux_classes.py
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
@hydrated_dataclass(AssetSpec)
class AssetSpecConfig:
    """Hydra-zen configuration interface for ``AssetSpec``.

    Exposes the asset attributes that are meaningful to *configure*: the
    asset ``rid`` and whether to ``cache`` it. It deliberately does **not**
    expose ``asset_role`` — an asset's role (``Input`` / ``Output``) is
    determined by **context**, not by configuration: an asset referenced in
    an execution's input configuration is an *input*, and assets written via
    ``commit_output_assets`` are *outputs*. ``AssetSpec.asset_role`` therefore
    keeps its ``"Input"`` default here and is set by the producing/consuming
    operation, never by the config author.

    (Exposing ``asset_role`` as a configurable, ``Literal``-typed field also
    broke structured-config registration under omegaconf < 2.4, which cannot
    serialize ``Literal`` annotations — another reason it does not belong on
    this interface.)

    Use in hydra-zen store definitions to specify assets, optionally cached:

        >>> from hydra_zen import store  # doctest: +SKIP
        >>> asset_store = store(group="assets")  # doctest: +SKIP
        >>> asset_store(  # doctest: +SKIP
        ...     [AssetSpecConfig(rid="6-EPNR", cache=True)],
        ...     name="cached_weights",
        ... )

    Attributes:
        rid: Resource Identifier of the asset. Mirrors ``AssetSpec.rid``.
        cache: If True, cache the downloaded asset by MD5 checksum in
            the DerivaML cache directory. Mirrors ``AssetSpec.cache``.
    """

    rid: str
    cache: bool = False

AssetSummary

Bases: BaseModel

Compact view of a consumed Asset.

Attributes:

Name Type Description
rid RID

Asset RID.

filename str | None

Original filename (may be empty if the asset row has no filename column populated).

asset_table str

Name of the asset table the row lives in (e.g. "Image", "Execution_Asset").

Source code in src/deriva_ml/execution/lineage.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
class AssetSummary(BaseModel):
    """Compact view of a consumed Asset.

    Attributes:
        rid: Asset RID.
        filename: Original filename (may be empty if the asset row
            has no filename column populated).
        asset_table: Name of the asset table the row lives in
            (e.g. ``"Image"``, ``"Execution_Asset"``).
    """

    model_config = ConfigDict(extra="forbid")

    rid: RID
    filename: str | None = None
    asset_table: str

BaseConfig dataclass

Base configuration for DerivaML applications.

This dataclass defines the common configuration structure shared by both script execution and notebook modes. Project-specific configs should inherit from this class to get the standard DerivaML fields.

Note

Fields use Any type annotations because several DerivaML types (DerivaMLConfig, DatasetSpec) are Pydantic models which are not compatible with OmegaConf structured configs. The actual types at runtime are documented below.

Attributes:

Name Type Description
deriva_ml Any

DerivaML connection configuration (DerivaMLConfig at runtime).

datasets Any

List of dataset specifications (list[DatasetSpec] at runtime).

assets Any

List of asset RIDs to load (list[str] at runtime).

dry_run bool

If True, skip catalog writes (for testing/debugging).

description str

Human-readable description of this run.

config_choices dict[str, str]

Dictionary mapping config group names to selected config names. This is automatically populated by get_notebook_configuration() with the Hydra runtime choices (e.g., {"model_config": "cifar10_quick", "assets": "roc_quick"}). Useful for tracking which configurations were used in an execution.

script_config Any

Optional alternate hydra-zen callable for the code to run. When set, run_model invokes it instead of model_config (it takes precedence) and it is the only callable exercised during a dry run. Defaults to None (use model_config).

Example

from dataclasses import dataclass from deriva_ml.execution import BaseConfig

@dataclass ... class MyConfig(BaseConfig): ... learning_rate: float = 0.001 ... epochs: int = 10

Source code in src/deriva_ml/execution/base_config.py
 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
@dataclass
class BaseConfig:
    """Base configuration for DerivaML applications.

    This dataclass defines the common configuration structure shared by
    both script execution and notebook modes. Project-specific configs
    should inherit from this class to get the standard DerivaML fields.

    Note:
        Fields use ``Any`` type annotations because several DerivaML types
        (DerivaMLConfig, DatasetSpec) are Pydantic models which are not
        compatible with OmegaConf structured configs. The actual types at
        runtime are documented below.

    Attributes:
        deriva_ml: DerivaML connection configuration (DerivaMLConfig at runtime).
        datasets: List of dataset specifications (list[DatasetSpec] at runtime).
        assets: List of asset RIDs to load (list[str] at runtime).
        dry_run: If True, skip catalog writes (for testing/debugging).
        description: Human-readable description of this run.
        config_choices: Dictionary mapping config group names to selected config names.
            This is automatically populated by get_notebook_configuration() with the
            Hydra runtime choices (e.g., {"model_config": "cifar10_quick", "assets": "roc_quick"}).
            Useful for tracking which configurations were used in an execution.
        script_config: Optional alternate hydra-zen callable for the code to
            run. When set, ``run_model`` invokes it instead of ``model_config``
            (it takes precedence) and it is the only callable exercised during a
            dry run. Defaults to ``None`` (use ``model_config``).

    Example:
        >>> from dataclasses import dataclass
        >>> from deriva_ml.execution import BaseConfig
        >>>
        >>> @dataclass
        ... class MyConfig(BaseConfig):
        ...     learning_rate: float = 0.001
        ...     epochs: int = 10
    """

    deriva_ml: Any = None
    datasets: Any = None
    assets: Any = None
    dry_run: bool = False
    description: str = ""
    config_choices: dict[str, str] = field(default_factory=dict)
    script_config: Any = None

DatasetSummary

Bases: BaseModel

Compact view of a consumed Dataset.

Attributes:

Name Type Description
rid RID

Dataset RID.

description str | None

Dataset description (may be None or empty).

version str | None

Current version at the time the lineage was walked (e.g. "0.1.0"). None if the dataset has no version history yet.

Source code in src/deriva_ml/execution/lineage.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class DatasetSummary(BaseModel):
    """Compact view of a consumed Dataset.

    Attributes:
        rid: Dataset RID.
        description: Dataset description (may be None or empty).
        version: Current version at the time the lineage was walked
            (e.g. ``"0.1.0"``). None if the dataset has no version
            history yet.
    """

    model_config = ConfigDict(extra="forbid")

    rid: RID
    description: str | None = None
    version: str | None = None

DerivaMLModel

Bases: Protocol

Protocol for model functions compatible with DerivaML's run_model().

A model function must accept keyword arguments ml_instance and execution that are injected at runtime by run_model(). All other parameters are configured via Hydra and passed through the model_config.

The model function is responsible for: 1. Downloading input datasets via execution.download_dataset_bag() 2. Performing the ML computation (training, inference, etc.) 3. Registering output files via execution.asset_file_path()

Output files registered with asset_file_path() are automatically uploaded to the catalog after the model completes.

Attributes

This protocol defines a callable signature, not attributes.

Examples

Basic model function:

def my_model(
    epochs: int = 10,
    ml_instance: DerivaML = None,
    execution: Execution = None,
) -> None:
    # Training logic here
    pass

With domain-specific DerivaML subclass:

def eyeai_model(
    threshold: float = 0.5,
    ml_instance: EyeAI = None,  # EyeAI is a DerivaML subclass
    execution: Execution = None,
) -> None:
    # Can use EyeAI-specific methods
    ml_instance.some_eyeai_method()

Checking protocol compliance:

>>> from deriva_ml.execution.model_protocol import DerivaMLModel
>>> def my_model(epochs=10, ml_instance=None, execution=None):
...     pass
>>> isinstance(my_model, DerivaMLModel)
True
Source code in src/deriva_ml/execution/model_protocol.py
 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
@runtime_checkable
class DerivaMLModel(Protocol):
    """Protocol for model functions compatible with DerivaML's run_model().

    A model function must accept keyword arguments `ml_instance` and `execution`
    that are injected at runtime by run_model(). All other parameters are
    configured via Hydra and passed through the model_config.

    The model function is responsible for:
    1. Downloading input datasets via execution.download_dataset_bag()
    2. Performing the ML computation (training, inference, etc.)
    3. Registering output files via execution.asset_file_path()

    Output files registered with asset_file_path() are automatically uploaded
    to the catalog after the model completes.

    Attributes
    ----------
    This protocol defines a callable signature, not attributes.

    Examples
    --------
    Basic model function:

        def my_model(
            epochs: int = 10,
            ml_instance: DerivaML = None,
            execution: Execution = None,
        ) -> None:
            # Training logic here
            pass

    With domain-specific DerivaML subclass:

        def eyeai_model(
            threshold: float = 0.5,
            ml_instance: EyeAI = None,  # EyeAI is a DerivaML subclass
            execution: Execution = None,
        ) -> None:
            # Can use EyeAI-specific methods
            ml_instance.some_eyeai_method()

    Checking protocol compliance:

        >>> from deriva_ml.execution.model_protocol import DerivaMLModel
        >>> def my_model(epochs=10, ml_instance=None, execution=None):
        ...     pass
        >>> isinstance(my_model, DerivaMLModel)
        True
    """

    def __call__(
        self,
        *args: Any,
        ml_instance: "DerivaML",
        execution: "Execution",
        **kwargs: Any,
    ) -> None:
        """Execute the model within a DerivaML execution context.

        Parameters
        ----------
        *args : Any
            Positional arguments (typically not used; prefer keyword args).
        ml_instance : DerivaML
            The DerivaML instance (or subclass like EyeAI) connected to the
            catalog. Use this for catalog operations not available through
            the execution context.
        execution : Execution
            The execution context manager. Provides:
            - execution.datasets: List of input DatasetSpec objects
            - execution.download_dataset_bag(): Download dataset as BDBag
            - execution.asset_file_path(): Register output file for upload
            - execution.working_dir: Path to local working directory
        **kwargs : Any
            Model-specific parameters configured via Hydra.

        Returns
        -------
        None
            Models should not return values. Results are captured through:
            - Files registered with asset_file_path() (uploaded to catalog)
            - Datasets created with execution.create_dataset()
            - Status updates via execution.update_status()
        """
        ...

__call__

__call__(
    *args: Any,
    ml_instance: "DerivaML",
    execution: "Execution",
    **kwargs: Any,
) -> None

Execute the model within a DerivaML execution context.

Parameters

args : Any Positional arguments (typically not used; prefer keyword args). ml_instance : DerivaML The DerivaML instance (or subclass like EyeAI) connected to the catalog. Use this for catalog operations not available through the execution context. execution : Execution The execution context manager. Provides: - execution.datasets: List of input DatasetSpec objects - execution.download_dataset_bag(): Download dataset as BDBag - execution.asset_file_path(): Register output file for upload - execution.working_dir: Path to local working directory *kwargs : Any Model-specific parameters configured via Hydra.

Returns

None Models should not return values. Results are captured through: - Files registered with asset_file_path() (uploaded to catalog) - Datasets created with execution.create_dataset() - Status updates via execution.update_status()

Source code in src/deriva_ml/execution/model_protocol.py
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
def __call__(
    self,
    *args: Any,
    ml_instance: "DerivaML",
    execution: "Execution",
    **kwargs: Any,
) -> None:
    """Execute the model within a DerivaML execution context.

    Parameters
    ----------
    *args : Any
        Positional arguments (typically not used; prefer keyword args).
    ml_instance : DerivaML
        The DerivaML instance (or subclass like EyeAI) connected to the
        catalog. Use this for catalog operations not available through
        the execution context.
    execution : Execution
        The execution context manager. Provides:
        - execution.datasets: List of input DatasetSpec objects
        - execution.download_dataset_bag(): Download dataset as BDBag
        - execution.asset_file_path(): Register output file for upload
        - execution.working_dir: Path to local working directory
    **kwargs : Any
        Model-specific parameters configured via Hydra.

    Returns
    -------
    None
        Models should not return values. Results are captured through:
        - Files registered with asset_file_path() (uploaded to catalog)
        - Datasets created with execution.create_dataset()
        - Status updates via execution.update_status()
    """
    ...

DescribedList

Bases: list

A list with an attached description.

This class extends list to add a description attribute while maintaining full list compatibility. This allows configuration values (like asset RIDs or dataset specs) to carry documentation without changing how they're used.

When stored in hydra-zen and resolved via instantiate(), the result is a DescribedList that behaves like a regular list but has a description attribute.

Attributes:

Name Type Description
description

Human-readable description of this configuration.

Example

from hydra_zen import store # doctest: +SKIP from deriva_ml.execution import with_description # doctest: +SKIP

asset_store = store(group="assets") # doctest: +SKIP asset_store( # doctest: +SKIP ... with_description( ... ["3WMG", "3XPA"], ... "Model weights from quick and extended training", ... ), ... name="comparison_weights", ... )

After instantiation, usage is identical to a regular list:

config.assets[0] # "3WMG"

len(config.assets) # 2

for rid in config.assets: ...

config.assets.description # "Model weights from..."

Source code in src/deriva_ml/execution/base_config.py
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
class DescribedList(list):
    """A list with an attached description.

    This class extends list to add a `description` attribute while maintaining
    full list compatibility. This allows configuration values (like asset RIDs
    or dataset specs) to carry documentation without changing how they're used.

    When stored in hydra-zen and resolved via `instantiate()`, the result is a
    DescribedList that behaves like a regular list but has a `description` attribute.

    Attributes:
        description: Human-readable description of this configuration.

    Example:
        >>> from hydra_zen import store  # doctest: +SKIP
        >>> from deriva_ml.execution import with_description  # doctest: +SKIP
        >>>
        >>> asset_store = store(group="assets")  # doctest: +SKIP
        >>> asset_store(  # doctest: +SKIP
        ...     with_description(
        ...         ["3WMG", "3XPA"],
        ...         "Model weights from quick and extended training",
        ...     ),
        ...     name="comparison_weights",
        ... )
        >>>
        >>> # After instantiation, usage is identical to a regular list:
        >>> # config.assets[0]  # "3WMG"
        >>> # len(config.assets)  # 2
        >>> # for rid in config.assets: ...
        >>> # config.assets.description  # "Model weights from..."
    """

    def __init__(self, items: list | None = None, description: str = ""):
        """Initialize a DescribedList.

        Args:
            items: Initial list items. If None, creates empty list.
            description: Human-readable description of this list.
        """
        super().__init__(items or [])
        self.description = description

    def __repr__(self) -> str:
        """Return string representation including description."""
        if self.description:
            return f"DescribedList({list(self)!r}, description={self.description!r})"
        return f"DescribedList({list(self)!r})"

__init__

__init__(
    items: list | None = None,
    description: str = "",
)

Initialize a DescribedList.

Parameters:

Name Type Description Default
items list | None

Initial list items. If None, creates empty list.

None
description str

Human-readable description of this list.

''
Source code in src/deriva_ml/execution/base_config.py
913
914
915
916
917
918
919
920
921
def __init__(self, items: list | None = None, description: str = ""):
    """Initialize a DescribedList.

    Args:
        items: Initial list items. If None, creates empty list.
        description: Human-readable description of this list.
    """
    super().__init__(items or [])
    self.description = description

__repr__

__repr__() -> str

Return string representation including description.

Source code in src/deriva_ml/execution/base_config.py
923
924
925
926
927
def __repr__(self) -> str:
    """Return string representation including description."""
    if self.description:
        return f"DescribedList({list(self)!r}, description={self.description!r})"
    return f"DescribedList({list(self)!r})"

Execution

Manages the lifecycle and context of a DerivaML execution.

An Execution represents a computational or manual process within DerivaML. It provides: - Dataset materialization and access - Asset management (inputs and outputs) - Status tracking and updates - Provenance recording - Result upload and cataloging

The class handles downloading required datasets and assets, tracking execution state, and managing the upload of results. Every dataset and file generated is associated with an execution record for provenance tracking.

Attributes:

Name Type Description
dataset_rids list[RID]

RIDs of datasets used in the execution.

datasets DatasetCollection

Collection wrapping the materialized DatasetBag objects (iterable, indexable; not a plain list).

configuration ExecutionConfiguration

Execution settings and parameters.

workflow_rid RID

RID of the associated workflow.

status ExecutionStatus

Current execution status (read-through from SQLite).

asset_paths dict[str, list[AssetFilePath]]

Mapping of asset-table name to the list of AssetFilePath objects for input assets downloaded by _initialize_execution. Each downloaded asset lands at <working_dir>/<exec_rid>/downloaded-assets/<asset_table>/<asset_rid>/<Filename> — keyed by asset RID, so two assets that share the same Filename do not collide on disk. Read files via AssetFilePath.file_name; do not hand-construct paths from the asset table or filename.

start_time datetime | None

When execution started.

stop_time datetime | None

When execution completed.

Example

The context manager handles start/stop timing. Upload must be called AFTER the context manager exits::

>>> config = ExecutionConfiguration(  # doctest: +SKIP
...     workflow="analysis",  # doctest: +SKIP
...     description="Process samples",  # doctest: +SKIP
... )  # doctest: +SKIP
>>> with ml.create_execution(config) as execution:  # doctest: +SKIP
...     bag = execution.download_dataset_bag(dataset_spec)  # doctest: +SKIP
...     # Run analysis using bag.path
...     output_path = execution.asset_file_path("Model", "model.pt")  # doctest: +SKIP
...     # Write results to output_path
...
>>> # IMPORTANT: Call commit AFTER exiting the context manager
>>> execution.commit_output_assets()  # doctest: +SKIP
Source code in src/deriva_ml/execution/execution.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
class Execution:
    """Manages the lifecycle and context of a DerivaML execution.

    An Execution represents a computational or manual process within DerivaML. It provides:
    - Dataset materialization and access
    - Asset management (inputs and outputs)
    - Status tracking and updates
    - Provenance recording
    - Result upload and cataloging

    The class handles downloading required datasets and assets, tracking execution state,
    and managing the upload of results. Every dataset and file generated is associated
    with an execution record for provenance tracking.

    Attributes:
        dataset_rids (list[RID]): RIDs of datasets used in the execution.
        datasets (DatasetCollection): Collection wrapping the materialized
            ``DatasetBag`` objects (iterable, indexable; not a plain list).
        configuration (ExecutionConfiguration): Execution settings and parameters.
        workflow_rid (RID): RID of the associated workflow.
        status (ExecutionStatus): Current execution status (read-through from SQLite).
        asset_paths (dict[str, list[AssetFilePath]]): Mapping of asset-table name to
            the list of ``AssetFilePath`` objects for input assets downloaded by
            ``_initialize_execution``. Each downloaded asset lands at
            ``<working_dir>/<exec_rid>/downloaded-assets/<asset_table>/<asset_rid>/<Filename>``
            — keyed by asset RID, so two assets that share the same ``Filename`` do
            not collide on disk. Read files via ``AssetFilePath.file_name``; do not
            hand-construct paths from the asset table or filename.
        start_time (datetime | None): When execution started.
        stop_time (datetime | None): When execution completed.

    Example:
        The context manager handles start/stop timing. Upload must be called AFTER
        the context manager exits::

            >>> config = ExecutionConfiguration(  # doctest: +SKIP
            ...     workflow="analysis",  # doctest: +SKIP
            ...     description="Process samples",  # doctest: +SKIP
            ... )  # doctest: +SKIP
            >>> with ml.create_execution(config) as execution:  # doctest: +SKIP
            ...     bag = execution.download_dataset_bag(dataset_spec)  # doctest: +SKIP
            ...     # Run analysis using bag.path
            ...     output_path = execution.asset_file_path("Model", "model.pt")  # doctest: +SKIP
            ...     # Write results to output_path
            ...
            >>> # IMPORTANT: Call commit AFTER exiting the context manager
            >>> execution.commit_output_assets()  # doctest: +SKIP
    """

    @validate_call(config=VALIDATION_CONFIG)
    def __init__(
        self,
        configuration: ExecutionConfiguration,
        ml_object: DerivaML,
        workflow: Workflow | None = None,
        reload: RID | None = None,
        dry_run: bool = False,
    ):
        """Initializes an Execution instance.

        Creates a new execution or reloads an existing one. Initializes the execution
        environment, downloads required datasets, and sets up asset tracking.

        Args:
            configuration: Settings and parameters for the execution.
            ml_object: DerivaML instance managing the execution.
            workflow: Optional Workflow object. If not specified, the workflow is taken from
                the ExecutionConfiguration object. Must be a Workflow object, not a RID.
            reload: Optional RID of existing execution to reload.
            dry_run: If True, don't create catalog records or upload results.

        Raises:
            DerivaMLException: If initialization fails, configuration is invalid,
                or workflow is not a Workflow object.

        Example:
            Create an execution with a workflow::

                >>> workflow = ml.lookup_workflow("2-ABC1")  # doctest: +SKIP
                >>> config = ExecutionConfiguration(  # doctest: +SKIP
                ...     workflow=workflow,  # doctest: +SKIP
                ...     description="Process data"  # doctest: +SKIP
                ... )  # doctest: +SKIP
                >>> execution = Execution(config, ml)  # doctest: +SKIP

            Or pass workflow separately::

                >>> workflow = ml.lookup_workflow_by_url(  # doctest: +SKIP
                ...     "https://github.com/org/repo/blob/abc123/analysis.py"  # doctest: +SKIP
                ... )  # doctest: +SKIP
                >>> config = ExecutionConfiguration(description="Run analysis")  # doctest: +SKIP
                >>> execution = Execution(config, ml, workflow=workflow)  # doctest: +SKIP
        """

        self.asset_paths: dict[str, list[AssetFilePath]] = {}
        self.configuration = configuration
        self._ml_object = ml_object
        self._model = ml_object.model
        self._logger = ml_object._logger
        # NOTE(E1/E3): self._status / self.start_time / self.stop_time
        # intentionally removed — execution status and lifecycle
        # timestamps now live in SQLite (see `status`, `start_time`,
        # `stop_time` properties below). Every read hits the workspace
        # registry; no in-memory copy is kept. ``uploaded_assets``
        # similarly reads from the asset manifest on every access
        # (see the ``uploaded_assets`` @property below) — no instance
        # field needed.
        self.configuration.argv = sys.argv
        self._execution_record: ExecutionRecord | None = None  # Lazily created after RID is assigned

        self.dataset_rids: List[RID] = []
        self._datasets_list: list[DatasetBag] = []

        self._working_dir = self._ml_object.working_dir
        self._cache_dir = self._ml_object.cache_dir
        if self._working_dir is None:
            raise DerivaMLException(
                "DerivaML working_dir is not set. "
                "Ensure the DerivaML instance was initialized with a valid working_dir."
            )
        self._dry_run = dry_run

        # Make sure we have a valid Workflow object.
        if workflow:
            self.configuration.workflow = workflow

        if self.configuration.workflow is None:
            raise DerivaMLException("Workflow must be specified either in configuration or as a parameter")

        if not isinstance(self.configuration.workflow, Workflow):
            raise DerivaMLException(
                f"Workflow must be a Workflow object, not {type(self.configuration.workflow).__name__}. "
                "Use ml.lookup_workflow(rid) or ml.lookup_workflow_by_url(url) to get a Workflow object."
            )

        # Validate workflow type(s) and register in catalog
        for wt in self.configuration.workflow.workflow_type:
            self._ml_object.lookup_term(MLVocab.workflow_type, wt)
        self.workflow_rid = (
            self._ml_object._add_workflow(self.configuration.workflow) if not self._dry_run else DRY_RUN_RID
        )

        # Validate the datasets and assets to be valid.
        for d in self.configuration.datasets:
            if self._ml_object.resolve_rid(d.rid).table.name != "Dataset":
                raise DerivaMLException("Dataset specified in execution configuration is not a dataset")

        for a in self.configuration.assets:
            if not self._model.is_asset(self._ml_object.resolve_rid(a.rid).table.name):
                raise DerivaMLException("Asset specified in execution configuration is not an asset table")

        schema_path = self._ml_object.pathBuilder().schemas[self._ml_object.ml_schema]
        if reload:
            self.execution_rid = reload
            if self.execution_rid == DRY_RUN_RID:
                self._dry_run = True
        elif self._dry_run:
            self.execution_rid = DRY_RUN_RID
        else:
            self.execution_rid = schema_path.Execution.insert(
                [
                    {
                        "Description": self.configuration.description,
                        "Workflow": self.workflow_rid,
                        "Status": str(ExecutionStatus.Created),
                    }
                ]
            )[0]["RID"]

        # Ex-init2 (audit): the catalog row exists at this point.
        # Everything below — environment file writes, dataset
        # materialization, asset downloads, SQLite registry insert —
        # can fail and leave an orphaned catalog Execution row. Wrap
        # the post-insert work in a try/except that rolls back the
        # catalog row before re-raising. ``reload`` and ``dry_run``
        # paths skip the rollback because they never inserted a row
        # in the first place.
        _catalog_row_owned_by_us = not reload and not self._dry_run and self.execution_rid != DRY_RUN_RID
        try:
            self._post_catalog_init_init(reload, schema_path)
        except Exception:
            if _catalog_row_owned_by_us:
                # Best-effort orphan cleanup; never mask the
                # original failure with a delete-side error.
                try:
                    schema_path.Execution.filter(schema_path.Execution.RID == self.execution_rid).delete()
                    logger.warning(
                        "create_execution %s: post-insert work failed; rolled back orphaned catalog Execution row.",
                        self.execution_rid,
                    )
                except Exception as cleanup_exc:
                    logger.error(
                        "create_execution %s: post-insert work failed AND "
                        "orphan-rollback also failed (%s). Manual cleanup "
                        "required: ``deriva-ml`` Execution row at this RID "
                        "has no workspace SQLite sibling.",
                        self.execution_rid,
                        cleanup_exc,
                    )
            raise

    def _post_catalog_init_init(self, reload, schema_path) -> None:
        """The post-catalog-insert section of __init__.

        Extracted (audit Ex-init2) so the wrapping try/except in
        ``__init__`` can roll back the orphaned catalog row on
        any failure here. Includes the
        ``DERIVA_ML_SAVE_EXECUTION_RID`` write, workspace setup,
        ExecutionRecord construction, dataset+asset download
        (via ``_initialize_execution``), and the SQLite registry
        insert.
        """
        if rid_path := os.environ.get("DERIVA_ML_SAVE_EXECUTION_RID", None):
            # Put execution_rid into the provided file path so we can find it later.
            # Also include hydra_runtime_output_dir so an outer runner harness
            # (run_notebook.py) can locate the Hydra job log it owns and register
            # it post-kernel — see "additive upload" in the state-machine docs.
            hydra_dir = getattr(self._ml_object, "hydra_runtime_output_dir", None)
            with Path(rid_path).open("w") as f:
                json.dump(
                    {
                        "hostname": self._ml_object.host_name,
                        "catalog_id": self._ml_object.catalog_id,
                        "workflow_rid": self.workflow_rid,
                        "execution_rid": self.execution_rid,
                        "hydra_runtime_output_dir": str(hydra_dir) if hydra_dir else None,
                    },
                    f,
                )

        # Create a directory for execution rid so we can recover the state in case of a crash.
        execution_root(prefix=self._ml_object.working_dir, exec_rid=self.execution_rid)

        # Create the ExecutionRecord to handle catalog state operations
        if not self._dry_run:
            self._execution_record = ExecutionRecord(
                execution_rid=self.execution_rid,
                workflow=self.configuration.workflow,
                status=ExecutionStatus.Created,
                description=self.configuration.description,
                _ml_instance=self._ml_object,
                _logger=self._logger,
            )

        # Bracket _initialize_execution with timestamps so the
        # download/materialize phase contributes a Download_Duration to
        # the catalog row. The SQLite registry row doesn't exist yet at
        # this point (insert_execution runs below), so we stash the
        # formatted string on self and write it through after the row
        # is created. See docs/bugs/2026-05-19-execution-phase-durations-design.md.
        from datetime import timezone

        _download_start = datetime.now(timezone.utc)
        self._initialize_execution(reload)
        _download_end = datetime.now(timezone.utc)
        self._download_duration_str = _format_duration(_download_start, _download_end)

        # Guard SQLite registry insertion: skip when (a) this is a dry-run
        # (we never want to persist dry-run state) or (b) we are resuming an
        # existing execution (reload is not None), in which case the registry
        # entry was written by the original run and should not be overwritten.
        # Writing twice would corrupt the start-time and initial-status fields.
        #
        # Pre Ex-init2 fix this site wrapped its own try/except that just
        # logged + re-raised, leaving an orphaned catalog row. The outer
        # try/except in ``__init__`` now owns orphan rollback for any
        # post-catalog-insert failure (this one, dataset materialization,
        # asset download, environment writes), so the inner wrapper is gone.
        if not self._dry_run and reload is None:
            store = self._ml_object.workspace.execution_state_store()
            now = datetime.now(timezone.utc)

            # Serialize the ExecutionConfiguration. Pydantic v2 dumps to
            # a plain dict; model_dump_json then serializes. Includes
            # the RID + version info so a reconstructed configuration
            # from a resume_execution call is faithful.
            config_json = self.configuration.model_dump_json()

            store.insert_execution(
                rid=self.execution_rid,
                workflow_rid=self.workflow_rid,
                description=self.configuration.description,
                config_json=config_json,
                status=ExecutionStatus.Created,
                mode=self._ml_object._mode,
                working_dir_rel=f"execution/{self.execution_rid}",
                created_at=now,
                last_activity=now,
            )
            # Persist the just-measured download duration through
            # update_execution. Done as a follow-up write rather
            # than baked into insert_execution so the insert
            # signature stays focused on identity / config fields.
            store.update_execution(
                self.execution_rid,
                download_duration=self._download_duration_str,
            )

    @classmethod
    def from_registry(cls, *, ml_object, execution_rid: str) -> "Execution":
        """Bind an Execution to an existing SQLite registry row.

        Distinct from ``create_execution`` — does NOT contact the
        catalog and does NOT POST a new row. The bound ``Execution``
        instance reads its lifecycle fields (``status``, ``error``,
        ``start_time``, ``stop_time``) from SQLite via the
        read-through property machinery.

        Called by :meth:`DerivaML.resume_execution`.

        Args:
            ml_object: The DerivaML instance this Execution is bound to.
            execution_rid: The pre-existing Execution RID.

        Returns:
            A minimally-initialized Execution with just enough state for
            execution_rid lookup.
        """
        # Minimal construction: skip __init__'s catalog interactions.
        # The read-through properties handle lifecycle field access.
        instance = cls.__new__(cls)
        instance._ml_object = ml_object
        instance._model = ml_object.model
        instance._logger = getattr(ml_object, "_logger", None)
        instance.execution_rid = execution_rid
        instance._dry_run = False
        # Fields the existing class expects to exist:
        instance._datasets_list = []
        instance.dataset_rids = []
        instance.asset_paths = {}
        instance.configuration = None  # Group E loads from config_json
        instance._working_dir = ml_object.working_dir
        instance._cache_dir = ml_object.cache_dir
        # NOTE(E1/E3): self._status / self.start_time / self.stop_time /
        # self.uploaded_assets intentionally not set — they are all
        # read-through properties backed by SQLite / the asset manifest.
        instance._execution_record = None
        # Pull ``workflow_rid`` from the registry row. The SQLite
        # row carries it (see ``state_store.executions.workflow_rid``);
        # leaving it None silently breaks downstream code that
        # relies on ``execution.workflow_rid`` (notably
        # ``add_workflow_executions`` linkage during nested-execution
        # attach). Best-effort: if the registry lookup fails or
        # returns None, leave it None — but we try.
        instance.workflow_rid = None
        try:
            row = ml_object.workspace.execution_state_store().get_execution(execution_rid)
            if row is not None:
                instance.workflow_rid = row.get("workflow_rid")
        except Exception:
            # The registry read can fail in odd offline-mode tests
            # or partially-initialized fixtures; preserve the
            # legacy ``None`` rather than refuse to construct.
            pass
        return instance

    def _save_runtime_environment(self):
        # Delegates to ``asset_upload.save_runtime_environment``
        # — extracted in the Ex-god first sweep so the helper
        # has a single home alongside the other asset-staging
        # helpers in ``execution/asset_upload.py``.
        from deriva_ml.execution.asset_upload import save_runtime_environment

        save_runtime_environment(
            self,
            runtime_env_asset_type=ExecMetadataType.runtime_env.value,
            env_snapshot_description=_ENV_SNAPSHOT_DESCRIPTION,
        )

    def _upload_hydra_config_assets(self):
        """Register Hydra static config YAMLs as Execution_Metadata assets.

        Delegates to ``asset_upload.upload_hydra_config_assets``;
        see that helper for the design notes on why this only
        walks ``<hydra_run_dir>/hydra-config/`` and not the
        parent directory.
        """
        from deriva_ml.execution.asset_upload import upload_hydra_config_assets

        upload_hydra_config_assets(
            self,
            hydra_config_asset_type=ExecMetadataType.hydra_config.value,
            metadata_descriptions=_METADATA_DESCRIPTIONS,
            env_snapshot_description=_ENV_SNAPSHOT_DESCRIPTION,
            execution_metadata_asset_name=MLAsset.execution_metadata,
        )

    @staticmethod
    def _get_metadata_description(file_name: str) -> str | None:
        """Resolve a description for an execution metadata file.

        Thin delegate to
        ``asset_upload.get_metadata_description``; the module-level
        constants are passed through so the helper stays
        decoupled from this class's imports.
        """
        from deriva_ml.execution.asset_upload import get_metadata_description

        return get_metadata_description(
            file_name,
            metadata_descriptions=_METADATA_DESCRIPTIONS,
            env_snapshot_description=_ENV_SNAPSHOT_DESCRIPTION,
        )

    def _set_asset_descriptions(self, uploaded_assets: dict[str, list[AssetFilePath]]) -> None:
        """Set Description on asset records after upload.

        Delegates to ``asset_upload.set_asset_descriptions``;
        see that helper for the manifest-snapshot performance
        note and the two-source description-resolution rule.
        """
        from deriva_ml.execution.asset_upload import set_asset_descriptions

        set_asset_descriptions(
            self,
            uploaded_assets,
            metadata_descriptions=_METADATA_DESCRIPTIONS,
            env_snapshot_description=_ENV_SNAPSHOT_DESCRIPTION,
        )

    def _materialize_input_datasets(self, reload: RID | None) -> None:
        """Materialize each input dataset and link it to the execution.

        For every ``DatasetSpec`` in :attr:`configuration.datasets`:

        1. Download the bag (via :meth:`download_dataset_bag`).
        2. Append it to :attr:`_datasets_list` and track the RID
           in :attr:`dataset_rids`.

        When this is a live run (not ``reload`` or ``dry_run``)
        and at least one dataset is present, insert the
        ``Dataset_Execution`` association rows in one batch.

        Args:
            reload: ``None`` for a fresh execution; an existing
                RID when resuming.
        """
        for dataset in self.configuration.datasets:
            self._logger.info(f"Materialize bag {dataset.rid}... ")
            self._datasets_list.append(self.download_dataset_bag(dataset))
            self.dataset_rids.append(dataset.rid)

        schema_path = self._ml_object.pathBuilder().schemas[self._ml_object.ml_schema]
        if self.dataset_rids and not (reload or self._dry_run):
            # Config-declared datasets are *inputs* (consume edges). Record the
            # consumed version on each input edge via the
            # ``Dataset_Execution.Dataset_Version`` FK, resolved from the
            # ``DatasetSpec.version`` (authorship-canonical model, Task 4).
            schema_path.Dataset_Execution.insert(
                [
                    {
                        "Dataset": dataset.rid,
                        "Execution": self.execution_rid,
                        "Dataset_Version": self._ml_object._version_rid(dataset.rid, dataset.version),
                    }
                    for dataset in self.configuration.datasets
                ]
            )

    def _download_input_assets(self, reload: RID | None) -> None:
        """Resolve every input asset RID and download to its per-asset slot.

        Each asset lands at
        ``<working_dir>/<exec_rid>/downloaded-assets/<asset_table>/<asset_rid>/<Filename>``
        so two assets with the same ``Filename`` from the same
        table don't collide on disk (common for prediction CSVs
        emitted by parallel multirun children).

        Args:
            reload: ``None`` for a fresh execution; an existing
                RID when resuming. The ``update_catalog`` flag on
                :meth:`download_asset` is suppressed when
                resuming or dry-running.
        """
        self._logger.info("Downloading assets ...")
        self.asset_paths = {}
        # Batch-resolve every asset RID up front (one query per
        # candidate table) instead of one resolve_rid round-trip per
        # asset. Skip cleanly when there are no asset specs so an
        # empty configuration doesn't fire a no-op resolve_rids call.
        asset_specs = list(self.configuration.assets)
        if asset_specs:
            asset_rids = [spec.rid for spec in asset_specs]
            rid_results = self._ml_object.resolve_rids(asset_rids)
        else:
            rid_results = {}
        for asset_spec in asset_specs:
            asset_rid = asset_spec.rid
            use_cache = asset_spec.cache
            rid_info = rid_results.get(asset_rid)
            if rid_info is None:
                # resolve_rids would have raised on missing RIDs; this
                # branch only triggers if asset_specs was non-empty but
                # rid_info wasn't returned (defensive — should not
                # happen).
                rid_info_table = self._ml_object.resolve_rid(asset_rid).table
            else:
                rid_info_table = rid_info.table
            asset_table = rid_info_table.name
            dest_dir = (
                execution_root(self._ml_object.working_dir, self.execution_rid)
                / "downloaded-assets"
                / asset_table
                / asset_rid
            )
            dest_dir.mkdir(parents=True, exist_ok=True)
            self.asset_paths.setdefault(asset_table, []).append(
                self.download_asset(
                    asset_rid=asset_rid,
                    dest_dir=dest_dir,
                    update_catalog=not (reload or self._dry_run),
                    use_cache=use_cache,
                    _asset_table=rid_info_table,
                )
            )

    def _register_init_metadata(self) -> None:
        """Stage configuration / uv.lock / Hydra config / runtime env for upload.

        Writes the in-memory configuration to
        ``configuration.json``, attaches ``uv.lock`` when the
        workflow's git root carries one, registers Hydra config
        assets (when running under hydra-zen), and snapshots the
        runtime environment (Python version, package list, etc.)
        for provenance.

        These artifacts are staged into the manifest only; the
        actual upload is :meth:`_upload_init_assets`.

        Skipped in ``dry_run`` and ``reload`` modes — the caller
        of :meth:`_initialize_execution` guards on this.
        """
        # Save DerivaML configuration with Deriva_Config type.
        cfile = self.asset_file_path(
            asset_name=MLAsset.execution_metadata,
            file_name="configuration.json",
            asset_types=ExecMetadataType.deriva_config.value,
            description=_METADATA_DESCRIPTIONS["configuration.json"],
        )
        with Path(cfile).open("w", encoding="utf-8") as config_file:
            json.dump(self.configuration.model_dump(mode="json"), config_file)

        # Only try to copy uv.lock if git_root is available (local workflow).
        if self.configuration.workflow.git_root:
            lock_file = Path(self.configuration.workflow.git_root) / "uv.lock"
        else:
            lock_file = None
        if lock_file and lock_file.exists():
            _ = self.asset_file_path(
                asset_name=MLAsset.execution_metadata,
                file_name=lock_file,
                asset_types=ExecMetadataType.execution_config.value,
                description=_METADATA_DESCRIPTIONS["uv.lock"],
            )

        self._upload_hydra_config_assets()
        self._save_runtime_environment()

    def _upload_init_assets(self) -> None:
        """Commit the staged init-time assets so they land in the catalog.

        Pairs with :meth:`_register_init_metadata`: that method
        stages files, this one commits them. Splitting keeps the
        catalog-write boundary visible. Same skip-in-dry-run/reload
        guard at the caller.
        """
        uploaded = self._bag_commit_upload()
        self._set_asset_descriptions(uploaded)

    def _initialize_execution(self, reload: RID | None = None) -> None:
        """Initialize the execution environment.

        Sets up the working directory, downloads required datasets and assets,
        and saves initial configuration metadata. Each input asset is placed at
        ``<working_dir>/<exec_rid>/downloaded-assets/<asset_table>/<asset_rid>/<Filename>``
        so two assets that share an asset table and ``Filename`` do not collide
        on disk. After initialization, ``self.asset_paths`` maps asset-table
        name to the list of ``AssetFilePath`` objects produced; use
        ``AssetFilePath.file_name`` as the canonical read path.

        Post Ex-init extraction this method is a thin dispatcher
        over four private helpers:

        1. :meth:`_materialize_input_datasets` — bag downloads +
           ``Dataset_Execution`` insert.
        2. :meth:`_download_input_assets` — per-asset RID resolution
           and download.
        3. :meth:`_register_init_metadata` — config JSON + uv.lock
           + Hydra config + runtime env staging. Skipped in
           ``dry_run`` and ``reload`` modes.
        4. :meth:`_upload_init_assets` — commit the staged
           init-time assets. Same skip-in-dry-run/reload guard.

        Args:
            reload: Optional RID of a previously initialized execution to reload.

        Raises:
            DerivaMLException: If initialization fails.
        """
        self._materialize_input_datasets(reload)
        self._download_input_assets(reload)

        if not reload and not self._dry_run:
            self._register_init_metadata()
            # Now upload the files so we have the info in case the execution fails.
            self._upload_init_assets()

        # NOTE(E3): `start_time` is no longer an instance attribute —
        # the authoritative value is written to SQLite by __enter__ via
        # state_machine.transition. `_initialize_execution` predates the
        # read-through design and is part of the legacy path retained
        # for `execution_start`/`execution_stop` compatibility.
        self._logger.info("Initialize status finished.")

    def _get_registry_row(self) -> dict:
        """Read this execution's row from the workspace SQLite registry.

        Shared helper for the four read-through properties (``status``,
        ``error``, ``start_time``, ``stop_time``). No caching — a
        mutation from another process (e.g., ``deriva-ml upload``
        running in a shell) is visible on the next read.

        Returns:
            The row dict from ``ExecutionStateStore.get_execution``.

        Raises:
            DerivaMLStateInconsistency: If the executions row for this
                rid is missing (gc'd, never created, or dry-run).
        """
        from deriva_ml.core.exceptions import DerivaMLStateInconsistency

        store = self._ml_object.workspace.execution_state_store()
        row = store.get_execution(self.execution_rid)
        if row is None:
            raise DerivaMLStateInconsistency(
                f"Execution {self.execution_rid} no longer in workspace registry. "
                f"It may have been garbage-collected or the workspace was "
                f"recreated. Use ml.list_executions() to see current state."
            )
        return row

    @staticmethod
    def _coerce_utc(value: "datetime | None") -> "datetime | None":
        """Coerce a SQLite-returned datetime to UTC-aware.

        SQLite may return naive datetimes even though we store them
        timezone-aware. Re-attach the UTC tzinfo when missing.
        """
        from datetime import timezone

        if value is not None and value.tzinfo is None:
            value = value.replace(tzinfo=timezone.utc)
        return value

    @property
    def status(self) -> "ExecutionStatus":
        """Current execution status, read from SQLite on every access.

        No caching — a mutation from another process (e.g., ``deriva-ml
        upload`` running in a shell) is visible on the next read.

        Returns:
            The ExecutionStatus value from the workspace registry.

        Raises:
            DerivaMLStateInconsistency: If the executions row for this
                rid is missing (gc'd or never created).

        Example:
            >>> exe = ml.resume_execution("5-ABC")  # doctest: +SKIP
            >>> exe.status  # doctest: +SKIP
            <ExecutionStatus.Stopped>
        """
        return ExecutionStatus(self._get_registry_row()["status"])

    @property
    def error(self) -> str | None:
        """Last error message for this execution, read from SQLite.

        Parallels ``status`` — no caching, every read hits the workspace
        registry. Populated by ``__exit__`` when an exception occurs
        (see spec §2.8 / §2.12).

        Returns:
            The error message string, or None if no error has been
            recorded for this execution.

        Raises:
            DerivaMLStateInconsistency: If the executions row for this
                rid is missing (gc'd or never created).

        Example:
            >>> with exe.execute():  # doctest: +SKIP
            ...     raise RuntimeError("boom")  # doctest: +SKIP
            >>> exe.error  # doctest: +SKIP
            'RuntimeError: boom'
        """
        return self._get_registry_row()["error"]

    @property
    def start_time(self) -> "datetime | None":
        """Start time from SQLite, or None if not yet started.

        Parallels ``status`` / ``error`` — no caching, every read hits
        the workspace registry. Populated by ``__enter__`` when the
        execution transitions to ``running``. Returned values are
        coerced to UTC-aware datetimes (SQLite may return naive values
        even though we store tz-aware).

        Returns:
            Timezone-aware (UTC) datetime when the execution's
            ``__enter__`` ran, or None before.

        Raises:
            DerivaMLStateInconsistency: If the executions row for this
                rid is missing (gc'd or never created, e.g. dry-run).

        Example:
            >>> exe = ml.resume_execution("EXE-A")  # doctest: +SKIP
            >>> if exe.start_time is not None:  # doctest: +SKIP
            ...     print(f"started at {exe.start_time}")  # doctest: +SKIP
        """
        return self._coerce_utc(self._get_registry_row()["start_time"])

    @property
    def stop_time(self) -> "datetime | None":
        """Stop time from SQLite, or None if not yet stopped/failed.

        Parallels ``status`` / ``error`` — no caching, every read hits
        the workspace registry. Populated by ``__exit__`` on either
        clean stop or exception (see spec §2.8 / §2.12). Returned
        values are coerced to UTC-aware datetimes.

        Returns:
            Timezone-aware (UTC) datetime when the execution's
            ``__exit__`` ran, or None if still running.

        Raises:
            DerivaMLStateInconsistency: If the executions row for this
                rid is missing.

        Example:
            >>> exe = ml.resume_execution("EXE-A")  # doctest: +SKIP
            >>> if exe.stop_time is not None:  # doctest: +SKIP
            ...     print(f"stopped at {exe.stop_time}")  # doctest: +SKIP
        """
        return self._coerce_utc(self._get_registry_row()["stop_time"])

    @property
    def uploaded_assets(self) -> dict[str, list[AssetFilePath]]:
        """Assets this execution has uploaded, read from the asset manifest.

        Reads the manifest on every access — no in-memory cache. The
        returned dict carries every entry whose status is
        ``uploaded`` across the manifest's lifetime, regardless of
        which ``commit_output_assets()`` call produced it. Each
        value is a list of :class:`AssetFilePath` objects giving the
        leased ``asset_rid`` and ``file_name`` for the entry.

        Returns:
            Map of ``"{schema}/{table}"`` → list of
            :class:`AssetFilePath`. Empty dict for dry-run executions
            and for executions that haven't uploaded anything yet.
            Never ``None``.

        Note:
            Until the Phase 3 cleanup landed (audit §A.8) this was an
            instance attribute holding the **most-recent call's**
            return value. The manifest is now the source of truth;
            the property returns the full manifest's uploaded
            entries. Callers that need the per-call subset should
            use the return value of ``commit_output_assets()``
            directly.

        Example:
            >>> with ml.create_execution(cfg) as exe:  # doctest: +SKIP
            ...     pass  # doctest: +SKIP
            >>> report = exe.commit_output_assets()  # doctest: +SKIP
            >>> # After commit, the property reflects the manifest:
            >>> sum(len(v) for v in exe.uploaded_assets.values()) >= report.total_uploaded  # doctest: +SKIP
            True
        """
        if self._dry_run:
            return {}
        from deriva_ml.execution.bag_commit import report_to_asset_map

        manifest = self._get_manifest()
        # ``report`` is unused when ``keys=None`` — pass a sentinel
        # that ``report_to_asset_map`` won't dereference.
        return report_to_asset_map(
            execution=self,
            report=None,  # type: ignore[arg-type]
            manifest=manifest,
            keys=None,
        )

    @property
    def datasets(self) -> "DatasetCollection":
        """Input datasets as a RID-keyed mapping + iterable.

        Replaces the previous ``list[DatasetBag]`` exposure (hard
        cutover per spec R5.1). The returned collection behaves like a
        ``Mapping[str, DatasetBag]`` (keyed by ``dataset_rid``) and is
        also iterable, yielding ``DatasetBag`` values in insertion
        order.

        Returns:
            A ``DatasetCollection`` wrapping the materialized
            ``DatasetBag`` objects that were downloaded during
            execution initialization.

        Example:
            >>> # RID lookup (primary access pattern)
            >>> bag = exe.datasets["1-XYZ"]  # doctest: +SKIP
            >>> # Iterate bags in insertion order
            >>> for bag in exe.datasets:  # doctest: +SKIP
            ...     print(bag.dataset_rid)  # doctest: +SKIP
            >>> # Introspect which RIDs are present
            >>> rids = list(exe.datasets.keys())  # doctest: +SKIP
            >>> # Count
            >>> n = len(exe.datasets)  # doctest: +SKIP

        Migration note:
            Callers that previously indexed by position
            (``exe.datasets[0]``) must switch to either
            ``list(exe.datasets)[0]`` or the RID-keyed lookup
            ``exe.datasets[rid]``.
        """
        from deriva_ml.execution.dataset_collection import DatasetCollection

        return DatasetCollection(self._datasets_list)

    @property
    def execution_record(self) -> ExecutionRecord | None:
        """Get the ExecutionRecord for catalog operations.

        Returns:
            ExecutionRecord if not in dry_run mode, None otherwise.
        """
        return self._execution_record

    @property
    def working_dir(self) -> Path:
        """Return the working directory for the execution."""
        return self._execution_root

    @property
    def _execution_root(self) -> Path:
        """Get the root directory for this execution's files.

        Returns:
            Path to the execution-specific directory.
        """
        return execution_root(self._working_dir, self.execution_rid)

    @property
    def _asset_root(self) -> Path:
        """Get the root directory for asset files.

        Returns:
            Path to the asset directory within the execution.
        """
        return asset_root(self._working_dir, self.execution_rid)

    @property
    def database_catalog(self) -> DerivaMLBagView | None:
        """Get a catalog-like interface for downloaded datasets.

        Returns a DerivaMLBagView that implements the DerivaMLCatalog
        protocol, allowing the same code to work with both live catalogs
        and downloaded bags.

        This is useful for writing code that can operate on either a live
        catalog (via DerivaML) or on downloaded bags (via DerivaMLBagView).

        Returns:
            DerivaMLBagView wrapping the primary downloaded dataset's model,
            or None if no datasets have been downloaded.

        Example:
            >>> with ml.create_execution(config) as exe:  # doctest: +SKIP
            ...     if exe.database_catalog:  # doctest: +SKIP
            ...         db = exe.database_catalog  # doctest: +SKIP
            ...         # Use same interface as DerivaML
            ...         dataset = db.lookup_dataset("4HM")  # doctest: +SKIP
            ...         term = db.lookup_term("Diagnosis", "cancer")  # doctest: +SKIP
            ...     else:
            ...         # No datasets downloaded, use live catalog
            ...         pass
        """
        if not self._datasets_list:
            return None
        # Use the first dataset's model as the primary
        return DerivaMLBagView(self._datasets_list[0].model)

    @property
    def catalog(self) -> "DerivaML":
        """Get the live catalog (DerivaML) instance for this execution.

        This provides access to the live catalog for operations that require
        catalog connectivity, such as looking up datasets or other read operations.

        Returns:
            DerivaML: The live catalog instance.

        Example:
            >>> with ml.create_execution(config) as exe:  # doctest: +SKIP
            ...     # Use live catalog for lookups
            ...     existing_dataset = exe.catalog.lookup_dataset("1-ABC")  # doctest: +SKIP
        """
        return self._ml_object

    def add_features(self, features: list[FeatureRecord]) -> int:
        """Stage feature records for batch insertion on execution completion.

        Writes the records to the execution's SQLite ``execution_state__feature_records`` table
        with status ``Pending``. The records are not sent to ermrest immediately
        — they are flushed in a single batch, **after asset upload**, when the
        execution completes successfully. This integrates with the SQLite
        execution-state design so crash-resume works for feature writes without
        extra plumbing.

        Records with ``Execution`` unset are auto-filled with this execution's
        RID. All records in a single call must share one feature definition;
        mixing features raises ``DerivaMLValidationError`` and nothing is staged.

        **Provenance requirement.** This is the only way to write feature values
        — ``DerivaML.add_features`` is retired (see the retired-API error shims).
        For "admin fixup" cases, create a short-lived execution with an
        appropriate ``Workflow_Type`` (e.g. ``Manual_Correction``) and call
        ``exe.add_features`` inside it. The three-extra-lines give you a real
        audit trail, which is the point.

        Args:
            features: List of FeatureRecord instances to stage. All must share
                the same feature definition. Create instances via
                ``Feature.feature_record_class()``.

        Returns:
            Number of records staged.

        Raises:
            ValueError: features list is empty.
            DerivaMLValidationError: Records do not share a single feature
                definition.
            DerivaMLDataError: SQLite staging write failed.

        Example:
            >>> feature = ml.lookup_feature("Image", "Glaucoma")  # doctest: +SKIP
            >>> RecordClass = feature.feature_record_class()  # doctest: +SKIP
            >>> records = [  # doctest: +SKIP
            ...     RecordClass(Image="IMG-1", Glaucoma="Normal"),  # doctest: +SKIP
            ...     RecordClass(Image="IMG-2", Glaucoma="Severe"),  # doctest: +SKIP
            ... ]  # doctest: +SKIP
            >>> with ml.create_execution(cfg) as exe:  # doctest: +SKIP
            ...     exe.add_features(records)     # staged, not yet in ermrest
            ...     # ... more work ...
            >>> # on __exit__: staged records flushed to ermrest after assets
        """
        from deriva_ml.core.exceptions import DerivaMLValidationError

        if not features:
            raise ValueError("features list must not be empty")

        # All records must share one feature definition
        feature_defs = {type(f).feature for f in features if type(f).feature is not None}
        if len(feature_defs) > 1:
            raise DerivaMLValidationError(
                f"add_features called with records from {len(feature_defs)} different "
                f"feature definitions; all records must share one feature."
            )

        # Auto-fill Execution RID on records that don't have it
        for f in features:
            if f.Execution is None:
                f.Execution = self.execution_rid

        # Stage to SQLite — durability boundary is the write-through here.
        feat_class = type(features[0])
        feat = feat_class.feature
        schema_name = feat.feature_table.schema.name
        table_name = feat.feature_table.name
        qualified = f"{schema_name}.{table_name}"
        feature_name = feat.feature_name
        target_table_name = feat.target_table.name

        # Stage every record in a single SQLite transaction. The
        # legacy per-record loop wrapped each ``stage_feature_record``
        # call in its own ``engine.begin()`` block (one WAL fsync per
        # record); for a multi-thousand-record ``add_features`` call
        # that's N serialized fsyncs. The bulk path collapses to one.
        # See ``ManifestStore.stage_feature_records``.
        records_json = [f.model_dump_json() for f in features]
        self._manifest_store.stage_feature_records(
            execution_rid=self.execution_rid,
            feature_table=qualified,
            feature_name=feature_name,
            target_table=target_table_name,
            records_json=records_json,
        )
        return len(features)

    @validate_call(config=VALIDATION_CONFIG)
    def download_dataset_bag(self, dataset: DatasetSpec) -> DatasetBag:
        """Downloads and materializes a dataset for use in the execution.

        Downloads the specified dataset as a BDBag and materializes it in the execution's
        working directory. The dataset version is determined by the DatasetSpec.

        Args:
            dataset: Specification of the dataset to download, including version and
                materialization options.

        Returns:
            DatasetBag: Object exposing, among others:
                - ``path``: local filesystem path to the materialized bag
                - ``dataset_rid``: the dataset's Resource Identifier
                - ``current_version``: the resolved dataset version

        Raises:
            DerivaMLException: If download or materialization fails.

        Example:
            >>> spec = DatasetSpec(rid="1-abc123", version="1.2.0")  # doctest: +SKIP
            >>> bag = execution.download_dataset_bag(spec)  # doctest: +SKIP
            >>> print(f"Downloaded {bag.dataset_rid} to {bag.path}")  # doctest: +SKIP
        """
        return self._ml_object.download_dataset_bag(dataset)

    def update_status(
        self,
        target: "ExecutionStatus",
        *,
        error: str | None = None,
    ) -> None:
        """Transition this execution to a new status.

        Thin wrapper around state_machine.transition() that validates
        against ALLOWED_TRANSITIONS, writes the SQLite registry, and syncs
        to the catalog when online.

        Args:
            target: Target ExecutionStatus enum member.
            error: For Failed/Aborted transitions, a human-readable error
                message written to the `error` column. On a non-terminal
                transition, error is ignored and a warning is logged.

        Raises:
            InvalidTransitionError: If the (current, target) pair is not in
                ALLOWED_TRANSITIONS.
            DerivaMLStateInconsistency: If state_machine's catalog sync
                detects divergence.

        Example:
            >>> exe.update_status(ExecutionStatus.Running)  # doctest: +SKIP
            >>> exe.update_status(ExecutionStatus.Failed, error="Network timeout")  # doctest: +SKIP
        """
        store = self._ml_object.workspace.execution_state_store()
        row = store.get_execution(self.execution_rid)
        if row is None:
            raise DerivaMLException(f"Execution {self.execution_rid} not in workspace registry")
        current = ExecutionStatus(row["status"])

        extra_fields: dict = {}
        # Terminal = Failed, Aborted.
        if target in (ExecutionStatus.Failed, ExecutionStatus.Aborted):
            if error is not None:
                extra_fields["error"] = error
        elif error is not None:
            logger.warning(
                "error= ignored on non-terminal transition to %s: %s",
                target.value,
                error,
            )

        transition(
            store=store,
            catalog=self._ml_object.catalog if self._ml_object._mode is ConnectionMode.online else None,
            execution_rid=self.execution_rid,
            current=current,
            target=target,
            mode=self._ml_object._mode,
            extra_fields=extra_fields,
        )

    def execution_start(self) -> None:
        """Marks the execution as started.

        Records the start time in SQLite and transitions the execution's
        status from ``Created`` to ``Running`` via the state machine
        (the same path the context-manager ``__enter__`` uses). This
        should be called before beginning the main execution work — its
        non-context-manager counterpart for code paths that can't use
        ``with ml.create_execution(...) as exe:`` (e.g., the multirun
        parent execution managed by an ``atexit`` handler).

        Pairs with ``execution_stop()`` which transitions Running → Stopped.

        Raises:
            InvalidTransitionError: If the execution is not currently in
                ``ExecutionStatus.Created``.

        Example:
            >>> execution.execution_start()  # doctest: +SKIP
            >>> try:  # doctest: +SKIP
            ...     # Run analysis
            ...     execution.execution_stop()  # doctest: +SKIP
            ... except Exception:
            ...     execution.update_status(ExecutionStatus.Failed, error="Analysis error")  # doctest: +SKIP
        """
        from datetime import timezone

        self._logger.info("Start execution...")

        # Dry-run executions don't have a SQLite registry row — there's
        # nothing to transition and the status read-through returns a
        # sentinel. Skip the state-machine call entirely.
        if self._dry_run:
            return

        # Transition Created → Running through the state machine, writing
        # start_time atomically with the status change so a crash between
        # the two can't leave the row inconsistent. Mirrors __enter__ —
        # the only difference is that this path is invoked imperatively
        # by callers that don't (or can't) use the context manager.
        current = self.status
        transition(
            store=self._ml_object.workspace.execution_state_store(),
            catalog=(self._ml_object.catalog if self._ml_object._mode is ConnectionMode.online else None),
            execution_rid=self.execution_rid,
            current=current,
            target=ExecutionStatus.Running,
            mode=self._ml_object._mode,
            extra_fields={"start_time": datetime.now(timezone.utc)},
        )

    def execution_stop(self) -> None:
        """Marks the execution as stopped (algorithm finished successfully).

        Computes the wall-clock duration against ``start_time`` and
        transitions Running → Stopped through the state machine,
        writing ``stop_time`` and ``duration`` atomically with the
        status change. Online callers see a single catalog PUT that
        carries both Status and Duration (the historical second
        catalog write is gone — audit §4.5).

        This should be called after all execution work is finished;
        upload of outputs is a separate phase that moves status from
        Stopped → Pending_Upload → Uploaded.

        Example:
            >>> try:  # doctest: +SKIP
            ...     # Run analysis
            ...     execution.execution_stop()  # doctest: +SKIP
            ... except Exception:
            ...     execution.update_status(ExecutionStatus.Failed, error="Analysis error")  # doctest: +SKIP
        """
        from datetime import timezone

        now = datetime.now(timezone.utc)

        # Compute algorithm duration against start_time. Falls back to
        # "0H 0min 0.0sec" if start_time is missing (shouldn't happen
        # in practice — Running → Stopped requires __enter__ /
        # execution_start to have set start_time).
        duration_str = _format_duration(self.start_time, now)

        if self._dry_run:
            return

        # Single atomic transition: SQLite write (status + stop_time +
        # duration) followed by online catalog PUT (Status + Duration
        # via _catalog_body_for_execution). Replaces the historical
        # two-write design that left Duration vulnerable to a partial
        # failure between writes (audit §4.5).
        current = self.status
        transition(
            store=self._ml_object.workspace.execution_state_store(),
            catalog=(self._ml_object.catalog if self._ml_object._mode is ConnectionMode.online else None),
            execution_rid=self.execution_rid,
            current=current,
            target=ExecutionStatus.Stopped,
            mode=self._ml_object._mode,
            extra_fields={"stop_time": now, "duration": duration_str},
        )

    @validate_call(config=VALIDATION_CONFIG)
    def download_asset(
        self,
        asset_rid: RID,
        dest_dir: Path,
        update_catalog: bool = True,
        use_cache: bool = False,
        _asset_table: Any = None,
    ) -> AssetFilePath:
        """Download an asset from a URL and place it in a local directory.

        The file is written to ``dest_dir / asset_record["Filename"]``.
        Overwrites any existing file at that path, with a WARNING logged
        when the existing content is byte-different from the asset's
        expected MD5 (issue #181). Idempotent re-downloads — the existing
        file's md5 already matches the catalog's recorded MD5 — log
        nothing. Callers that need silent overwrites can accept the
        WARNING; callers that need genuine isolation should pass a unique
        ``dest_dir`` per asset. The canonical pattern is
        ``dest_dir = working_dir / 'downloads' / asset_rid``, which is
        what ``_initialize_execution`` uses internally so the
        platform-default download path is collision-free by construction.

        **Directional tagging.** Assets downloaded via this method are
        recorded as **inputs** of this execution (when
        ``update_catalog=True``, the default). deriva-ml auto-adds the
        ``Input_File`` Asset_Type tag and writes ``Asset_Role="Input"``
        on the ``{Asset}_Execution`` row. The asset's pre-existing
        content tags (e.g., ``Model_File`` if it was a prior
        execution's output) are preserved — the directional tag is
        additive, not a replacement. This is symmetric with the
        ``Output_File`` tag added when assets are uploaded via
        :meth:`asset_file_path` + :meth:`commit_output_assets`.
        See the "How execution-asset roles work" section of the
        execution user guide for the full contract.

        Args:
            asset_rid: RID of the asset.
            dest_dir: Destination directory for the asset. When ``Filename``
                may collide across concurrent ``download_asset`` calls,
                pass a unique directory per asset to avoid the WARNING and
                the silent overwrite it guards against.
            update_catalog: Whether to write the ``{Asset}_Execution``
                row (``Asset_Role="Input"``) and the ``Input_File``
                Asset_Type tag. Default ``True`` — the input-role
                contract requires it. Pass ``False`` only for ad-hoc
                downloads outside an execution-tracking context.
            use_cache: If True, check the cache directory for a previously downloaded copy
                with a matching MD5 checksum before downloading. Cached copies are stored
                in ``cache_dir/assets/{rid}_{md5}/`` and symlinked into the destination.
            _asset_table: Internal — pre-resolved Table object for this RID. When supplied
                (typically from ``_initialize_execution``'s batched ``resolve_rids`` call)
                skips the per-asset ``resolve_rid`` round-trip. Underscore-prefixed because
                callers should not rely on this; pass through the public ``resolve_rid``
                path otherwise.

        Returns:
            An AssetFilePath with the path to the downloaded (or cached) asset file.
            ``AssetFilePath.file_name`` is the canonical access path — read from it
            rather than hand-constructing a path from the asset table or filename.
        """
        from deriva_ml.execution.asset_upload import download_asset as _download_asset

        return _download_asset(
            self,
            asset_rid,
            dest_dir,
            update_catalog=update_catalog,
            use_cache=use_cache,
            _asset_table=_asset_table,
            asset_type_vocab_term=MLVocab.asset_type,
            check_overwrite_safe_fn=_check_overwrite_safe,
        )

    @validate_call(config=VALIDATION_CONFIG)
    def commit_output_assets(
        self,
        clean_folder: bool | None = None,
        progress_callback: Callable[[UploadProgress], None] | None = None,
    ) -> UploadReport:
        """Commit this execution's output assets to the catalog.

        Single per-execution upload entry point (ADR-0009). Reads the
        asset manifest, uploads each file to the catalog's Hatrac
        object store, and inserts ``{Asset}_Execution`` association
        records linking each uploaded asset to this execution with the
        ``Output`` role. Brackets the work with the
        ``Pending_Upload → Uploaded`` (success) or
        ``Pending_Upload → Failed`` (exception) state-machine
        transition, records ``Upload_Duration`` in the SQLite registry,
        writes asset descriptions to the catalog, and optionally cleans
        the execution working folder.

        Call this method **after** exiting the execution context
        manager, not inside it. The context manager sets execution
        status to ``Stopped`` on exit; this method transitions
        ``Stopped → Pending_Upload → Uploaded`` (or ``Failed``).

        Idempotent: re-running after a successful upload (status
        ``Uploaded``, no pending assets) is a no-op that returns an
        empty report. Re-running after a partial failure resumes from
        the last known-good state — ``BagCatalogLoader``'s
        ``match_by_columns`` dedup makes row inserts idempotent at the
        catalog.

        The method raises on failure. Failure isolation is the batch
        caller's job (:meth:`DerivaML.commit_pending_executions`), not
        the per-execution call's.

        **Directional tagging.** Every asset committed by this call
        gets ``Asset_Role="Output"`` on its ``{Asset}_Execution`` row
        and the ``Output_File`` Asset_Type tag (auto-added by
        deriva-ml, in addition to any content tags the caller passed
        via :meth:`asset_file_path(..., asset_types=...)`). This is
        symmetric with the ``Input_File`` tag added by
        :meth:`download_asset`. See the "How execution-asset roles
        work" section of the execution user guide for the full
        contract.

        Args:
            clean_folder: Whether to delete output folders after
                upload. If None (default), uses the DerivaML instance's
                ``clean_execution_dir`` setting. Pass True/False to
                override for this specific execution.
            progress_callback: Optional callback function to receive
                upload progress updates. Called with UploadProgress
                objects containing file name, bytes uploaded, total
                bytes, percent complete, phase, and status message.

        Returns:
            UploadReport with ``execution_rids=[self.execution_rid]``
            and per-(schema, table) upload counts. ``total_uploaded``
            is the sum of asset rows committed across all asset tables
            this execution touched. For dry-run executions, returns an
            empty report.

        Raises:
            DerivaMLUploadError: If any file upload fails. Partial
                uploads are recorded in the manifest so the upload can
                be resumed.
            DerivaMLReadOnlyError: If the catalog connection is
                read-only.

        Example:
            >>> with ml.create_execution(cfg) as exe:  # doctest: +SKIP
            ...     path = exe.asset_file_path("Model", "model.pt")  # doctest: +SKIP
            >>> report = exe.commit_output_assets()  # doctest: +SKIP
            >>> print(report.total_uploaded, "assets committed")  # doctest: +SKIP
        """
        from deriva_ml.execution.asset_upload import (
            commit_output_assets as _commit_output_assets,
        )

        result = _commit_output_assets(
            self,
            clean_folder=clean_folder,
            progress_callback=progress_callback,
            pending_upload_status=ExecutionStatus.Pending_Upload,
            uploaded_status=ExecutionStatus.Uploaded,
            failed_status=ExecutionStatus.Failed,
            running_status=ExecutionStatus.Running,
            stopped_status=ExecutionStatus.Stopped,
            format_duration_fn=_format_duration,
        )

        # Build UploadReport from the free function's per-table dict.
        # Each value is a list of AssetFilePath; the count is the
        # number of asset rows committed for that table.
        total_uploaded = sum(len(v) for v in result.values())
        per_table = {fqn: {"uploaded": len(v), "failed": 0} for fqn, v in result.items()}
        return UploadReport(
            execution_rids=[self.execution_rid],
            total_uploaded=total_uploaded,
            total_failed=0,
            per_table=per_table,
            errors=[],
        )

    def _bag_commit_upload(
        self,
        *,
        progress_callback: Callable[[UploadProgress], None] | None = None,
    ) -> dict[str, list[AssetFilePath]]:
        """Upload pending execution outputs via the bag pipeline.

        Thin delegate to ``asset_upload.bag_commit_upload``;
        see that helper for the bag-build → bag-load → manifest-mark
        flow.
        """
        from deriva_ml.execution.asset_upload import bag_commit_upload

        return bag_commit_upload(self, progress_callback=progress_callback)

    def _clean_folder_contents(self, folder_path: Path, remove_folder: bool = True):
        """Clean up folder contents and optionally the folder itself.

        Thin delegate to ``asset_upload.clean_folder_contents``.
        The helper doesn't need ``self`` at all — it's a pure
        filesystem op that lived on ``Execution`` for legacy
        reasons. Preserved here as an instance method so the
        existing in-class call sites
        (``commit_output_assets``, ``__exit__``,
        ``execution_stop``) still read naturally.
        """
        from deriva_ml.execution.asset_upload import clean_folder_contents

        clean_folder_contents(
            folder_path,
            remove_folder=remove_folder,
            logger=self._logger,
        )

    def _update_asset_execution_table(
        self,
        uploaded_assets: dict[str, list[AssetFilePath]],
        asset_role: str = "Output",
    ) -> None:
        """Link assets to this execution and auto-tag them by role.

        Thin delegate to ``asset_upload.update_asset_execution_table``;
        see that helper for the per-branch (Input/Output)
        logic.

        **Audit ledger note (Output branch is NOT dead):**
        The 2026-05-22 audit recommended dropping the Output
        branch as "dead in production." That recommendation
        is rejected — ``Asset_Role`` Input vs Output is real
        public-API behaviour (``execution.list_assets(asset_role=...)``).
        A prior pass eliminated this in error; do not repeat
        that mistake. The bag-commit Output flow at
        ``bag_commit._add_asset_rows_to_bag`` writes the same
        rows for bag-pipeline assets; this branch handles
        non-bag callers.
        """
        from deriva_ml.execution.asset_upload import update_asset_execution_table

        update_asset_execution_table(
            self,
            uploaded_assets,
            asset_role=asset_role,
            asset_role_vocab_term=MLVocab.asset_role,
            input_file_tag=ExecAssetType.input_file.value,
            output_file_tag=ExecAssetType.output_file.value,
            asset_type_path_fn=asset_type_path,
        )

    @validate_call(config=VALIDATION_CONFIG)
    def asset_file_path(
        self,
        asset_name: str,
        file_name: str | Path,
        asset_types: list[str] | str | None = None,
        copy_file=False,
        rename_file: str | None = None,
        metadata=None,
        description: str | None = None,
        **kwargs,
    ) -> AssetFilePath:
        """Register a file for upload and return a path to write to.

        This routine has three modes depending on whether file_name refers to an existing file:
        1. **New file**: file_name doesn't exist — returns a path to write to.
        2. **Symlink**: file_name exists, copy_file=False — symlinks into staging.
        3. **Copy**: file_name exists, copy_file=True — copies into staging.

        Files are stored in a flat per-table directory (``assets/{AssetTable}/``).
        Metadata is tracked in a persistent JSON manifest for crash safety.
        Metadata can be set at registration time via the ``metadata`` parameter
        (an AssetRecord or dict) or incrementally after via the returned
        AssetFilePath's ``metadata`` property.

        Thin delegate to ``asset_upload.asset_file_path``;
        see that helper for the per-mode logic and the
        ``asset_types is None`` vs explicit-empty-list
        normalization.

        **Directional tagging.** Files registered via this method are
        uploaded as **outputs** of this execution. After
        :meth:`commit_output_assets` runs, deriva-ml auto-adds
        the ``Output_File`` Asset_Type tag to every uploaded asset
        (alongside any content tags you passed in ``asset_types``).
        You don't pass ``Output_File`` yourself — it's framework-
        supplied, deduplicated if explicit, and symmetric with the
        ``Input_File`` tag added by :meth:`download_asset`. The
        ``{Asset}_Execution`` row gets ``Asset_Role="Output"``.
        See the "How execution-asset roles work" section of the
        execution user guide for the full contract.

        Args:
            asset_name: Name of the asset table. Must be a valid asset table.
            file_name: Name of file to be uploaded, or path to an existing file.
            asset_types: Content-classification tags from the Asset_Type
                vocabulary (e.g., ``["Model_File"]``,
                ``["Segmentation_Mask"]``). The directional
                ``Output_File`` tag is added automatically — do not
                pass it explicitly. Defaults to ``asset_name``.
            copy_file: Whether to copy the file rather than creating a symbolic link.
            rename_file: If provided, rename the file during staging.
            metadata: An AssetRecord instance or dict of metadata column values.
            description: Optional description for the asset record.
            **kwargs: Additional metadata values (legacy support, merged with metadata).

        Returns:
            AssetFilePath bound to the manifest for write-through metadata updates.

        Raises:
            DerivaMLException: If the asset table doesn't exist.
            DerivaMLValidationError: If asset_types contains invalid terms.
        """
        from deriva_ml.execution.asset_upload import asset_file_path as _asset_file_path

        return _asset_file_path(
            self,
            asset_name,
            file_name,
            asset_types=asset_types,
            copy_file=copy_file,
            rename_file=rename_file,
            metadata=metadata,
            description=description,
            asset_type_vocab_term=MLVocab.asset_type,
            flat_asset_dir_fn=flat_asset_dir,
            asset_type_path_fn=asset_type_path,
            legacy_kwargs=kwargs,
        )

    def metrics_file(self, filename: str = "metrics.jsonl") -> AssetFilePath:
        """Return a path for writing training-metric records.

        Thin sugar over ``asset_file_path(MLAsset.execution_metadata, ...)``
        that stamps the file with ``asset_types=Metrics_File`` so the
        catalog's ``Execution_Metadata.Type`` column honestly describes
        the file's purpose. The file registers with the execution's asset
        manifest on first call and uploads as part of
        ``commit_output_assets()``.

        The file itself is plain text; callers decide the format. The
        default filename ``metrics.jsonl`` suggests one JSON record per
        line — the simplest shape that lets a downstream reader page
        through the file without loading the whole thing into memory —
        but CSV, YAML, or a single JSON object also work as long as the
        readback code knows the format.

        Repeated calls inside the same execution return the **same**
        AssetFilePath (registered once in the manifest), so append-style
        writes across an epoch loop are safe::

            with ml.create_execution(cfg) as exe:
                for epoch in range(num_epochs):
                    train_loss = train_one_epoch(...)
                    val_loss = evaluate(...)
                    with exe.metrics_file().open("a") as f:
                        json.dump(
                            {"epoch": epoch, "train_loss": train_loss,
                             "val_loss": val_loss},
                            f,
                        )
                        f.write("\\n")
            exe.commit_output_assets()

        Args:
            filename: Name of the metrics file inside the execution's
                Execution_Metadata staging area. Defaults to
                ``"metrics.jsonl"``. Override to distinguish multiple
                metric streams (e.g. ``"train_metrics.jsonl"`` +
                ``"eval_metrics.jsonl"``) — each distinct filename
                becomes a separate Execution_Metadata asset on upload.

        Returns:
            AssetFilePath for the metrics file. Use its ``.open(...)``
            method to read, write, or append; the manifest tracks the
            file for upload regardless of how you write to it.

        Raises:
            DerivaMLException: If the Execution_Metadata table is not
                present in the catalog schema (should never happen in a
                correctly-initialized catalog).
            DerivaMLValidationError: If the ``Metrics_File`` term is
                missing from the Asset_Type vocabulary (i.e. an old
                catalog predating this feature; run ``create_ml_schema``
                or ``initialize_ml_schema`` once to seed the term).

        Example:
            >>> from deriva_ml.core.enums import MLAsset, ExecMetadataType  # doctest: +SKIP
            >>> MLAsset.execution_metadata.value  # doctest: +SKIP
            'Execution_Metadata'
            >>> ExecMetadataType.metrics_file.value  # doctest: +SKIP
            'Metrics_File'

            >>> # Catalog-dependent end-to-end flow:
            >>> import json  # doctest: +SKIP
            >>> with ml.create_execution(cfg) as exe:  # doctest: +SKIP
            ...     with exe.metrics_file().open("a") as f:  # doctest: +SKIP
            ...         json.dump({"epoch": 0, "val_loss": 0.23}, f)  # doctest: +SKIP
            ...         f.write("\\n")  # doctest: +SKIP
            >>> exe.commit_output_assets()  # doctest: +SKIP
        """
        from deriva_ml.execution.asset_upload import metrics_file as _metrics_file

        return _metrics_file(
            self,
            filename,
            execution_metadata_asset_name=MLAsset.execution_metadata,
            metrics_file_asset_type=ExecMetadataType.metrics_file.value,
        )

    def _get_manifest(self) -> AssetManifest:
        """Get or create the asset manifest for this execution."""
        if not hasattr(self, "_manifest") or self._manifest is None:
            ws = self._ml_object.workspace
            self._manifest = AssetManifest(ws.manifest_store(), self.execution_rid)
        return self._manifest

    @property
    def _manifest_store(self) -> "ManifestStore":
        """Return the ManifestStore for this workspace.

        Used by ``add_features`` to stage feature records to SQLite; the
        bag-commit path reads them back via
        ``bag_commit._add_staged_feature_rows_to_bag`` for the catalog insert.
        """
        return self._ml_object.workspace.manifest_store()

    def table_path(self, table: str) -> Path:
        """Return a local file path to a CSV to add values to a table on upload.

        Args:
            table: Name of table to be uploaded.

        Returns:
            Pathlib path to the file in which to place table values.

        Raises:
            DerivaMLException: If ``table`` is not found in any domain schema.

        Example:
            >>> path = exe.table_path("Measurement")  # doctest: +SKIP
            >>> with path.open("w") as f:  # doctest: +SKIP
            ...     writer = csv.DictWriter(f, fieldnames=["Subject", "Score"])  # doctest: +SKIP
            ...     writer.writerow({"Subject": "IMG-1", "Score": 0.95})  # doctest: +SKIP
        """
        # Find which domain schema contains this table
        table_schema = None
        for domain_schema in self._ml_object.domain_schemas:
            if domain_schema in self._model.schemas:
                if table in self._model.schemas[domain_schema].tables:
                    table_schema = domain_schema
                    break

        if table_schema is None:
            raise DerivaMLException("Table '{}' not found in any domain schema".format(table))

        return table_path(self._working_dir, schema=table_schema, table=table)

    def execute(self) -> Execution:
        """Return self so this Execution can be used as a context manager.

        Per spec §2.8, the lifecycle transitions (created → running →
        stopped/failed) live on ``__enter__`` / ``__exit__``. ``execute()``
        itself is a no-op that simply returns ``self`` so usage reads
        naturally as ``with exe.execute() as e: ...``.

        Returns:
            This Execution instance, which is itself a context manager.

        Example:
            >>> with exe.execute() as e:  # doctest: +SKIP
            ...     # e.status is ExecutionStatus.Running
            ...     pass
            >>> # e.status is ExecutionStatus.Stopped (or failed on exception)
        """
        return self

    def list_input_datasets(self) -> list[Dataset]:
        """List all datasets that were inputs to this execution.

        Excludes any dataset this execution itself *produced* — the
        ``Dataset_Execution`` association table has no role column to
        distinguish inputs from outputs, so we infer authorship from
        each dataset's ``Dataset_Version.Execution`` link.

        Returns:
            List of Dataset objects that were used as inputs.

        Example:
            >>> for ds in execution.list_input_datasets():  # doctest: +SKIP
            ...     print(f"Input: {ds.dataset_rid} - {ds.description}")  # doctest: +SKIP
        """
        if self._execution_record is not None:
            return self._execution_record.list_input_datasets()

        # Fallback for dry-run mode (no execution record bound).
        # Delegates to the shared helper so the dry-run path
        # and the canonical ``ExecutionRecord.list_input_datasets``
        # path stay in lockstep — pre-fix they re-implemented the
        # same producer-filter walk in two places.
        from deriva_ml.execution._helpers import list_input_datasets as _list_input_datasets

        return _list_input_datasets(
            ml_instance=self._ml_object,
            execution_rid=self.execution_rid,
        )

    def list_assets(self, asset_role: str | None = None) -> list["Asset"]:
        """List all assets that were inputs or outputs of this execution.

        Args:
            asset_role: Optional filter: "Input" or "Output". If None, returns all.

        Returns:
            List of Asset objects associated with this execution.

        Example:
            >>> inputs = execution.list_assets(asset_role="Input")  # doctest: +SKIP
            >>> outputs = execution.list_assets(asset_role="Output")  # doctest: +SKIP
        """
        if self._execution_record is not None:
            return self._execution_record.list_assets(asset_role=asset_role)

        # Fallback for dry-run mode (no execution record bound).
        # Delegates to the shared helper so the dry-run path
        # and the canonical ``ExecutionRecord.list_assets`` path
        # stay in lockstep — pre-fix the dry-run path only
        # walked ``Execution_Asset_Execution`` while the
        # canonical path walked every ``*_Execution`` association
        # across all schemas. That mismatch was invisible until a
        # dry-run scenario exercised assets in a domain-schema
        # table other than ``Execution_Asset``; now both paths
        # do the full walk.
        from deriva_ml.execution._helpers import list_assets as _list_assets

        return _list_assets(
            ml_instance=self._ml_object,
            execution_rid=self.execution_rid,
            asset_role=asset_role,
        )

    @validate_call(config=VALIDATION_CONFIG)
    def create_dataset(
        self,
        dataset_types: str | list[str] | None = None,
        version: DatasetVersion | str | None = None,
        description: str = "",
    ) -> Dataset:
        """Create a new dataset tracked to this execution.

        Creates a ``Dataset`` catalog record linked to this execution as its
        provenance. The dataset is immediately usable for adding members and
        incrementing versions.

        Args:
            dataset_types: One or more dataset type vocabulary term names to apply.
                Must be pre-registered via ``add_dataset_type``. Pass ``None``
                or an empty list to create an untyped dataset.
            description: Human-readable description of the dataset. Stored in
                the catalog ``Dataset.Description`` column.
            version: Dataset version. Defaults to 0.1.0.

        Returns:
            A ``Dataset`` instance bound to the newly created catalog record.

        Raises:
            DerivaMLInvalidTerm: If any name in ``dataset_types`` is not a
                registered ``Dataset_Type`` vocabulary term.
            DerivaMLExecutionError: If the execution context is no longer active.

        Example:
            >>> with ml.create_execution(cfg) as exe:  # doctest: +SKIP
            ...     ds = exe.create_dataset(  # doctest: +SKIP
            ...         dataset_types=["training"],  # doctest: +SKIP
            ...         description="Training images v1",  # doctest: +SKIP
            ...     )  # doctest: +SKIP
        """
        return Dataset.create_dataset(
            ml_instance=self._ml_object,
            execution_rid=self.execution_rid,
            dataset_types=dataset_types,
            version=version,
            description=description,
        )

    def add_input_dataset(self, dataset_rid: RID, version: DatasetVersion | str | None = None) -> None:
        """Record an existing dataset as an *input* consumed by this execution.

        Writes a single ``Dataset_Execution`` association row linking
        ``dataset_rid`` to this execution. Because this execution did
        not *author* ``dataset_rid`` (its ``Dataset_Version.Execution``
        link points at whichever execution created it), the
        input/output inference used by :meth:`list_input_datasets`
        classifies it as an **input** — a consume edge — not an output.

        This is the counterpart of :meth:`create_dataset` (which records
        an *output*). Use it when an execution reads a dataset it did not
        produce and you want that consumption recorded as walkable
        provenance (so :meth:`list_input_datasets` and lineage walks can
        reach the consumed dataset), *without* the bag download that
        declaring the dataset in ``ExecutionConfiguration.datasets``
        would trigger. The most common caller is
        :func:`deriva_ml.dataset.split.split_dataset`, which records its
        source dataset as an input of the splitting execution.

        When ``version`` is supplied, the consumed version is recorded on
        the input edge via the ``Dataset_Execution.Dataset_Version`` FK
        (resolved through :meth:`_version_rid`). When ``version`` is
        ``None`` the ``Dataset_Version`` column is left NULL — fully
        backward-compatible with callers that pass only a RID.

        The link is idempotent: if ``dataset_rid`` is already associated
        with this execution, no duplicate row is inserted. In dry-run
        mode this is a no-op (the dry-run contract forbids catalog
        mutations).

        Args:
            dataset_rid: RID of the already-existing dataset that this
                execution consumed as an input.
            version: Optional consumed dataset version. May be a
                :class:`DatasetVersion` or a version string. When given,
                recorded on the input edge's ``Dataset_Version`` FK.

        Example:
            >>> with ml.create_execution(cfg) as exe:  # doctest: +SKIP
            ...     exe.add_input_dataset("1-ABC0")  # doctest: +SKIP
            ...     # "1-ABC0" now appears in exe.list_input_datasets()
        """
        if self._dry_run:
            return
        schema_path = self._ml_object.pathBuilder().schemas[self._ml_object.ml_schema]
        dataset_exec = schema_path.Dataset_Execution
        already_linked = {
            row["Dataset"]
            for row in dataset_exec.filter(dataset_exec.Execution == self.execution_rid).entities().fetch()
        }
        if dataset_rid in already_linked:
            return
        version_rid = self._ml_object._version_rid(dataset_rid, version) if version is not None else None
        dataset_exec.insert(
            [{"Dataset": dataset_rid, "Execution": self.execution_rid, "Dataset_Version": version_rid}]
        )

    @validate_call(config=VALIDATION_CONFIG)
    def add_files(
        self,
        files: Iterable[FileSpec],
        dataset_types: str | list[str] | None = None,
        description: str = "",
    ) -> "Dataset":
        """Adds files to the catalog with their metadata.

        Registers files in the catalog along with their metadata (MD5, length, URL) and associates them with
        specified file types.

        Args:
            files: File specifications containing MD5 checksum, length, and URL.
            dataset_types: One or more dataset type terms from File_Type vocabulary.
            description: Description of the files.

        Returns:
            RID: Dataset  that identifies newly added files. Will be nested to mirror original directory structure
            of the files.

        Raises:
            DerivaMLInvalidTerm: If file_types are invalid or execution_rid is not an execution record.

        Examples:
            Add a single file type:
                >>> files = [FileSpec(url="path/to/file.txt", md5="abc123", length=1000)]  # doctest: +SKIP
                >>> rids = exe.add_files(files, dataset_types="text")  # doctest: +SKIP

            Add multiple file types:
                >>> rids = exe.add_files(  # doctest: +SKIP
                ...     files=[FileSpec(url="image.png", md5="def456", length=2000)],  # doctest: +SKIP
                ...     dataset_types=["image", "png"],  # doctest: +SKIP
                ... )  # doctest: +SKIP
        """
        return self._ml_object.add_files(
            files=files,
            execution_rid=self.execution_rid,
            dataset_types=dataset_types,
            description=description,
        )

    # =========================================================================
    # Execution Nesting Methods
    # =========================================================================

    def add_nested_execution(
        self,
        nested_execution: "Execution | ExecutionRecord | RID",
        sequence: int | None = None,
    ) -> None:
        """Add a nested (child) execution to this execution.

        Creates a parent-child relationship between this execution and another.
        This is useful for grouping related executions, such as parameter sweeps
        or pipeline stages.

        Args:
            nested_execution: The child execution to add (Execution, ExecutionRecord, or RID).
            sequence: Optional ordering index (0, 1, 2...). Use None for parallel executions.

        Raises:
            DerivaMLException: If the association cannot be created.

        Example:
            >>> parent_exec = ml.create_execution(parent_config)  # doctest: +SKIP
            >>> child_exec = ml.create_execution(child_config)  # doctest: +SKIP
            >>> parent_exec.add_nested_execution(child_exec, sequence=0)  # doctest: +SKIP
        """
        if self._dry_run:
            return

        # Get the RID from the nested execution
        if isinstance(nested_execution, Execution):
            nested_rid = nested_execution.execution_rid
        elif isinstance(nested_execution, ExecutionRecord):
            nested_rid = nested_execution.execution_rid
        else:
            nested_rid = nested_execution

        # Delegate to ExecutionRecord if available
        if self._execution_record is not None:
            self._execution_record.add_nested_execution(nested_rid, sequence=sequence)
        else:
            # Fallback for cases without execution record
            from deriva_ml.execution._helpers import insert_nested_execution_link

            insert_nested_execution_link(
                ml_instance=self._ml_object,
                parent_rid=self.execution_rid,
                child_rid=nested_rid,
                sequence=sequence,
            )

    def is_nested(self) -> bool:
        """Check if this execution is nested within another execution.

        Hierarchy queries live on :class:`ExecutionRecord` only (per spec
        R2.1). This shortcut delegates to
        ``self._execution_record.is_nested()`` when available.

        Returns:
            True if this execution has at least one parent execution.

        Raises:
            DerivaMLException: If this Execution has no bound
                ExecutionRecord (e.g. a dry-run execution).
        """
        if self._execution_record is None:
            raise DerivaMLException(
                "is_nested requires a bound ExecutionRecord. Hierarchy queries are not available in dry-run mode."
            )
        return self._execution_record.is_nested()

    def is_parent(self) -> bool:
        """Check if this execution has nested child executions.

        Hierarchy queries live on :class:`ExecutionRecord` only (per spec
        R2.1). This shortcut delegates to
        ``self._execution_record.is_parent()`` when available.

        Returns:
            True if this execution has at least one nested execution.

        Raises:
            DerivaMLException: If this Execution has no bound
                ExecutionRecord (e.g. a dry-run execution).
        """
        if self._execution_record is None:
            raise DerivaMLException(
                "is_parent requires a bound ExecutionRecord. Hierarchy queries are not available in dry-run mode."
            )
        return self._execution_record.is_parent()

    def __str__(self):
        items = [
            f"caching_dir: {self._cache_dir}",
            f"_working_dir: {self._working_dir}",
            f"execution_rid: {self.execution_rid}",
            f"workflow_rid: {self.workflow_rid}",
            f"asset_paths: {self.asset_paths}",
            f"configuration: {self.configuration}",
        ]
        return "\n".join(items)

    def __repr__(self) -> str:
        """One-line summary including status and pending counts.

        Pending counts read SQLite — no caching. Example output::

            <Execution EXE-A status=stopped pending=15rows/2files>

        Omits the pending suffix when there are no pending rows or
        files. Always guards against exceptions — ``repr`` MUST NOT
        raise, so reads that would raise (e.g., the registry row is
        missing) degrade to ``<Execution EXE-A>``.

        Returns:
            Compact repr string suitable for logs and interactive use.
        """
        try:
            store = self._ml_object.workspace.execution_state_store()
            row = store.get_execution(self.execution_rid)
            if row is None:
                return f"<Execution {self.execution_rid} status=? (not in registry)>"
            counts = store.count_pending_by_kind(execution_rid=self.execution_rid)
            pending_part = ""
            if counts["pending_rows"] or counts["pending_files"]:
                pending_part = f" pending={counts['pending_rows']}rows/{counts['pending_files']}files"
            return f"<Execution {self.execution_rid} status={row['status']}{pending_part}>"
        except Exception:  # repr must not raise
            return f"<Execution {self.execution_rid}>"

    def __enter__(self) -> "Execution":
        """Begin the execution: status created → running.

        Context-manager wrapper around :meth:`execution_start`. The
        actual transition (Created → Running, with ``start_time``
        atomically set in the same SQLite write and an online-mode
        catalog sync) lives in ``execution_start``; this method just
        delegates so the imperative and context-manager paths share
        one implementation.

        Dry-run executions skip the transition entirely — there is no
        SQLite registry row for a dry-run (sentinel RID), so there is
        nothing to transition. ``start_time`` reads back as None for
        dry-runs.

        Returns:
            This Execution instance.

        Raises:
            InvalidTransitionError: If the execution is not currently
                in ``ExecutionStatus.Created``.

        Example:
            >>> with exe.execute() as e:  # doctest: +SKIP
            ...     e.status  # doctest: +SKIP
            <ExecutionStatus.Running>
        """
        self.execution_start()
        return self

    def __exit__(self, exc_type: Any, exc_value: Any, exc_tb: Any) -> bool:
        """End the execution: status running → stopped (clean) or failed.

        On clean exit, transitions to ``stopped``. On exception, transitions
        to ``failed`` and stores the exception message in the ``error``
        column. Per spec §2.12 / R6.3, returns False to propagate any
        exception (unlike the legacy ``__exit__`` which returned True to
        suppress). After the transition, emits an INFO log summarizing
        pending rows/files if any are still staged (the full
        ``PendingSummary`` render lands in Group G; this is the
        placeholder.)

        Args:
           exc_type: Exception type (or None on clean exit).
           exc_value: Exception value (or None on clean exit).
           exc_tb: Exception traceback (or None on clean exit).

        Returns:
           False — always. Any exception propagates to the caller.
        """
        from datetime import datetime, timezone

        if self._dry_run:
            # No SQLite row for dry-run executions; stop_time read-through
            # returns None. Log any exception before returning.
            if exc_value is not None:
                logging.error(
                    "Dry-run execution failed: %s: %s",
                    exc_type.__name__,
                    exc_value,
                )
            return False

        current = self.status
        now = datetime.now(timezone.utc)

        # Tolerate executions that have already advanced past Running by
        # the time __exit__ fires. The canonical pattern for the
        # context manager is "exit at Running → Stopped"; but it is
        # legal (and fixture code in demo_catalog.py does this) to
        # call commit_output_assets() inside the with block, which
        # advances Running → Stopped → Pending_Upload → Uploaded
        # before __exit__ is invoked. Forcing a Stopped/Failed
        # transition from a terminal state would crash the caller's
        # successful path on the way out. Leave terminal states alone
        # — the work is already done.
        if current in {
            ExecutionStatus.Stopped,
            ExecutionStatus.Pending_Upload,
            ExecutionStatus.Uploaded,
            ExecutionStatus.Failed,
            ExecutionStatus.Aborted,
        }:
            return False

        if exc_value is None:
            # Clean exit: delegate Running → Stopped to execution_stop() so
            # the duration computation + single-atomic-transition contract
            # (audit §4.5) is honored. The inline transition this replaced
            # wrote stop_time but not duration, leaving the catalog
            # Execution_Duration column null for every with-block exit —
            # see docs/bugs/2026-05-19-execution-exit-omits-duration.md.
            self.execution_stop()
        else:
            # Failed exit: write stop_time, error, AND duration so the
            # Execution_Duration column reflects how long the run got
            # before it crashed. Useful diagnostic when comparing failed
            # vs successful runs of the same workflow.
            duration_str = _format_duration(self.start_time, now)
            transition(
                store=self._ml_object.workspace.execution_state_store(),
                catalog=(self._ml_object.catalog if self._ml_object._mode is ConnectionMode.online else None),
                execution_rid=self.execution_rid,
                current=current,
                target=ExecutionStatus.Failed,
                mode=self._ml_object._mode,
                extra_fields={
                    "stop_time": now,
                    "duration": duration_str,
                    "error": f"{exc_type.__name__}: {exc_value}",
                },
            )

        # Emit the pending-summary INFO log per §2.12 / R6.3. Full
        # PendingSummary object lands in Group G; this is a placeholder.
        store = self._ml_object.workspace.execution_state_store()
        counts = store.count_pending_by_kind(execution_rid=self.execution_rid)
        if counts["pending_rows"] or counts["pending_files"]:
            logger.info(
                "[Execution %s] exited with pending: %d rows, %d files. Call exe.commit_output_assets() to flush.",
                self.execution_rid,
                counts["pending_rows"],
                counts["pending_files"],
            )

        if exc_value is not None:
            logging.error(
                "Execution %s failed: %s: %s",
                self.execution_rid,
                exc_type.__name__,
                exc_value,
            )

        # Propagate any exception.
        return False

    def abort(self) -> None:
        """Mark this execution as aborted.

        Legal from any non-terminal status (``created``, ``running``,
        ``stopped``, ``failed``). Pending rows are NOT discarded —
        the user can inspect them and decide whether to recover via
        ``resume_execution`` or discard via ``gc_executions``.

        Dry-run executions have no SQLite registry row, so abort() is
        a no-op for them.

        Raises:
            InvalidTransitionError: If the current status doesn't allow
                abort (e.g., status='uploaded' — terminal).

        Example:
            >>> exe = ml.resume_execution("EXE-A")  # doctest: +SKIP
            >>> exe.abort()  # doctest: +SKIP
            >>> exe.status  # doctest: +SKIP
            <ExecutionStatus.Aborted>
        """
        if self._dry_run:
            return

        transition(
            store=self._ml_object.workspace.execution_state_store(),
            catalog=(self._ml_object.catalog if self._ml_object._mode is ConnectionMode.online else None),
            execution_rid=self.execution_rid,
            current=self.status,
            target=ExecutionStatus.Aborted,
            mode=self._ml_object._mode,
        )

    def pending_summary(self) -> "PendingSummary":
        """Return a snapshot of pending upload state for this execution.

        Read-only; does not affect state. Safe to call from anywhere at
        any time, including from a separate process holding the same
        workspace.

        Returns:
            PendingSummary with per-table row and asset counts and
            diagnostic messages from any failed rows.

        Example:
            >>> summary = exe.pending_summary()  # doctest: +SKIP
            >>> if summary.has_pending:  # doctest: +SKIP
            ...     print(summary.render())  # doctest: +SKIP
        """
        from deriva_ml.execution.pending_summary import (
            PendingAssetCount,
            PendingRowCount,
            PendingSummary,
        )

        store = self._ml_object.workspace.execution_state_store()
        data = store.pending_summary_rows(execution_rid=self.execution_rid)
        return PendingSummary(
            execution_rid=self.execution_rid,
            rows=[PendingRowCount(**r) for r in data["rows"]],
            assets=[PendingAssetCount(**a) for a in data["assets"]],
            diagnostics=data["diagnostics"],
        )

catalog property

catalog: 'DerivaML'

Get the live catalog (DerivaML) instance for this execution.

This provides access to the live catalog for operations that require catalog connectivity, such as looking up datasets or other read operations.

Returns:

Name Type Description
DerivaML 'DerivaML'

The live catalog instance.

Example

with ml.create_execution(config) as exe: # doctest: +SKIP ... # Use live catalog for lookups ... existing_dataset = exe.catalog.lookup_dataset("1-ABC") # doctest: +SKIP

database_catalog property

database_catalog: DerivaMLBagView | None

Get a catalog-like interface for downloaded datasets.

Returns a DerivaMLBagView that implements the DerivaMLCatalog protocol, allowing the same code to work with both live catalogs and downloaded bags.

This is useful for writing code that can operate on either a live catalog (via DerivaML) or on downloaded bags (via DerivaMLBagView).

Returns:

Type Description
DerivaMLBagView | None

DerivaMLBagView wrapping the primary downloaded dataset's model,

DerivaMLBagView | None

or None if no datasets have been downloaded.

Example

with ml.create_execution(config) as exe: # doctest: +SKIP ... if exe.database_catalog: # doctest: +SKIP ... db = exe.database_catalog # doctest: +SKIP ... # Use same interface as DerivaML ... dataset = db.lookup_dataset("4HM") # doctest: +SKIP ... term = db.lookup_term("Diagnosis", "cancer") # doctest: +SKIP ... else: ... # No datasets downloaded, use live catalog ... pass

datasets property

datasets: 'DatasetCollection'

Input datasets as a RID-keyed mapping + iterable.

Replaces the previous list[DatasetBag] exposure (hard cutover per spec R5.1). The returned collection behaves like a Mapping[str, DatasetBag] (keyed by dataset_rid) and is also iterable, yielding DatasetBag values in insertion order.

Returns:

Type Description
'DatasetCollection'

A DatasetCollection wrapping the materialized

'DatasetCollection'

DatasetBag objects that were downloaded during

'DatasetCollection'

execution initialization.

Example

RID lookup (primary access pattern)

bag = exe.datasets["1-XYZ"] # doctest: +SKIP

Iterate bags in insertion order

for bag in exe.datasets: # doctest: +SKIP ... print(bag.dataset_rid) # doctest: +SKIP

Introspect which RIDs are present

rids = list(exe.datasets.keys()) # doctest: +SKIP

Count

n = len(exe.datasets) # doctest: +SKIP

Migration note

Callers that previously indexed by position (exe.datasets[0]) must switch to either list(exe.datasets)[0] or the RID-keyed lookup exe.datasets[rid].

error property

error: str | None

Last error message for this execution, read from SQLite.

Parallels status — no caching, every read hits the workspace registry. Populated by __exit__ when an exception occurs (see spec §2.8 / §2.12).

Returns:

Type Description
str | None

The error message string, or None if no error has been

str | None

recorded for this execution.

Raises:

Type Description
DerivaMLStateInconsistency

If the executions row for this rid is missing (gc'd or never created).

Example

with exe.execute(): # doctest: +SKIP ... raise RuntimeError("boom") # doctest: +SKIP exe.error # doctest: +SKIP 'RuntimeError: boom'

execution_record property

execution_record: ExecutionRecord | None

Get the ExecutionRecord for catalog operations.

Returns:

Type Description
ExecutionRecord | None

ExecutionRecord if not in dry_run mode, None otherwise.

start_time property

start_time: 'datetime | None'

Start time from SQLite, or None if not yet started.

Parallels status / error — no caching, every read hits the workspace registry. Populated by __enter__ when the execution transitions to running. Returned values are coerced to UTC-aware datetimes (SQLite may return naive values even though we store tz-aware).

Returns:

Type Description
'datetime | None'

Timezone-aware (UTC) datetime when the execution's

'datetime | None'

__enter__ ran, or None before.

Raises:

Type Description
DerivaMLStateInconsistency

If the executions row for this rid is missing (gc'd or never created, e.g. dry-run).

Example

exe = ml.resume_execution("EXE-A") # doctest: +SKIP if exe.start_time is not None: # doctest: +SKIP ... print(f"started at {exe.start_time}") # doctest: +SKIP

status property

status: 'ExecutionStatus'

Current execution status, read from SQLite on every access.

No caching — a mutation from another process (e.g., deriva-ml upload running in a shell) is visible on the next read.

Returns:

Type Description
'ExecutionStatus'

The ExecutionStatus value from the workspace registry.

Raises:

Type Description
DerivaMLStateInconsistency

If the executions row for this rid is missing (gc'd or never created).

Example

exe = ml.resume_execution("5-ABC") # doctest: +SKIP exe.status # doctest: +SKIP

stop_time property

stop_time: 'datetime | None'

Stop time from SQLite, or None if not yet stopped/failed.

Parallels status / error — no caching, every read hits the workspace registry. Populated by __exit__ on either clean stop or exception (see spec §2.8 / §2.12). Returned values are coerced to UTC-aware datetimes.

Returns:

Type Description
'datetime | None'

Timezone-aware (UTC) datetime when the execution's

'datetime | None'

__exit__ ran, or None if still running.

Raises:

Type Description
DerivaMLStateInconsistency

If the executions row for this rid is missing.

Example

exe = ml.resume_execution("EXE-A") # doctest: +SKIP if exe.stop_time is not None: # doctest: +SKIP ... print(f"stopped at {exe.stop_time}") # doctest: +SKIP

uploaded_assets property

uploaded_assets: dict[
    str, list[AssetFilePath]
]

Assets this execution has uploaded, read from the asset manifest.

Reads the manifest on every access — no in-memory cache. The returned dict carries every entry whose status is uploaded across the manifest's lifetime, regardless of which commit_output_assets() call produced it. Each value is a list of :class:AssetFilePath objects giving the leased asset_rid and file_name for the entry.

Returns:

Type Description
dict[str, list[AssetFilePath]]

Map of "{schema}/{table}" → list of

dict[str, list[AssetFilePath]]

class:AssetFilePath. Empty dict for dry-run executions

dict[str, list[AssetFilePath]]

and for executions that haven't uploaded anything yet.

dict[str, list[AssetFilePath]]

Never None.

Note

Until the Phase 3 cleanup landed (audit §A.8) this was an instance attribute holding the most-recent call's return value. The manifest is now the source of truth; the property returns the full manifest's uploaded entries. Callers that need the per-call subset should use the return value of commit_output_assets() directly.

Example

with ml.create_execution(cfg) as exe: # doctest: +SKIP ... pass # doctest: +SKIP report = exe.commit_output_assets() # doctest: +SKIP

After commit, the property reflects the manifest:

sum(len(v) for v in exe.uploaded_assets.values()) >= report.total_uploaded # doctest: +SKIP True

working_dir property

working_dir: Path

Return the working directory for the execution.

__enter__

__enter__() -> 'Execution'

Begin the execution: status created → running.

Context-manager wrapper around :meth:execution_start. The actual transition (Created → Running, with start_time atomically set in the same SQLite write and an online-mode catalog sync) lives in execution_start; this method just delegates so the imperative and context-manager paths share one implementation.

Dry-run executions skip the transition entirely — there is no SQLite registry row for a dry-run (sentinel RID), so there is nothing to transition. start_time reads back as None for dry-runs.

Returns:

Type Description
'Execution'

This Execution instance.

Raises:

Type Description
InvalidTransitionError

If the execution is not currently in ExecutionStatus.Created.

Example

with exe.execute() as e: # doctest: +SKIP ... e.status # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
def __enter__(self) -> "Execution":
    """Begin the execution: status created → running.

    Context-manager wrapper around :meth:`execution_start`. The
    actual transition (Created → Running, with ``start_time``
    atomically set in the same SQLite write and an online-mode
    catalog sync) lives in ``execution_start``; this method just
    delegates so the imperative and context-manager paths share
    one implementation.

    Dry-run executions skip the transition entirely — there is no
    SQLite registry row for a dry-run (sentinel RID), so there is
    nothing to transition. ``start_time`` reads back as None for
    dry-runs.

    Returns:
        This Execution instance.

    Raises:
        InvalidTransitionError: If the execution is not currently
            in ``ExecutionStatus.Created``.

    Example:
        >>> with exe.execute() as e:  # doctest: +SKIP
        ...     e.status  # doctest: +SKIP
        <ExecutionStatus.Running>
    """
    self.execution_start()
    return self

__exit__

__exit__(
    exc_type: Any,
    exc_value: Any,
    exc_tb: Any,
) -> bool

End the execution: status running → stopped (clean) or failed.

On clean exit, transitions to stopped. On exception, transitions to failed and stores the exception message in the error column. Per spec §2.12 / R6.3, returns False to propagate any exception (unlike the legacy __exit__ which returned True to suppress). After the transition, emits an INFO log summarizing pending rows/files if any are still staged (the full PendingSummary render lands in Group G; this is the placeholder.)

Parameters:

Name Type Description Default
exc_type Any

Exception type (or None on clean exit).

required
exc_value Any

Exception value (or None on clean exit).

required
exc_tb Any

Exception traceback (or None on clean exit).

required

Returns:

Type Description
bool

False — always. Any exception propagates to the caller.

Source code in src/deriva_ml/execution/execution.py
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
def __exit__(self, exc_type: Any, exc_value: Any, exc_tb: Any) -> bool:
    """End the execution: status running → stopped (clean) or failed.

    On clean exit, transitions to ``stopped``. On exception, transitions
    to ``failed`` and stores the exception message in the ``error``
    column. Per spec §2.12 / R6.3, returns False to propagate any
    exception (unlike the legacy ``__exit__`` which returned True to
    suppress). After the transition, emits an INFO log summarizing
    pending rows/files if any are still staged (the full
    ``PendingSummary`` render lands in Group G; this is the
    placeholder.)

    Args:
       exc_type: Exception type (or None on clean exit).
       exc_value: Exception value (or None on clean exit).
       exc_tb: Exception traceback (or None on clean exit).

    Returns:
       False — always. Any exception propagates to the caller.
    """
    from datetime import datetime, timezone

    if self._dry_run:
        # No SQLite row for dry-run executions; stop_time read-through
        # returns None. Log any exception before returning.
        if exc_value is not None:
            logging.error(
                "Dry-run execution failed: %s: %s",
                exc_type.__name__,
                exc_value,
            )
        return False

    current = self.status
    now = datetime.now(timezone.utc)

    # Tolerate executions that have already advanced past Running by
    # the time __exit__ fires. The canonical pattern for the
    # context manager is "exit at Running → Stopped"; but it is
    # legal (and fixture code in demo_catalog.py does this) to
    # call commit_output_assets() inside the with block, which
    # advances Running → Stopped → Pending_Upload → Uploaded
    # before __exit__ is invoked. Forcing a Stopped/Failed
    # transition from a terminal state would crash the caller's
    # successful path on the way out. Leave terminal states alone
    # — the work is already done.
    if current in {
        ExecutionStatus.Stopped,
        ExecutionStatus.Pending_Upload,
        ExecutionStatus.Uploaded,
        ExecutionStatus.Failed,
        ExecutionStatus.Aborted,
    }:
        return False

    if exc_value is None:
        # Clean exit: delegate Running → Stopped to execution_stop() so
        # the duration computation + single-atomic-transition contract
        # (audit §4.5) is honored. The inline transition this replaced
        # wrote stop_time but not duration, leaving the catalog
        # Execution_Duration column null for every with-block exit —
        # see docs/bugs/2026-05-19-execution-exit-omits-duration.md.
        self.execution_stop()
    else:
        # Failed exit: write stop_time, error, AND duration so the
        # Execution_Duration column reflects how long the run got
        # before it crashed. Useful diagnostic when comparing failed
        # vs successful runs of the same workflow.
        duration_str = _format_duration(self.start_time, now)
        transition(
            store=self._ml_object.workspace.execution_state_store(),
            catalog=(self._ml_object.catalog if self._ml_object._mode is ConnectionMode.online else None),
            execution_rid=self.execution_rid,
            current=current,
            target=ExecutionStatus.Failed,
            mode=self._ml_object._mode,
            extra_fields={
                "stop_time": now,
                "duration": duration_str,
                "error": f"{exc_type.__name__}: {exc_value}",
            },
        )

    # Emit the pending-summary INFO log per §2.12 / R6.3. Full
    # PendingSummary object lands in Group G; this is a placeholder.
    store = self._ml_object.workspace.execution_state_store()
    counts = store.count_pending_by_kind(execution_rid=self.execution_rid)
    if counts["pending_rows"] or counts["pending_files"]:
        logger.info(
            "[Execution %s] exited with pending: %d rows, %d files. Call exe.commit_output_assets() to flush.",
            self.execution_rid,
            counts["pending_rows"],
            counts["pending_files"],
        )

    if exc_value is not None:
        logging.error(
            "Execution %s failed: %s: %s",
            self.execution_rid,
            exc_type.__name__,
            exc_value,
        )

    # Propagate any exception.
    return False

__init__

__init__(
    configuration: ExecutionConfiguration,
    ml_object: DerivaML,
    workflow: Workflow | None = None,
    reload: RID | None = None,
    dry_run: bool = False,
)

Initializes an Execution instance.

Creates a new execution or reloads an existing one. Initializes the execution environment, downloads required datasets, and sets up asset tracking.

Parameters:

Name Type Description Default
configuration ExecutionConfiguration

Settings and parameters for the execution.

required
ml_object DerivaML

DerivaML instance managing the execution.

required
workflow Workflow | None

Optional Workflow object. If not specified, the workflow is taken from the ExecutionConfiguration object. Must be a Workflow object, not a RID.

None
reload RID | None

Optional RID of existing execution to reload.

None
dry_run bool

If True, don't create catalog records or upload results.

False

Raises:

Type Description
DerivaMLException

If initialization fails, configuration is invalid, or workflow is not a Workflow object.

Example

Create an execution with a workflow::

>>> workflow = ml.lookup_workflow("2-ABC1")  # doctest: +SKIP
>>> config = ExecutionConfiguration(  # doctest: +SKIP
...     workflow=workflow,  # doctest: +SKIP
...     description="Process data"  # doctest: +SKIP
... )  # doctest: +SKIP
>>> execution = Execution(config, ml)  # doctest: +SKIP

Or pass workflow separately::

>>> workflow = ml.lookup_workflow_by_url(  # doctest: +SKIP
...     "https://github.com/org/repo/blob/abc123/analysis.py"  # doctest: +SKIP
... )  # doctest: +SKIP
>>> config = ExecutionConfiguration(description="Run analysis")  # doctest: +SKIP
>>> execution = Execution(config, ml, workflow=workflow)  # doctest: +SKIP
Source code in src/deriva_ml/execution/execution.py
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
@validate_call(config=VALIDATION_CONFIG)
def __init__(
    self,
    configuration: ExecutionConfiguration,
    ml_object: DerivaML,
    workflow: Workflow | None = None,
    reload: RID | None = None,
    dry_run: bool = False,
):
    """Initializes an Execution instance.

    Creates a new execution or reloads an existing one. Initializes the execution
    environment, downloads required datasets, and sets up asset tracking.

    Args:
        configuration: Settings and parameters for the execution.
        ml_object: DerivaML instance managing the execution.
        workflow: Optional Workflow object. If not specified, the workflow is taken from
            the ExecutionConfiguration object. Must be a Workflow object, not a RID.
        reload: Optional RID of existing execution to reload.
        dry_run: If True, don't create catalog records or upload results.

    Raises:
        DerivaMLException: If initialization fails, configuration is invalid,
            or workflow is not a Workflow object.

    Example:
        Create an execution with a workflow::

            >>> workflow = ml.lookup_workflow("2-ABC1")  # doctest: +SKIP
            >>> config = ExecutionConfiguration(  # doctest: +SKIP
            ...     workflow=workflow,  # doctest: +SKIP
            ...     description="Process data"  # doctest: +SKIP
            ... )  # doctest: +SKIP
            >>> execution = Execution(config, ml)  # doctest: +SKIP

        Or pass workflow separately::

            >>> workflow = ml.lookup_workflow_by_url(  # doctest: +SKIP
            ...     "https://github.com/org/repo/blob/abc123/analysis.py"  # doctest: +SKIP
            ... )  # doctest: +SKIP
            >>> config = ExecutionConfiguration(description="Run analysis")  # doctest: +SKIP
            >>> execution = Execution(config, ml, workflow=workflow)  # doctest: +SKIP
    """

    self.asset_paths: dict[str, list[AssetFilePath]] = {}
    self.configuration = configuration
    self._ml_object = ml_object
    self._model = ml_object.model
    self._logger = ml_object._logger
    # NOTE(E1/E3): self._status / self.start_time / self.stop_time
    # intentionally removed — execution status and lifecycle
    # timestamps now live in SQLite (see `status`, `start_time`,
    # `stop_time` properties below). Every read hits the workspace
    # registry; no in-memory copy is kept. ``uploaded_assets``
    # similarly reads from the asset manifest on every access
    # (see the ``uploaded_assets`` @property below) — no instance
    # field needed.
    self.configuration.argv = sys.argv
    self._execution_record: ExecutionRecord | None = None  # Lazily created after RID is assigned

    self.dataset_rids: List[RID] = []
    self._datasets_list: list[DatasetBag] = []

    self._working_dir = self._ml_object.working_dir
    self._cache_dir = self._ml_object.cache_dir
    if self._working_dir is None:
        raise DerivaMLException(
            "DerivaML working_dir is not set. "
            "Ensure the DerivaML instance was initialized with a valid working_dir."
        )
    self._dry_run = dry_run

    # Make sure we have a valid Workflow object.
    if workflow:
        self.configuration.workflow = workflow

    if self.configuration.workflow is None:
        raise DerivaMLException("Workflow must be specified either in configuration or as a parameter")

    if not isinstance(self.configuration.workflow, Workflow):
        raise DerivaMLException(
            f"Workflow must be a Workflow object, not {type(self.configuration.workflow).__name__}. "
            "Use ml.lookup_workflow(rid) or ml.lookup_workflow_by_url(url) to get a Workflow object."
        )

    # Validate workflow type(s) and register in catalog
    for wt in self.configuration.workflow.workflow_type:
        self._ml_object.lookup_term(MLVocab.workflow_type, wt)
    self.workflow_rid = (
        self._ml_object._add_workflow(self.configuration.workflow) if not self._dry_run else DRY_RUN_RID
    )

    # Validate the datasets and assets to be valid.
    for d in self.configuration.datasets:
        if self._ml_object.resolve_rid(d.rid).table.name != "Dataset":
            raise DerivaMLException("Dataset specified in execution configuration is not a dataset")

    for a in self.configuration.assets:
        if not self._model.is_asset(self._ml_object.resolve_rid(a.rid).table.name):
            raise DerivaMLException("Asset specified in execution configuration is not an asset table")

    schema_path = self._ml_object.pathBuilder().schemas[self._ml_object.ml_schema]
    if reload:
        self.execution_rid = reload
        if self.execution_rid == DRY_RUN_RID:
            self._dry_run = True
    elif self._dry_run:
        self.execution_rid = DRY_RUN_RID
    else:
        self.execution_rid = schema_path.Execution.insert(
            [
                {
                    "Description": self.configuration.description,
                    "Workflow": self.workflow_rid,
                    "Status": str(ExecutionStatus.Created),
                }
            ]
        )[0]["RID"]

    # Ex-init2 (audit): the catalog row exists at this point.
    # Everything below — environment file writes, dataset
    # materialization, asset downloads, SQLite registry insert —
    # can fail and leave an orphaned catalog Execution row. Wrap
    # the post-insert work in a try/except that rolls back the
    # catalog row before re-raising. ``reload`` and ``dry_run``
    # paths skip the rollback because they never inserted a row
    # in the first place.
    _catalog_row_owned_by_us = not reload and not self._dry_run and self.execution_rid != DRY_RUN_RID
    try:
        self._post_catalog_init_init(reload, schema_path)
    except Exception:
        if _catalog_row_owned_by_us:
            # Best-effort orphan cleanup; never mask the
            # original failure with a delete-side error.
            try:
                schema_path.Execution.filter(schema_path.Execution.RID == self.execution_rid).delete()
                logger.warning(
                    "create_execution %s: post-insert work failed; rolled back orphaned catalog Execution row.",
                    self.execution_rid,
                )
            except Exception as cleanup_exc:
                logger.error(
                    "create_execution %s: post-insert work failed AND "
                    "orphan-rollback also failed (%s). Manual cleanup "
                    "required: ``deriva-ml`` Execution row at this RID "
                    "has no workspace SQLite sibling.",
                    self.execution_rid,
                    cleanup_exc,
                )
        raise

__repr__

__repr__() -> str

One-line summary including status and pending counts.

Pending counts read SQLite — no caching. Example output::

<Execution EXE-A status=stopped pending=15rows/2files>

Omits the pending suffix when there are no pending rows or files. Always guards against exceptions — repr MUST NOT raise, so reads that would raise (e.g., the registry row is missing) degrade to <Execution EXE-A>.

Returns:

Type Description
str

Compact repr string suitable for logs and interactive use.

Source code in src/deriva_ml/execution/execution.py
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
def __repr__(self) -> str:
    """One-line summary including status and pending counts.

    Pending counts read SQLite — no caching. Example output::

        <Execution EXE-A status=stopped pending=15rows/2files>

    Omits the pending suffix when there are no pending rows or
    files. Always guards against exceptions — ``repr`` MUST NOT
    raise, so reads that would raise (e.g., the registry row is
    missing) degrade to ``<Execution EXE-A>``.

    Returns:
        Compact repr string suitable for logs and interactive use.
    """
    try:
        store = self._ml_object.workspace.execution_state_store()
        row = store.get_execution(self.execution_rid)
        if row is None:
            return f"<Execution {self.execution_rid} status=? (not in registry)>"
        counts = store.count_pending_by_kind(execution_rid=self.execution_rid)
        pending_part = ""
        if counts["pending_rows"] or counts["pending_files"]:
            pending_part = f" pending={counts['pending_rows']}rows/{counts['pending_files']}files"
        return f"<Execution {self.execution_rid} status={row['status']}{pending_part}>"
    except Exception:  # repr must not raise
        return f"<Execution {self.execution_rid}>"

abort

abort() -> None

Mark this execution as aborted.

Legal from any non-terminal status (created, running, stopped, failed). Pending rows are NOT discarded — the user can inspect them and decide whether to recover via resume_execution or discard via gc_executions.

Dry-run executions have no SQLite registry row, so abort() is a no-op for them.

Raises:

Type Description
InvalidTransitionError

If the current status doesn't allow abort (e.g., status='uploaded' — terminal).

Example

exe = ml.resume_execution("EXE-A") # doctest: +SKIP exe.abort() # doctest: +SKIP exe.status # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
def abort(self) -> None:
    """Mark this execution as aborted.

    Legal from any non-terminal status (``created``, ``running``,
    ``stopped``, ``failed``). Pending rows are NOT discarded —
    the user can inspect them and decide whether to recover via
    ``resume_execution`` or discard via ``gc_executions``.

    Dry-run executions have no SQLite registry row, so abort() is
    a no-op for them.

    Raises:
        InvalidTransitionError: If the current status doesn't allow
            abort (e.g., status='uploaded' — terminal).

    Example:
        >>> exe = ml.resume_execution("EXE-A")  # doctest: +SKIP
        >>> exe.abort()  # doctest: +SKIP
        >>> exe.status  # doctest: +SKIP
        <ExecutionStatus.Aborted>
    """
    if self._dry_run:
        return

    transition(
        store=self._ml_object.workspace.execution_state_store(),
        catalog=(self._ml_object.catalog if self._ml_object._mode is ConnectionMode.online else None),
        execution_rid=self.execution_rid,
        current=self.status,
        target=ExecutionStatus.Aborted,
        mode=self._ml_object._mode,
    )

add_features

add_features(
    features: list[FeatureRecord],
) -> int

Stage feature records for batch insertion on execution completion.

Writes the records to the execution's SQLite execution_state__feature_records table with status Pending. The records are not sent to ermrest immediately — they are flushed in a single batch, after asset upload, when the execution completes successfully. This integrates with the SQLite execution-state design so crash-resume works for feature writes without extra plumbing.

Records with Execution unset are auto-filled with this execution's RID. All records in a single call must share one feature definition; mixing features raises DerivaMLValidationError and nothing is staged.

Provenance requirement. This is the only way to write feature values — DerivaML.add_features is retired (see the retired-API error shims). For "admin fixup" cases, create a short-lived execution with an appropriate Workflow_Type (e.g. Manual_Correction) and call exe.add_features inside it. The three-extra-lines give you a real audit trail, which is the point.

Parameters:

Name Type Description Default
features list[FeatureRecord]

List of FeatureRecord instances to stage. All must share the same feature definition. Create instances via Feature.feature_record_class().

required

Returns:

Type Description
int

Number of records staged.

Raises:

Type Description
ValueError

features list is empty.

DerivaMLValidationError

Records do not share a single feature definition.

DerivaMLDataError

SQLite staging write failed.

Example

feature = ml.lookup_feature("Image", "Glaucoma") # doctest: +SKIP RecordClass = feature.feature_record_class() # doctest: +SKIP records = [ # doctest: +SKIP ... RecordClass(Image="IMG-1", Glaucoma="Normal"), # doctest: +SKIP ... RecordClass(Image="IMG-2", Glaucoma="Severe"), # doctest: +SKIP ... ] # doctest: +SKIP with ml.create_execution(cfg) as exe: # doctest: +SKIP ... exe.add_features(records) # staged, not yet in ermrest ... # ... more work ...

on exit: staged records flushed to ermrest after assets

Source code in src/deriva_ml/execution/execution.py
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
def add_features(self, features: list[FeatureRecord]) -> int:
    """Stage feature records for batch insertion on execution completion.

    Writes the records to the execution's SQLite ``execution_state__feature_records`` table
    with status ``Pending``. The records are not sent to ermrest immediately
    — they are flushed in a single batch, **after asset upload**, when the
    execution completes successfully. This integrates with the SQLite
    execution-state design so crash-resume works for feature writes without
    extra plumbing.

    Records with ``Execution`` unset are auto-filled with this execution's
    RID. All records in a single call must share one feature definition;
    mixing features raises ``DerivaMLValidationError`` and nothing is staged.

    **Provenance requirement.** This is the only way to write feature values
    — ``DerivaML.add_features`` is retired (see the retired-API error shims).
    For "admin fixup" cases, create a short-lived execution with an
    appropriate ``Workflow_Type`` (e.g. ``Manual_Correction``) and call
    ``exe.add_features`` inside it. The three-extra-lines give you a real
    audit trail, which is the point.

    Args:
        features: List of FeatureRecord instances to stage. All must share
            the same feature definition. Create instances via
            ``Feature.feature_record_class()``.

    Returns:
        Number of records staged.

    Raises:
        ValueError: features list is empty.
        DerivaMLValidationError: Records do not share a single feature
            definition.
        DerivaMLDataError: SQLite staging write failed.

    Example:
        >>> feature = ml.lookup_feature("Image", "Glaucoma")  # doctest: +SKIP
        >>> RecordClass = feature.feature_record_class()  # doctest: +SKIP
        >>> records = [  # doctest: +SKIP
        ...     RecordClass(Image="IMG-1", Glaucoma="Normal"),  # doctest: +SKIP
        ...     RecordClass(Image="IMG-2", Glaucoma="Severe"),  # doctest: +SKIP
        ... ]  # doctest: +SKIP
        >>> with ml.create_execution(cfg) as exe:  # doctest: +SKIP
        ...     exe.add_features(records)     # staged, not yet in ermrest
        ...     # ... more work ...
        >>> # on __exit__: staged records flushed to ermrest after assets
    """
    from deriva_ml.core.exceptions import DerivaMLValidationError

    if not features:
        raise ValueError("features list must not be empty")

    # All records must share one feature definition
    feature_defs = {type(f).feature for f in features if type(f).feature is not None}
    if len(feature_defs) > 1:
        raise DerivaMLValidationError(
            f"add_features called with records from {len(feature_defs)} different "
            f"feature definitions; all records must share one feature."
        )

    # Auto-fill Execution RID on records that don't have it
    for f in features:
        if f.Execution is None:
            f.Execution = self.execution_rid

    # Stage to SQLite — durability boundary is the write-through here.
    feat_class = type(features[0])
    feat = feat_class.feature
    schema_name = feat.feature_table.schema.name
    table_name = feat.feature_table.name
    qualified = f"{schema_name}.{table_name}"
    feature_name = feat.feature_name
    target_table_name = feat.target_table.name

    # Stage every record in a single SQLite transaction. The
    # legacy per-record loop wrapped each ``stage_feature_record``
    # call in its own ``engine.begin()`` block (one WAL fsync per
    # record); for a multi-thousand-record ``add_features`` call
    # that's N serialized fsyncs. The bulk path collapses to one.
    # See ``ManifestStore.stage_feature_records``.
    records_json = [f.model_dump_json() for f in features]
    self._manifest_store.stage_feature_records(
        execution_rid=self.execution_rid,
        feature_table=qualified,
        feature_name=feature_name,
        target_table=target_table_name,
        records_json=records_json,
    )
    return len(features)

add_files

add_files(
    files: Iterable[FileSpec],
    dataset_types: str
    | list[str]
    | None = None,
    description: str = "",
) -> "Dataset"

Adds files to the catalog with their metadata.

Registers files in the catalog along with their metadata (MD5, length, URL) and associates them with specified file types.

Parameters:

Name Type Description Default
files Iterable[FileSpec]

File specifications containing MD5 checksum, length, and URL.

required
dataset_types str | list[str] | None

One or more dataset type terms from File_Type vocabulary.

None
description str

Description of the files.

''

Returns:

Name Type Description
RID 'Dataset'

Dataset that identifies newly added files. Will be nested to mirror original directory structure

'Dataset'

of the files.

Raises:

Type Description
DerivaMLInvalidTerm

If file_types are invalid or execution_rid is not an execution record.

Examples:

Add a single file type: >>> files = [FileSpec(url="path/to/file.txt", md5="abc123", length=1000)] # doctest: +SKIP >>> rids = exe.add_files(files, dataset_types="text") # doctest: +SKIP

Add multiple file types: >>> rids = exe.add_files( # doctest: +SKIP ... files=[FileSpec(url="image.png", md5="def456", length=2000)], # doctest: +SKIP ... dataset_types=["image", "png"], # doctest: +SKIP ... ) # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
@validate_call(config=VALIDATION_CONFIG)
def add_files(
    self,
    files: Iterable[FileSpec],
    dataset_types: str | list[str] | None = None,
    description: str = "",
) -> "Dataset":
    """Adds files to the catalog with their metadata.

    Registers files in the catalog along with their metadata (MD5, length, URL) and associates them with
    specified file types.

    Args:
        files: File specifications containing MD5 checksum, length, and URL.
        dataset_types: One or more dataset type terms from File_Type vocabulary.
        description: Description of the files.

    Returns:
        RID: Dataset  that identifies newly added files. Will be nested to mirror original directory structure
        of the files.

    Raises:
        DerivaMLInvalidTerm: If file_types are invalid or execution_rid is not an execution record.

    Examples:
        Add a single file type:
            >>> files = [FileSpec(url="path/to/file.txt", md5="abc123", length=1000)]  # doctest: +SKIP
            >>> rids = exe.add_files(files, dataset_types="text")  # doctest: +SKIP

        Add multiple file types:
            >>> rids = exe.add_files(  # doctest: +SKIP
            ...     files=[FileSpec(url="image.png", md5="def456", length=2000)],  # doctest: +SKIP
            ...     dataset_types=["image", "png"],  # doctest: +SKIP
            ... )  # doctest: +SKIP
    """
    return self._ml_object.add_files(
        files=files,
        execution_rid=self.execution_rid,
        dataset_types=dataset_types,
        description=description,
    )

add_input_dataset

add_input_dataset(
    dataset_rid: RID,
    version: DatasetVersion
    | str
    | None = None,
) -> None

Record an existing dataset as an input consumed by this execution.

Writes a single Dataset_Execution association row linking dataset_rid to this execution. Because this execution did not author dataset_rid (its Dataset_Version.Execution link points at whichever execution created it), the input/output inference used by :meth:list_input_datasets classifies it as an input — a consume edge — not an output.

This is the counterpart of :meth:create_dataset (which records an output). Use it when an execution reads a dataset it did not produce and you want that consumption recorded as walkable provenance (so :meth:list_input_datasets and lineage walks can reach the consumed dataset), without the bag download that declaring the dataset in ExecutionConfiguration.datasets would trigger. The most common caller is :func:deriva_ml.dataset.split.split_dataset, which records its source dataset as an input of the splitting execution.

When version is supplied, the consumed version is recorded on the input edge via the Dataset_Execution.Dataset_Version FK (resolved through :meth:_version_rid). When version is None the Dataset_Version column is left NULL — fully backward-compatible with callers that pass only a RID.

The link is idempotent: if dataset_rid is already associated with this execution, no duplicate row is inserted. In dry-run mode this is a no-op (the dry-run contract forbids catalog mutations).

Parameters:

Name Type Description Default
dataset_rid RID

RID of the already-existing dataset that this execution consumed as an input.

required
version DatasetVersion | str | None

Optional consumed dataset version. May be a :class:DatasetVersion or a version string. When given, recorded on the input edge's Dataset_Version FK.

None
Example

with ml.create_execution(cfg) as exe: # doctest: +SKIP ... exe.add_input_dataset("1-ABC0") # doctest: +SKIP ... # "1-ABC0" now appears in exe.list_input_datasets()

Source code in src/deriva_ml/execution/execution.py
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
def add_input_dataset(self, dataset_rid: RID, version: DatasetVersion | str | None = None) -> None:
    """Record an existing dataset as an *input* consumed by this execution.

    Writes a single ``Dataset_Execution`` association row linking
    ``dataset_rid`` to this execution. Because this execution did
    not *author* ``dataset_rid`` (its ``Dataset_Version.Execution``
    link points at whichever execution created it), the
    input/output inference used by :meth:`list_input_datasets`
    classifies it as an **input** — a consume edge — not an output.

    This is the counterpart of :meth:`create_dataset` (which records
    an *output*). Use it when an execution reads a dataset it did not
    produce and you want that consumption recorded as walkable
    provenance (so :meth:`list_input_datasets` and lineage walks can
    reach the consumed dataset), *without* the bag download that
    declaring the dataset in ``ExecutionConfiguration.datasets``
    would trigger. The most common caller is
    :func:`deriva_ml.dataset.split.split_dataset`, which records its
    source dataset as an input of the splitting execution.

    When ``version`` is supplied, the consumed version is recorded on
    the input edge via the ``Dataset_Execution.Dataset_Version`` FK
    (resolved through :meth:`_version_rid`). When ``version`` is
    ``None`` the ``Dataset_Version`` column is left NULL — fully
    backward-compatible with callers that pass only a RID.

    The link is idempotent: if ``dataset_rid`` is already associated
    with this execution, no duplicate row is inserted. In dry-run
    mode this is a no-op (the dry-run contract forbids catalog
    mutations).

    Args:
        dataset_rid: RID of the already-existing dataset that this
            execution consumed as an input.
        version: Optional consumed dataset version. May be a
            :class:`DatasetVersion` or a version string. When given,
            recorded on the input edge's ``Dataset_Version`` FK.

    Example:
        >>> with ml.create_execution(cfg) as exe:  # doctest: +SKIP
        ...     exe.add_input_dataset("1-ABC0")  # doctest: +SKIP
        ...     # "1-ABC0" now appears in exe.list_input_datasets()
    """
    if self._dry_run:
        return
    schema_path = self._ml_object.pathBuilder().schemas[self._ml_object.ml_schema]
    dataset_exec = schema_path.Dataset_Execution
    already_linked = {
        row["Dataset"]
        for row in dataset_exec.filter(dataset_exec.Execution == self.execution_rid).entities().fetch()
    }
    if dataset_rid in already_linked:
        return
    version_rid = self._ml_object._version_rid(dataset_rid, version) if version is not None else None
    dataset_exec.insert(
        [{"Dataset": dataset_rid, "Execution": self.execution_rid, "Dataset_Version": version_rid}]
    )

add_nested_execution

add_nested_execution(
    nested_execution: "Execution | ExecutionRecord | RID",
    sequence: int | None = None,
) -> None

Add a nested (child) execution to this execution.

Creates a parent-child relationship between this execution and another. This is useful for grouping related executions, such as parameter sweeps or pipeline stages.

Parameters:

Name Type Description Default
nested_execution 'Execution | ExecutionRecord | RID'

The child execution to add (Execution, ExecutionRecord, or RID).

required
sequence int | None

Optional ordering index (0, 1, 2...). Use None for parallel executions.

None

Raises:

Type Description
DerivaMLException

If the association cannot be created.

Example

parent_exec = ml.create_execution(parent_config) # doctest: +SKIP child_exec = ml.create_execution(child_config) # doctest: +SKIP parent_exec.add_nested_execution(child_exec, sequence=0) # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
def add_nested_execution(
    self,
    nested_execution: "Execution | ExecutionRecord | RID",
    sequence: int | None = None,
) -> None:
    """Add a nested (child) execution to this execution.

    Creates a parent-child relationship between this execution and another.
    This is useful for grouping related executions, such as parameter sweeps
    or pipeline stages.

    Args:
        nested_execution: The child execution to add (Execution, ExecutionRecord, or RID).
        sequence: Optional ordering index (0, 1, 2...). Use None for parallel executions.

    Raises:
        DerivaMLException: If the association cannot be created.

    Example:
        >>> parent_exec = ml.create_execution(parent_config)  # doctest: +SKIP
        >>> child_exec = ml.create_execution(child_config)  # doctest: +SKIP
        >>> parent_exec.add_nested_execution(child_exec, sequence=0)  # doctest: +SKIP
    """
    if self._dry_run:
        return

    # Get the RID from the nested execution
    if isinstance(nested_execution, Execution):
        nested_rid = nested_execution.execution_rid
    elif isinstance(nested_execution, ExecutionRecord):
        nested_rid = nested_execution.execution_rid
    else:
        nested_rid = nested_execution

    # Delegate to ExecutionRecord if available
    if self._execution_record is not None:
        self._execution_record.add_nested_execution(nested_rid, sequence=sequence)
    else:
        # Fallback for cases without execution record
        from deriva_ml.execution._helpers import insert_nested_execution_link

        insert_nested_execution_link(
            ml_instance=self._ml_object,
            parent_rid=self.execution_rid,
            child_rid=nested_rid,
            sequence=sequence,
        )

asset_file_path

asset_file_path(
    asset_name: str,
    file_name: str | Path,
    asset_types: list[str]
    | str
    | None = None,
    copy_file=False,
    rename_file: str | None = None,
    metadata=None,
    description: str | None = None,
    **kwargs,
) -> AssetFilePath

Register a file for upload and return a path to write to.

This routine has three modes depending on whether file_name refers to an existing file: 1. New file: file_name doesn't exist — returns a path to write to. 2. Symlink: file_name exists, copy_file=False — symlinks into staging. 3. Copy: file_name exists, copy_file=True — copies into staging.

Files are stored in a flat per-table directory (assets/{AssetTable}/). Metadata is tracked in a persistent JSON manifest for crash safety. Metadata can be set at registration time via the metadata parameter (an AssetRecord or dict) or incrementally after via the returned AssetFilePath's metadata property.

Thin delegate to asset_upload.asset_file_path; see that helper for the per-mode logic and the asset_types is None vs explicit-empty-list normalization.

Directional tagging. Files registered via this method are uploaded as outputs of this execution. After :meth:commit_output_assets runs, deriva-ml auto-adds the Output_File Asset_Type tag to every uploaded asset (alongside any content tags you passed in asset_types). You don't pass Output_File yourself — it's framework- supplied, deduplicated if explicit, and symmetric with the Input_File tag added by :meth:download_asset. The {Asset}_Execution row gets Asset_Role="Output". See the "How execution-asset roles work" section of the execution user guide for the full contract.

Parameters:

Name Type Description Default
asset_name str

Name of the asset table. Must be a valid asset table.

required
file_name str | Path

Name of file to be uploaded, or path to an existing file.

required
asset_types list[str] | str | None

Content-classification tags from the Asset_Type vocabulary (e.g., ["Model_File"], ["Segmentation_Mask"]). The directional Output_File tag is added automatically — do not pass it explicitly. Defaults to asset_name.

None
copy_file

Whether to copy the file rather than creating a symbolic link.

False
rename_file str | None

If provided, rename the file during staging.

None
metadata

An AssetRecord instance or dict of metadata column values.

None
description str | None

Optional description for the asset record.

None
**kwargs

Additional metadata values (legacy support, merged with metadata).

{}

Returns:

Type Description
AssetFilePath

AssetFilePath bound to the manifest for write-through metadata updates.

Raises:

Type Description
DerivaMLException

If the asset table doesn't exist.

DerivaMLValidationError

If asset_types contains invalid terms.

Source code in src/deriva_ml/execution/execution.py
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
@validate_call(config=VALIDATION_CONFIG)
def asset_file_path(
    self,
    asset_name: str,
    file_name: str | Path,
    asset_types: list[str] | str | None = None,
    copy_file=False,
    rename_file: str | None = None,
    metadata=None,
    description: str | None = None,
    **kwargs,
) -> AssetFilePath:
    """Register a file for upload and return a path to write to.

    This routine has three modes depending on whether file_name refers to an existing file:
    1. **New file**: file_name doesn't exist — returns a path to write to.
    2. **Symlink**: file_name exists, copy_file=False — symlinks into staging.
    3. **Copy**: file_name exists, copy_file=True — copies into staging.

    Files are stored in a flat per-table directory (``assets/{AssetTable}/``).
    Metadata is tracked in a persistent JSON manifest for crash safety.
    Metadata can be set at registration time via the ``metadata`` parameter
    (an AssetRecord or dict) or incrementally after via the returned
    AssetFilePath's ``metadata`` property.

    Thin delegate to ``asset_upload.asset_file_path``;
    see that helper for the per-mode logic and the
    ``asset_types is None`` vs explicit-empty-list
    normalization.

    **Directional tagging.** Files registered via this method are
    uploaded as **outputs** of this execution. After
    :meth:`commit_output_assets` runs, deriva-ml auto-adds
    the ``Output_File`` Asset_Type tag to every uploaded asset
    (alongside any content tags you passed in ``asset_types``).
    You don't pass ``Output_File`` yourself — it's framework-
    supplied, deduplicated if explicit, and symmetric with the
    ``Input_File`` tag added by :meth:`download_asset`. The
    ``{Asset}_Execution`` row gets ``Asset_Role="Output"``.
    See the "How execution-asset roles work" section of the
    execution user guide for the full contract.

    Args:
        asset_name: Name of the asset table. Must be a valid asset table.
        file_name: Name of file to be uploaded, or path to an existing file.
        asset_types: Content-classification tags from the Asset_Type
            vocabulary (e.g., ``["Model_File"]``,
            ``["Segmentation_Mask"]``). The directional
            ``Output_File`` tag is added automatically — do not
            pass it explicitly. Defaults to ``asset_name``.
        copy_file: Whether to copy the file rather than creating a symbolic link.
        rename_file: If provided, rename the file during staging.
        metadata: An AssetRecord instance or dict of metadata column values.
        description: Optional description for the asset record.
        **kwargs: Additional metadata values (legacy support, merged with metadata).

    Returns:
        AssetFilePath bound to the manifest for write-through metadata updates.

    Raises:
        DerivaMLException: If the asset table doesn't exist.
        DerivaMLValidationError: If asset_types contains invalid terms.
    """
    from deriva_ml.execution.asset_upload import asset_file_path as _asset_file_path

    return _asset_file_path(
        self,
        asset_name,
        file_name,
        asset_types=asset_types,
        copy_file=copy_file,
        rename_file=rename_file,
        metadata=metadata,
        description=description,
        asset_type_vocab_term=MLVocab.asset_type,
        flat_asset_dir_fn=flat_asset_dir,
        asset_type_path_fn=asset_type_path,
        legacy_kwargs=kwargs,
    )

commit_output_assets

commit_output_assets(
    clean_folder: bool | None = None,
    progress_callback: Callable[
        [UploadProgress], None
    ]
    | None = None,
) -> UploadReport

Commit this execution's output assets to the catalog.

Single per-execution upload entry point (ADR-0009). Reads the asset manifest, uploads each file to the catalog's Hatrac object store, and inserts {Asset}_Execution association records linking each uploaded asset to this execution with the Output role. Brackets the work with the Pending_Upload → Uploaded (success) or Pending_Upload → Failed (exception) state-machine transition, records Upload_Duration in the SQLite registry, writes asset descriptions to the catalog, and optionally cleans the execution working folder.

Call this method after exiting the execution context manager, not inside it. The context manager sets execution status to Stopped on exit; this method transitions Stopped → Pending_Upload → Uploaded (or Failed).

Idempotent: re-running after a successful upload (status Uploaded, no pending assets) is a no-op that returns an empty report. Re-running after a partial failure resumes from the last known-good state — BagCatalogLoader's match_by_columns dedup makes row inserts idempotent at the catalog.

The method raises on failure. Failure isolation is the batch caller's job (:meth:DerivaML.commit_pending_executions), not the per-execution call's.

Directional tagging. Every asset committed by this call gets Asset_Role="Output" on its {Asset}_Execution row and the Output_File Asset_Type tag (auto-added by deriva-ml, in addition to any content tags the caller passed via :meth:asset_file_path(..., asset_types=...)). This is symmetric with the Input_File tag added by :meth:download_asset. See the "How execution-asset roles work" section of the execution user guide for the full contract.

Parameters:

Name Type Description Default
clean_folder bool | None

Whether to delete output folders after upload. If None (default), uses the DerivaML instance's clean_execution_dir setting. Pass True/False to override for this specific execution.

None
progress_callback Callable[[UploadProgress], None] | None

Optional callback function to receive upload progress updates. Called with UploadProgress objects containing file name, bytes uploaded, total bytes, percent complete, phase, and status message.

None

Returns:

Type Description
UploadReport

UploadReport with execution_rids=[self.execution_rid]

UploadReport

and per-(schema, table) upload counts. total_uploaded

UploadReport

is the sum of asset rows committed across all asset tables

UploadReport

this execution touched. For dry-run executions, returns an

UploadReport

empty report.

Raises:

Type Description
DerivaMLUploadError

If any file upload fails. Partial uploads are recorded in the manifest so the upload can be resumed.

DerivaMLReadOnlyError

If the catalog connection is read-only.

Example

with ml.create_execution(cfg) as exe: # doctest: +SKIP ... path = exe.asset_file_path("Model", "model.pt") # doctest: +SKIP report = exe.commit_output_assets() # doctest: +SKIP print(report.total_uploaded, "assets committed") # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
@validate_call(config=VALIDATION_CONFIG)
def commit_output_assets(
    self,
    clean_folder: bool | None = None,
    progress_callback: Callable[[UploadProgress], None] | None = None,
) -> UploadReport:
    """Commit this execution's output assets to the catalog.

    Single per-execution upload entry point (ADR-0009). Reads the
    asset manifest, uploads each file to the catalog's Hatrac
    object store, and inserts ``{Asset}_Execution`` association
    records linking each uploaded asset to this execution with the
    ``Output`` role. Brackets the work with the
    ``Pending_Upload → Uploaded`` (success) or
    ``Pending_Upload → Failed`` (exception) state-machine
    transition, records ``Upload_Duration`` in the SQLite registry,
    writes asset descriptions to the catalog, and optionally cleans
    the execution working folder.

    Call this method **after** exiting the execution context
    manager, not inside it. The context manager sets execution
    status to ``Stopped`` on exit; this method transitions
    ``Stopped → Pending_Upload → Uploaded`` (or ``Failed``).

    Idempotent: re-running after a successful upload (status
    ``Uploaded``, no pending assets) is a no-op that returns an
    empty report. Re-running after a partial failure resumes from
    the last known-good state — ``BagCatalogLoader``'s
    ``match_by_columns`` dedup makes row inserts idempotent at the
    catalog.

    The method raises on failure. Failure isolation is the batch
    caller's job (:meth:`DerivaML.commit_pending_executions`), not
    the per-execution call's.

    **Directional tagging.** Every asset committed by this call
    gets ``Asset_Role="Output"`` on its ``{Asset}_Execution`` row
    and the ``Output_File`` Asset_Type tag (auto-added by
    deriva-ml, in addition to any content tags the caller passed
    via :meth:`asset_file_path(..., asset_types=...)`). This is
    symmetric with the ``Input_File`` tag added by
    :meth:`download_asset`. See the "How execution-asset roles
    work" section of the execution user guide for the full
    contract.

    Args:
        clean_folder: Whether to delete output folders after
            upload. If None (default), uses the DerivaML instance's
            ``clean_execution_dir`` setting. Pass True/False to
            override for this specific execution.
        progress_callback: Optional callback function to receive
            upload progress updates. Called with UploadProgress
            objects containing file name, bytes uploaded, total
            bytes, percent complete, phase, and status message.

    Returns:
        UploadReport with ``execution_rids=[self.execution_rid]``
        and per-(schema, table) upload counts. ``total_uploaded``
        is the sum of asset rows committed across all asset tables
        this execution touched. For dry-run executions, returns an
        empty report.

    Raises:
        DerivaMLUploadError: If any file upload fails. Partial
            uploads are recorded in the manifest so the upload can
            be resumed.
        DerivaMLReadOnlyError: If the catalog connection is
            read-only.

    Example:
        >>> with ml.create_execution(cfg) as exe:  # doctest: +SKIP
        ...     path = exe.asset_file_path("Model", "model.pt")  # doctest: +SKIP
        >>> report = exe.commit_output_assets()  # doctest: +SKIP
        >>> print(report.total_uploaded, "assets committed")  # doctest: +SKIP
    """
    from deriva_ml.execution.asset_upload import (
        commit_output_assets as _commit_output_assets,
    )

    result = _commit_output_assets(
        self,
        clean_folder=clean_folder,
        progress_callback=progress_callback,
        pending_upload_status=ExecutionStatus.Pending_Upload,
        uploaded_status=ExecutionStatus.Uploaded,
        failed_status=ExecutionStatus.Failed,
        running_status=ExecutionStatus.Running,
        stopped_status=ExecutionStatus.Stopped,
        format_duration_fn=_format_duration,
    )

    # Build UploadReport from the free function's per-table dict.
    # Each value is a list of AssetFilePath; the count is the
    # number of asset rows committed for that table.
    total_uploaded = sum(len(v) for v in result.values())
    per_table = {fqn: {"uploaded": len(v), "failed": 0} for fqn, v in result.items()}
    return UploadReport(
        execution_rids=[self.execution_rid],
        total_uploaded=total_uploaded,
        total_failed=0,
        per_table=per_table,
        errors=[],
    )

create_dataset

create_dataset(
    dataset_types: str
    | list[str]
    | None = None,
    version: DatasetVersion
    | str
    | None = None,
    description: str = "",
) -> Dataset

Create a new dataset tracked to this execution.

Creates a Dataset catalog record linked to this execution as its provenance. The dataset is immediately usable for adding members and incrementing versions.

Parameters:

Name Type Description Default
dataset_types str | list[str] | None

One or more dataset type vocabulary term names to apply. Must be pre-registered via add_dataset_type. Pass None or an empty list to create an untyped dataset.

None
description str

Human-readable description of the dataset. Stored in the catalog Dataset.Description column.

''
version DatasetVersion | str | None

Dataset version. Defaults to 0.1.0.

None

Returns:

Type Description
Dataset

A Dataset instance bound to the newly created catalog record.

Raises:

Type Description
DerivaMLInvalidTerm

If any name in dataset_types is not a registered Dataset_Type vocabulary term.

DerivaMLExecutionError

If the execution context is no longer active.

Example

with ml.create_execution(cfg) as exe: # doctest: +SKIP ... ds = exe.create_dataset( # doctest: +SKIP ... dataset_types=["training"], # doctest: +SKIP ... description="Training images v1", # doctest: +SKIP ... ) # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
@validate_call(config=VALIDATION_CONFIG)
def create_dataset(
    self,
    dataset_types: str | list[str] | None = None,
    version: DatasetVersion | str | None = None,
    description: str = "",
) -> Dataset:
    """Create a new dataset tracked to this execution.

    Creates a ``Dataset`` catalog record linked to this execution as its
    provenance. The dataset is immediately usable for adding members and
    incrementing versions.

    Args:
        dataset_types: One or more dataset type vocabulary term names to apply.
            Must be pre-registered via ``add_dataset_type``. Pass ``None``
            or an empty list to create an untyped dataset.
        description: Human-readable description of the dataset. Stored in
            the catalog ``Dataset.Description`` column.
        version: Dataset version. Defaults to 0.1.0.

    Returns:
        A ``Dataset`` instance bound to the newly created catalog record.

    Raises:
        DerivaMLInvalidTerm: If any name in ``dataset_types`` is not a
            registered ``Dataset_Type`` vocabulary term.
        DerivaMLExecutionError: If the execution context is no longer active.

    Example:
        >>> with ml.create_execution(cfg) as exe:  # doctest: +SKIP
        ...     ds = exe.create_dataset(  # doctest: +SKIP
        ...         dataset_types=["training"],  # doctest: +SKIP
        ...         description="Training images v1",  # doctest: +SKIP
        ...     )  # doctest: +SKIP
    """
    return Dataset.create_dataset(
        ml_instance=self._ml_object,
        execution_rid=self.execution_rid,
        dataset_types=dataset_types,
        version=version,
        description=description,
    )

download_asset

download_asset(
    asset_rid: RID,
    dest_dir: Path,
    update_catalog: bool = True,
    use_cache: bool = False,
    _asset_table: Any = None,
) -> AssetFilePath

Download an asset from a URL and place it in a local directory.

The file is written to dest_dir / asset_record["Filename"]. Overwrites any existing file at that path, with a WARNING logged when the existing content is byte-different from the asset's expected MD5 (issue #181). Idempotent re-downloads — the existing file's md5 already matches the catalog's recorded MD5 — log nothing. Callers that need silent overwrites can accept the WARNING; callers that need genuine isolation should pass a unique dest_dir per asset. The canonical pattern is dest_dir = working_dir / 'downloads' / asset_rid, which is what _initialize_execution uses internally so the platform-default download path is collision-free by construction.

Directional tagging. Assets downloaded via this method are recorded as inputs of this execution (when update_catalog=True, the default). deriva-ml auto-adds the Input_File Asset_Type tag and writes Asset_Role="Input" on the {Asset}_Execution row. The asset's pre-existing content tags (e.g., Model_File if it was a prior execution's output) are preserved — the directional tag is additive, not a replacement. This is symmetric with the Output_File tag added when assets are uploaded via :meth:asset_file_path + :meth:commit_output_assets. See the "How execution-asset roles work" section of the execution user guide for the full contract.

Parameters:

Name Type Description Default
asset_rid RID

RID of the asset.

required
dest_dir Path

Destination directory for the asset. When Filename may collide across concurrent download_asset calls, pass a unique directory per asset to avoid the WARNING and the silent overwrite it guards against.

required
update_catalog bool

Whether to write the {Asset}_Execution row (Asset_Role="Input") and the Input_File Asset_Type tag. Default True — the input-role contract requires it. Pass False only for ad-hoc downloads outside an execution-tracking context.

True
use_cache bool

If True, check the cache directory for a previously downloaded copy with a matching MD5 checksum before downloading. Cached copies are stored in cache_dir/assets/{rid}_{md5}/ and symlinked into the destination.

False
_asset_table Any

Internal — pre-resolved Table object for this RID. When supplied (typically from _initialize_execution's batched resolve_rids call) skips the per-asset resolve_rid round-trip. Underscore-prefixed because callers should not rely on this; pass through the public resolve_rid path otherwise.

None

Returns:

Type Description
AssetFilePath

An AssetFilePath with the path to the downloaded (or cached) asset file.

AssetFilePath

AssetFilePath.file_name is the canonical access path — read from it

AssetFilePath

rather than hand-constructing a path from the asset table or filename.

Source code in src/deriva_ml/execution/execution.py
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
@validate_call(config=VALIDATION_CONFIG)
def download_asset(
    self,
    asset_rid: RID,
    dest_dir: Path,
    update_catalog: bool = True,
    use_cache: bool = False,
    _asset_table: Any = None,
) -> AssetFilePath:
    """Download an asset from a URL and place it in a local directory.

    The file is written to ``dest_dir / asset_record["Filename"]``.
    Overwrites any existing file at that path, with a WARNING logged
    when the existing content is byte-different from the asset's
    expected MD5 (issue #181). Idempotent re-downloads — the existing
    file's md5 already matches the catalog's recorded MD5 — log
    nothing. Callers that need silent overwrites can accept the
    WARNING; callers that need genuine isolation should pass a unique
    ``dest_dir`` per asset. The canonical pattern is
    ``dest_dir = working_dir / 'downloads' / asset_rid``, which is
    what ``_initialize_execution`` uses internally so the
    platform-default download path is collision-free by construction.

    **Directional tagging.** Assets downloaded via this method are
    recorded as **inputs** of this execution (when
    ``update_catalog=True``, the default). deriva-ml auto-adds the
    ``Input_File`` Asset_Type tag and writes ``Asset_Role="Input"``
    on the ``{Asset}_Execution`` row. The asset's pre-existing
    content tags (e.g., ``Model_File`` if it was a prior
    execution's output) are preserved — the directional tag is
    additive, not a replacement. This is symmetric with the
    ``Output_File`` tag added when assets are uploaded via
    :meth:`asset_file_path` + :meth:`commit_output_assets`.
    See the "How execution-asset roles work" section of the
    execution user guide for the full contract.

    Args:
        asset_rid: RID of the asset.
        dest_dir: Destination directory for the asset. When ``Filename``
            may collide across concurrent ``download_asset`` calls,
            pass a unique directory per asset to avoid the WARNING and
            the silent overwrite it guards against.
        update_catalog: Whether to write the ``{Asset}_Execution``
            row (``Asset_Role="Input"``) and the ``Input_File``
            Asset_Type tag. Default ``True`` — the input-role
            contract requires it. Pass ``False`` only for ad-hoc
            downloads outside an execution-tracking context.
        use_cache: If True, check the cache directory for a previously downloaded copy
            with a matching MD5 checksum before downloading. Cached copies are stored
            in ``cache_dir/assets/{rid}_{md5}/`` and symlinked into the destination.
        _asset_table: Internal — pre-resolved Table object for this RID. When supplied
            (typically from ``_initialize_execution``'s batched ``resolve_rids`` call)
            skips the per-asset ``resolve_rid`` round-trip. Underscore-prefixed because
            callers should not rely on this; pass through the public ``resolve_rid``
            path otherwise.

    Returns:
        An AssetFilePath with the path to the downloaded (or cached) asset file.
        ``AssetFilePath.file_name`` is the canonical access path — read from it
        rather than hand-constructing a path from the asset table or filename.
    """
    from deriva_ml.execution.asset_upload import download_asset as _download_asset

    return _download_asset(
        self,
        asset_rid,
        dest_dir,
        update_catalog=update_catalog,
        use_cache=use_cache,
        _asset_table=_asset_table,
        asset_type_vocab_term=MLVocab.asset_type,
        check_overwrite_safe_fn=_check_overwrite_safe,
    )

download_dataset_bag

download_dataset_bag(
    dataset: DatasetSpec,
) -> DatasetBag

Downloads and materializes a dataset for use in the execution.

Downloads the specified dataset as a BDBag and materializes it in the execution's working directory. The dataset version is determined by the DatasetSpec.

Parameters:

Name Type Description Default
dataset DatasetSpec

Specification of the dataset to download, including version and materialization options.

required

Returns:

Name Type Description
DatasetBag DatasetBag

Object exposing, among others: - path: local filesystem path to the materialized bag - dataset_rid: the dataset's Resource Identifier - current_version: the resolved dataset version

Raises:

Type Description
DerivaMLException

If download or materialization fails.

Example

spec = DatasetSpec(rid="1-abc123", version="1.2.0") # doctest: +SKIP bag = execution.download_dataset_bag(spec) # doctest: +SKIP print(f"Downloaded {bag.dataset_rid} to {bag.path}") # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
@validate_call(config=VALIDATION_CONFIG)
def download_dataset_bag(self, dataset: DatasetSpec) -> DatasetBag:
    """Downloads and materializes a dataset for use in the execution.

    Downloads the specified dataset as a BDBag and materializes it in the execution's
    working directory. The dataset version is determined by the DatasetSpec.

    Args:
        dataset: Specification of the dataset to download, including version and
            materialization options.

    Returns:
        DatasetBag: Object exposing, among others:
            - ``path``: local filesystem path to the materialized bag
            - ``dataset_rid``: the dataset's Resource Identifier
            - ``current_version``: the resolved dataset version

    Raises:
        DerivaMLException: If download or materialization fails.

    Example:
        >>> spec = DatasetSpec(rid="1-abc123", version="1.2.0")  # doctest: +SKIP
        >>> bag = execution.download_dataset_bag(spec)  # doctest: +SKIP
        >>> print(f"Downloaded {bag.dataset_rid} to {bag.path}")  # doctest: +SKIP
    """
    return self._ml_object.download_dataset_bag(dataset)

execute

execute() -> Execution

Return self so this Execution can be used as a context manager.

Per spec §2.8, the lifecycle transitions (created → running → stopped/failed) live on __enter__ / __exit__. execute() itself is a no-op that simply returns self so usage reads naturally as with exe.execute() as e: ....

Returns:

Type Description
Execution

This Execution instance, which is itself a context manager.

Example

with exe.execute() as e: # doctest: +SKIP ... # e.status is ExecutionStatus.Running ... pass

e.status is ExecutionStatus.Stopped (or failed on exception)

Source code in src/deriva_ml/execution/execution.py
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
def execute(self) -> Execution:
    """Return self so this Execution can be used as a context manager.

    Per spec §2.8, the lifecycle transitions (created → running →
    stopped/failed) live on ``__enter__`` / ``__exit__``. ``execute()``
    itself is a no-op that simply returns ``self`` so usage reads
    naturally as ``with exe.execute() as e: ...``.

    Returns:
        This Execution instance, which is itself a context manager.

    Example:
        >>> with exe.execute() as e:  # doctest: +SKIP
        ...     # e.status is ExecutionStatus.Running
        ...     pass
        >>> # e.status is ExecutionStatus.Stopped (or failed on exception)
    """
    return self

execution_start

execution_start() -> None

Marks the execution as started.

Records the start time in SQLite and transitions the execution's status from Created to Running via the state machine (the same path the context-manager __enter__ uses). This should be called before beginning the main execution work — its non-context-manager counterpart for code paths that can't use with ml.create_execution(...) as exe: (e.g., the multirun parent execution managed by an atexit handler).

Pairs with execution_stop() which transitions Running → Stopped.

Raises:

Type Description
InvalidTransitionError

If the execution is not currently in ExecutionStatus.Created.

Example

execution.execution_start() # doctest: +SKIP try: # doctest: +SKIP ... # Run analysis ... execution.execution_stop() # doctest: +SKIP ... except Exception: ... execution.update_status(ExecutionStatus.Failed, error="Analysis error") # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
def execution_start(self) -> None:
    """Marks the execution as started.

    Records the start time in SQLite and transitions the execution's
    status from ``Created`` to ``Running`` via the state machine
    (the same path the context-manager ``__enter__`` uses). This
    should be called before beginning the main execution work — its
    non-context-manager counterpart for code paths that can't use
    ``with ml.create_execution(...) as exe:`` (e.g., the multirun
    parent execution managed by an ``atexit`` handler).

    Pairs with ``execution_stop()`` which transitions Running → Stopped.

    Raises:
        InvalidTransitionError: If the execution is not currently in
            ``ExecutionStatus.Created``.

    Example:
        >>> execution.execution_start()  # doctest: +SKIP
        >>> try:  # doctest: +SKIP
        ...     # Run analysis
        ...     execution.execution_stop()  # doctest: +SKIP
        ... except Exception:
        ...     execution.update_status(ExecutionStatus.Failed, error="Analysis error")  # doctest: +SKIP
    """
    from datetime import timezone

    self._logger.info("Start execution...")

    # Dry-run executions don't have a SQLite registry row — there's
    # nothing to transition and the status read-through returns a
    # sentinel. Skip the state-machine call entirely.
    if self._dry_run:
        return

    # Transition Created → Running through the state machine, writing
    # start_time atomically with the status change so a crash between
    # the two can't leave the row inconsistent. Mirrors __enter__ —
    # the only difference is that this path is invoked imperatively
    # by callers that don't (or can't) use the context manager.
    current = self.status
    transition(
        store=self._ml_object.workspace.execution_state_store(),
        catalog=(self._ml_object.catalog if self._ml_object._mode is ConnectionMode.online else None),
        execution_rid=self.execution_rid,
        current=current,
        target=ExecutionStatus.Running,
        mode=self._ml_object._mode,
        extra_fields={"start_time": datetime.now(timezone.utc)},
    )

execution_stop

execution_stop() -> None

Marks the execution as stopped (algorithm finished successfully).

Computes the wall-clock duration against start_time and transitions Running → Stopped through the state machine, writing stop_time and duration atomically with the status change. Online callers see a single catalog PUT that carries both Status and Duration (the historical second catalog write is gone — audit §4.5).

This should be called after all execution work is finished; upload of outputs is a separate phase that moves status from Stopped → Pending_Upload → Uploaded.

Example

try: # doctest: +SKIP ... # Run analysis ... execution.execution_stop() # doctest: +SKIP ... except Exception: ... execution.update_status(ExecutionStatus.Failed, error="Analysis error") # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
def execution_stop(self) -> None:
    """Marks the execution as stopped (algorithm finished successfully).

    Computes the wall-clock duration against ``start_time`` and
    transitions Running → Stopped through the state machine,
    writing ``stop_time`` and ``duration`` atomically with the
    status change. Online callers see a single catalog PUT that
    carries both Status and Duration (the historical second
    catalog write is gone — audit §4.5).

    This should be called after all execution work is finished;
    upload of outputs is a separate phase that moves status from
    Stopped → Pending_Upload → Uploaded.

    Example:
        >>> try:  # doctest: +SKIP
        ...     # Run analysis
        ...     execution.execution_stop()  # doctest: +SKIP
        ... except Exception:
        ...     execution.update_status(ExecutionStatus.Failed, error="Analysis error")  # doctest: +SKIP
    """
    from datetime import timezone

    now = datetime.now(timezone.utc)

    # Compute algorithm duration against start_time. Falls back to
    # "0H 0min 0.0sec" if start_time is missing (shouldn't happen
    # in practice — Running → Stopped requires __enter__ /
    # execution_start to have set start_time).
    duration_str = _format_duration(self.start_time, now)

    if self._dry_run:
        return

    # Single atomic transition: SQLite write (status + stop_time +
    # duration) followed by online catalog PUT (Status + Duration
    # via _catalog_body_for_execution). Replaces the historical
    # two-write design that left Duration vulnerable to a partial
    # failure between writes (audit §4.5).
    current = self.status
    transition(
        store=self._ml_object.workspace.execution_state_store(),
        catalog=(self._ml_object.catalog if self._ml_object._mode is ConnectionMode.online else None),
        execution_rid=self.execution_rid,
        current=current,
        target=ExecutionStatus.Stopped,
        mode=self._ml_object._mode,
        extra_fields={"stop_time": now, "duration": duration_str},
    )

from_registry classmethod

from_registry(
    *, ml_object, execution_rid: str
) -> "Execution"

Bind an Execution to an existing SQLite registry row.

Distinct from create_execution — does NOT contact the catalog and does NOT POST a new row. The bound Execution instance reads its lifecycle fields (status, error, start_time, stop_time) from SQLite via the read-through property machinery.

Called by :meth:DerivaML.resume_execution.

Parameters:

Name Type Description Default
ml_object

The DerivaML instance this Execution is bound to.

required
execution_rid str

The pre-existing Execution RID.

required

Returns:

Type Description
'Execution'

A minimally-initialized Execution with just enough state for

'Execution'

execution_rid lookup.

Source code in src/deriva_ml/execution/execution.py
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
@classmethod
def from_registry(cls, *, ml_object, execution_rid: str) -> "Execution":
    """Bind an Execution to an existing SQLite registry row.

    Distinct from ``create_execution`` — does NOT contact the
    catalog and does NOT POST a new row. The bound ``Execution``
    instance reads its lifecycle fields (``status``, ``error``,
    ``start_time``, ``stop_time``) from SQLite via the
    read-through property machinery.

    Called by :meth:`DerivaML.resume_execution`.

    Args:
        ml_object: The DerivaML instance this Execution is bound to.
        execution_rid: The pre-existing Execution RID.

    Returns:
        A minimally-initialized Execution with just enough state for
        execution_rid lookup.
    """
    # Minimal construction: skip __init__'s catalog interactions.
    # The read-through properties handle lifecycle field access.
    instance = cls.__new__(cls)
    instance._ml_object = ml_object
    instance._model = ml_object.model
    instance._logger = getattr(ml_object, "_logger", None)
    instance.execution_rid = execution_rid
    instance._dry_run = False
    # Fields the existing class expects to exist:
    instance._datasets_list = []
    instance.dataset_rids = []
    instance.asset_paths = {}
    instance.configuration = None  # Group E loads from config_json
    instance._working_dir = ml_object.working_dir
    instance._cache_dir = ml_object.cache_dir
    # NOTE(E1/E3): self._status / self.start_time / self.stop_time /
    # self.uploaded_assets intentionally not set — they are all
    # read-through properties backed by SQLite / the asset manifest.
    instance._execution_record = None
    # Pull ``workflow_rid`` from the registry row. The SQLite
    # row carries it (see ``state_store.executions.workflow_rid``);
    # leaving it None silently breaks downstream code that
    # relies on ``execution.workflow_rid`` (notably
    # ``add_workflow_executions`` linkage during nested-execution
    # attach). Best-effort: if the registry lookup fails or
    # returns None, leave it None — but we try.
    instance.workflow_rid = None
    try:
        row = ml_object.workspace.execution_state_store().get_execution(execution_rid)
        if row is not None:
            instance.workflow_rid = row.get("workflow_rid")
    except Exception:
        # The registry read can fail in odd offline-mode tests
        # or partially-initialized fixtures; preserve the
        # legacy ``None`` rather than refuse to construct.
        pass
    return instance

is_nested

is_nested() -> bool

Check if this execution is nested within another execution.

Hierarchy queries live on :class:ExecutionRecord only (per spec R2.1). This shortcut delegates to self._execution_record.is_nested() when available.

Returns:

Type Description
bool

True if this execution has at least one parent execution.

Raises:

Type Description
DerivaMLException

If this Execution has no bound ExecutionRecord (e.g. a dry-run execution).

Source code in src/deriva_ml/execution/execution.py
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
def is_nested(self) -> bool:
    """Check if this execution is nested within another execution.

    Hierarchy queries live on :class:`ExecutionRecord` only (per spec
    R2.1). This shortcut delegates to
    ``self._execution_record.is_nested()`` when available.

    Returns:
        True if this execution has at least one parent execution.

    Raises:
        DerivaMLException: If this Execution has no bound
            ExecutionRecord (e.g. a dry-run execution).
    """
    if self._execution_record is None:
        raise DerivaMLException(
            "is_nested requires a bound ExecutionRecord. Hierarchy queries are not available in dry-run mode."
        )
    return self._execution_record.is_nested()

is_parent

is_parent() -> bool

Check if this execution has nested child executions.

Hierarchy queries live on :class:ExecutionRecord only (per spec R2.1). This shortcut delegates to self._execution_record.is_parent() when available.

Returns:

Type Description
bool

True if this execution has at least one nested execution.

Raises:

Type Description
DerivaMLException

If this Execution has no bound ExecutionRecord (e.g. a dry-run execution).

Source code in src/deriva_ml/execution/execution.py
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
def is_parent(self) -> bool:
    """Check if this execution has nested child executions.

    Hierarchy queries live on :class:`ExecutionRecord` only (per spec
    R2.1). This shortcut delegates to
    ``self._execution_record.is_parent()`` when available.

    Returns:
        True if this execution has at least one nested execution.

    Raises:
        DerivaMLException: If this Execution has no bound
            ExecutionRecord (e.g. a dry-run execution).
    """
    if self._execution_record is None:
        raise DerivaMLException(
            "is_parent requires a bound ExecutionRecord. Hierarchy queries are not available in dry-run mode."
        )
    return self._execution_record.is_parent()

list_assets

list_assets(
    asset_role: str | None = None,
) -> list["Asset"]

List all assets that were inputs or outputs of this execution.

Parameters:

Name Type Description Default
asset_role str | None

Optional filter: "Input" or "Output". If None, returns all.

None

Returns:

Type Description
list['Asset']

List of Asset objects associated with this execution.

Example

inputs = execution.list_assets(asset_role="Input") # doctest: +SKIP outputs = execution.list_assets(asset_role="Output") # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
def list_assets(self, asset_role: str | None = None) -> list["Asset"]:
    """List all assets that were inputs or outputs of this execution.

    Args:
        asset_role: Optional filter: "Input" or "Output". If None, returns all.

    Returns:
        List of Asset objects associated with this execution.

    Example:
        >>> inputs = execution.list_assets(asset_role="Input")  # doctest: +SKIP
        >>> outputs = execution.list_assets(asset_role="Output")  # doctest: +SKIP
    """
    if self._execution_record is not None:
        return self._execution_record.list_assets(asset_role=asset_role)

    # Fallback for dry-run mode (no execution record bound).
    # Delegates to the shared helper so the dry-run path
    # and the canonical ``ExecutionRecord.list_assets`` path
    # stay in lockstep — pre-fix the dry-run path only
    # walked ``Execution_Asset_Execution`` while the
    # canonical path walked every ``*_Execution`` association
    # across all schemas. That mismatch was invisible until a
    # dry-run scenario exercised assets in a domain-schema
    # table other than ``Execution_Asset``; now both paths
    # do the full walk.
    from deriva_ml.execution._helpers import list_assets as _list_assets

    return _list_assets(
        ml_instance=self._ml_object,
        execution_rid=self.execution_rid,
        asset_role=asset_role,
    )

list_input_datasets

list_input_datasets() -> list[Dataset]

List all datasets that were inputs to this execution.

Excludes any dataset this execution itself produced — the Dataset_Execution association table has no role column to distinguish inputs from outputs, so we infer authorship from each dataset's Dataset_Version.Execution link.

Returns:

Type Description
list[Dataset]

List of Dataset objects that were used as inputs.

Example

for ds in execution.list_input_datasets(): # doctest: +SKIP ... print(f"Input: {ds.dataset_rid} - {ds.description}") # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
def list_input_datasets(self) -> list[Dataset]:
    """List all datasets that were inputs to this execution.

    Excludes any dataset this execution itself *produced* — the
    ``Dataset_Execution`` association table has no role column to
    distinguish inputs from outputs, so we infer authorship from
    each dataset's ``Dataset_Version.Execution`` link.

    Returns:
        List of Dataset objects that were used as inputs.

    Example:
        >>> for ds in execution.list_input_datasets():  # doctest: +SKIP
        ...     print(f"Input: {ds.dataset_rid} - {ds.description}")  # doctest: +SKIP
    """
    if self._execution_record is not None:
        return self._execution_record.list_input_datasets()

    # Fallback for dry-run mode (no execution record bound).
    # Delegates to the shared helper so the dry-run path
    # and the canonical ``ExecutionRecord.list_input_datasets``
    # path stay in lockstep — pre-fix they re-implemented the
    # same producer-filter walk in two places.
    from deriva_ml.execution._helpers import list_input_datasets as _list_input_datasets

    return _list_input_datasets(
        ml_instance=self._ml_object,
        execution_rid=self.execution_rid,
    )

metrics_file

metrics_file(
    filename: str = "metrics.jsonl",
) -> AssetFilePath

Return a path for writing training-metric records.

Thin sugar over asset_file_path(MLAsset.execution_metadata, ...) that stamps the file with asset_types=Metrics_File so the catalog's Execution_Metadata.Type column honestly describes the file's purpose. The file registers with the execution's asset manifest on first call and uploads as part of commit_output_assets().

The file itself is plain text; callers decide the format. The default filename metrics.jsonl suggests one JSON record per line — the simplest shape that lets a downstream reader page through the file without loading the whole thing into memory — but CSV, YAML, or a single JSON object also work as long as the readback code knows the format.

Repeated calls inside the same execution return the same AssetFilePath (registered once in the manifest), so append-style writes across an epoch loop are safe::

with ml.create_execution(cfg) as exe:
    for epoch in range(num_epochs):
        train_loss = train_one_epoch(...)
        val_loss = evaluate(...)
        with exe.metrics_file().open("a") as f:
            json.dump(
                {"epoch": epoch, "train_loss": train_loss,
                 "val_loss": val_loss},
                f,
            )
            f.write("\n")
exe.commit_output_assets()

Parameters:

Name Type Description Default
filename str

Name of the metrics file inside the execution's Execution_Metadata staging area. Defaults to "metrics.jsonl". Override to distinguish multiple metric streams (e.g. "train_metrics.jsonl" + "eval_metrics.jsonl") — each distinct filename becomes a separate Execution_Metadata asset on upload.

'metrics.jsonl'

Returns:

Type Description
AssetFilePath

AssetFilePath for the metrics file. Use its .open(...)

AssetFilePath

method to read, write, or append; the manifest tracks the

AssetFilePath

file for upload regardless of how you write to it.

Raises:

Type Description
DerivaMLException

If the Execution_Metadata table is not present in the catalog schema (should never happen in a correctly-initialized catalog).

DerivaMLValidationError

If the Metrics_File term is missing from the Asset_Type vocabulary (i.e. an old catalog predating this feature; run create_ml_schema or initialize_ml_schema once to seed the term).

Example

from deriva_ml.core.enums import MLAsset, ExecMetadataType # doctest: +SKIP MLAsset.execution_metadata.value # doctest: +SKIP 'Execution_Metadata' ExecMetadataType.metrics_file.value # doctest: +SKIP 'Metrics_File'

Catalog-dependent end-to-end flow:

import json # doctest: +SKIP with ml.create_execution(cfg) as exe: # doctest: +SKIP ... with exe.metrics_file().open("a") as f: # doctest: +SKIP ... json.dump({"epoch": 0, "val_loss": 0.23}, f) # doctest: +SKIP ... f.write("\n") # doctest: +SKIP exe.commit_output_assets() # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
def metrics_file(self, filename: str = "metrics.jsonl") -> AssetFilePath:
    """Return a path for writing training-metric records.

    Thin sugar over ``asset_file_path(MLAsset.execution_metadata, ...)``
    that stamps the file with ``asset_types=Metrics_File`` so the
    catalog's ``Execution_Metadata.Type`` column honestly describes
    the file's purpose. The file registers with the execution's asset
    manifest on first call and uploads as part of
    ``commit_output_assets()``.

    The file itself is plain text; callers decide the format. The
    default filename ``metrics.jsonl`` suggests one JSON record per
    line — the simplest shape that lets a downstream reader page
    through the file without loading the whole thing into memory —
    but CSV, YAML, or a single JSON object also work as long as the
    readback code knows the format.

    Repeated calls inside the same execution return the **same**
    AssetFilePath (registered once in the manifest), so append-style
    writes across an epoch loop are safe::

        with ml.create_execution(cfg) as exe:
            for epoch in range(num_epochs):
                train_loss = train_one_epoch(...)
                val_loss = evaluate(...)
                with exe.metrics_file().open("a") as f:
                    json.dump(
                        {"epoch": epoch, "train_loss": train_loss,
                         "val_loss": val_loss},
                        f,
                    )
                    f.write("\\n")
        exe.commit_output_assets()

    Args:
        filename: Name of the metrics file inside the execution's
            Execution_Metadata staging area. Defaults to
            ``"metrics.jsonl"``. Override to distinguish multiple
            metric streams (e.g. ``"train_metrics.jsonl"`` +
            ``"eval_metrics.jsonl"``) — each distinct filename
            becomes a separate Execution_Metadata asset on upload.

    Returns:
        AssetFilePath for the metrics file. Use its ``.open(...)``
        method to read, write, or append; the manifest tracks the
        file for upload regardless of how you write to it.

    Raises:
        DerivaMLException: If the Execution_Metadata table is not
            present in the catalog schema (should never happen in a
            correctly-initialized catalog).
        DerivaMLValidationError: If the ``Metrics_File`` term is
            missing from the Asset_Type vocabulary (i.e. an old
            catalog predating this feature; run ``create_ml_schema``
            or ``initialize_ml_schema`` once to seed the term).

    Example:
        >>> from deriva_ml.core.enums import MLAsset, ExecMetadataType  # doctest: +SKIP
        >>> MLAsset.execution_metadata.value  # doctest: +SKIP
        'Execution_Metadata'
        >>> ExecMetadataType.metrics_file.value  # doctest: +SKIP
        'Metrics_File'

        >>> # Catalog-dependent end-to-end flow:
        >>> import json  # doctest: +SKIP
        >>> with ml.create_execution(cfg) as exe:  # doctest: +SKIP
        ...     with exe.metrics_file().open("a") as f:  # doctest: +SKIP
        ...         json.dump({"epoch": 0, "val_loss": 0.23}, f)  # doctest: +SKIP
        ...         f.write("\\n")  # doctest: +SKIP
        >>> exe.commit_output_assets()  # doctest: +SKIP
    """
    from deriva_ml.execution.asset_upload import metrics_file as _metrics_file

    return _metrics_file(
        self,
        filename,
        execution_metadata_asset_name=MLAsset.execution_metadata,
        metrics_file_asset_type=ExecMetadataType.metrics_file.value,
    )

pending_summary

pending_summary() -> 'PendingSummary'

Return a snapshot of pending upload state for this execution.

Read-only; does not affect state. Safe to call from anywhere at any time, including from a separate process holding the same workspace.

Returns:

Type Description
'PendingSummary'

PendingSummary with per-table row and asset counts and

'PendingSummary'

diagnostic messages from any failed rows.

Example

summary = exe.pending_summary() # doctest: +SKIP if summary.has_pending: # doctest: +SKIP ... print(summary.render()) # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
def pending_summary(self) -> "PendingSummary":
    """Return a snapshot of pending upload state for this execution.

    Read-only; does not affect state. Safe to call from anywhere at
    any time, including from a separate process holding the same
    workspace.

    Returns:
        PendingSummary with per-table row and asset counts and
        diagnostic messages from any failed rows.

    Example:
        >>> summary = exe.pending_summary()  # doctest: +SKIP
        >>> if summary.has_pending:  # doctest: +SKIP
        ...     print(summary.render())  # doctest: +SKIP
    """
    from deriva_ml.execution.pending_summary import (
        PendingAssetCount,
        PendingRowCount,
        PendingSummary,
    )

    store = self._ml_object.workspace.execution_state_store()
    data = store.pending_summary_rows(execution_rid=self.execution_rid)
    return PendingSummary(
        execution_rid=self.execution_rid,
        rows=[PendingRowCount(**r) for r in data["rows"]],
        assets=[PendingAssetCount(**a) for a in data["assets"]],
        diagnostics=data["diagnostics"],
    )

table_path

table_path(table: str) -> Path

Return a local file path to a CSV to add values to a table on upload.

Parameters:

Name Type Description Default
table str

Name of table to be uploaded.

required

Returns:

Type Description
Path

Pathlib path to the file in which to place table values.

Raises:

Type Description
DerivaMLException

If table is not found in any domain schema.

Example

path = exe.table_path("Measurement") # doctest: +SKIP with path.open("w") as f: # doctest: +SKIP ... writer = csv.DictWriter(f, fieldnames=["Subject", "Score"]) # doctest: +SKIP ... writer.writerow({"Subject": "IMG-1", "Score": 0.95}) # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
def table_path(self, table: str) -> Path:
    """Return a local file path to a CSV to add values to a table on upload.

    Args:
        table: Name of table to be uploaded.

    Returns:
        Pathlib path to the file in which to place table values.

    Raises:
        DerivaMLException: If ``table`` is not found in any domain schema.

    Example:
        >>> path = exe.table_path("Measurement")  # doctest: +SKIP
        >>> with path.open("w") as f:  # doctest: +SKIP
        ...     writer = csv.DictWriter(f, fieldnames=["Subject", "Score"])  # doctest: +SKIP
        ...     writer.writerow({"Subject": "IMG-1", "Score": 0.95})  # doctest: +SKIP
    """
    # Find which domain schema contains this table
    table_schema = None
    for domain_schema in self._ml_object.domain_schemas:
        if domain_schema in self._model.schemas:
            if table in self._model.schemas[domain_schema].tables:
                table_schema = domain_schema
                break

    if table_schema is None:
        raise DerivaMLException("Table '{}' not found in any domain schema".format(table))

    return table_path(self._working_dir, schema=table_schema, table=table)

update_status

update_status(
    target: "ExecutionStatus",
    *,
    error: str | None = None,
) -> None

Transition this execution to a new status.

Thin wrapper around state_machine.transition() that validates against ALLOWED_TRANSITIONS, writes the SQLite registry, and syncs to the catalog when online.

Parameters:

Name Type Description Default
target 'ExecutionStatus'

Target ExecutionStatus enum member.

required
error str | None

For Failed/Aborted transitions, a human-readable error message written to the error column. On a non-terminal transition, error is ignored and a warning is logged.

None

Raises:

Type Description
InvalidTransitionError

If the (current, target) pair is not in ALLOWED_TRANSITIONS.

DerivaMLStateInconsistency

If state_machine's catalog sync detects divergence.

Example

exe.update_status(ExecutionStatus.Running) # doctest: +SKIP exe.update_status(ExecutionStatus.Failed, error="Network timeout") # doctest: +SKIP

Source code in src/deriva_ml/execution/execution.py
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
def update_status(
    self,
    target: "ExecutionStatus",
    *,
    error: str | None = None,
) -> None:
    """Transition this execution to a new status.

    Thin wrapper around state_machine.transition() that validates
    against ALLOWED_TRANSITIONS, writes the SQLite registry, and syncs
    to the catalog when online.

    Args:
        target: Target ExecutionStatus enum member.
        error: For Failed/Aborted transitions, a human-readable error
            message written to the `error` column. On a non-terminal
            transition, error is ignored and a warning is logged.

    Raises:
        InvalidTransitionError: If the (current, target) pair is not in
            ALLOWED_TRANSITIONS.
        DerivaMLStateInconsistency: If state_machine's catalog sync
            detects divergence.

    Example:
        >>> exe.update_status(ExecutionStatus.Running)  # doctest: +SKIP
        >>> exe.update_status(ExecutionStatus.Failed, error="Network timeout")  # doctest: +SKIP
    """
    store = self._ml_object.workspace.execution_state_store()
    row = store.get_execution(self.execution_rid)
    if row is None:
        raise DerivaMLException(f"Execution {self.execution_rid} not in workspace registry")
    current = ExecutionStatus(row["status"])

    extra_fields: dict = {}
    # Terminal = Failed, Aborted.
    if target in (ExecutionStatus.Failed, ExecutionStatus.Aborted):
        if error is not None:
            extra_fields["error"] = error
    elif error is not None:
        logger.warning(
            "error= ignored on non-terminal transition to %s: %s",
            target.value,
            error,
        )

    transition(
        store=store,
        catalog=self._ml_object.catalog if self._ml_object._mode is ConnectionMode.online else None,
        execution_rid=self.execution_rid,
        current=current,
        target=target,
        mode=self._ml_object._mode,
        extra_fields=extra_fields,
    )

ExecutionConfiguration

Bases: BaseModel

Configuration for a DerivaML execution.

Defines the complete configuration for a computational or manual process in DerivaML, including required datasets, input assets, workflow definition, and parameters.

Attributes:

Name Type Description
datasets list[DatasetSpec]

Dataset specifications, each containing: - rid: Dataset Resource Identifier - version: Version to use - materialize: Whether to extract dataset contents

assets list[AssetSpec]

Asset specifications. Each element can be: - A plain RID string (no caching) - An AssetSpec(rid=..., cache=True) for checksum-based caching

workflow Workflow | None

Workflow object defining the computational process. Use ml.lookup_workflow(rid) or ml.lookup_workflow_by_url(url) to get a Workflow object from a RID or URL. Defaults to None, which means the workflow must be provided via the workflow parameter of ml.create_execution() instead. If no workflow is specified in either place, a DerivaMLException is raised at execution creation time.

description str

Description of execution purpose (supports Markdown).

argv list[str]

Command line arguments used to start execution.

config_choices dict[str, str]

Hydra config group choices that were selected. Maps group names to selected config names (e.g., {"model_config": "cifar10_quick"}). Automatically populated by run_model() and get_notebook_configuration().

Example

Plain RIDs (backward compatible)

config = ExecutionConfiguration(assets=["6-EPNR", "6-EP56"])

Mixed: cached model weights + uncached embeddings

config = ExecutionConfiguration( ... assets=[ ... AssetSpec(rid="6-EPNR", cache=True), ... "6-EP56", ... ] ... )

Source code in src/deriva_ml/execution/execution_configuration.py
 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
class ExecutionConfiguration(BaseModel):
    """Configuration for a DerivaML execution.

    Defines the complete configuration for a computational or manual process in DerivaML,
    including required datasets, input assets, workflow definition, and parameters.

    Attributes:
        datasets (list[DatasetSpec]): Dataset specifications, each containing:
            - rid: Dataset Resource Identifier
            - version: Version to use
            - materialize: Whether to extract dataset contents
        assets (list[AssetSpec]): Asset specifications. Each element can be:
            - A plain RID string (no caching)
            - An ``AssetSpec(rid=..., cache=True)`` for checksum-based caching
        workflow (Workflow | None): Workflow object defining the computational process.
            Use ``ml.lookup_workflow(rid)`` or ``ml.lookup_workflow_by_url(url)`` to get
            a Workflow object from a RID or URL. Defaults to ``None``, which means the
            workflow must be provided via the ``workflow`` parameter of
            ``ml.create_execution()`` instead. If no workflow is specified in either
            place, a ``DerivaMLException`` is raised at execution creation time.
        description (str): Description of execution purpose (supports Markdown).
        argv (list[str]): Command line arguments used to start execution.
        config_choices (dict[str, str]): Hydra config group choices that were selected.
            Maps group names to selected config names (e.g., {"model_config": "cifar10_quick"}).
            Automatically populated by run_model() and get_notebook_configuration().

    Example:
        >>> # Plain RIDs (backward compatible)
        >>> config = ExecutionConfiguration(assets=["6-EPNR", "6-EP56"])
        >>>
        >>> # Mixed: cached model weights + uncached embeddings
        >>> config = ExecutionConfiguration(
        ...     assets=[
        ...         AssetSpec(rid="6-EPNR", cache=True),
        ...         "6-EP56",
        ...     ]
        ... )
    """

    datasets: list[DatasetSpec] = []
    assets: list[AssetSpec] = []
    workflow: Workflow | None = None
    description: str = ""
    argv: list[str] = Field(default_factory=lambda: sys.argv)
    config_choices: dict[str, str] = Field(default_factory=dict)

    model_config = VALIDATION_CONFIG

    @field_validator("assets", mode="before")
    @classmethod
    def validate_assets(cls, value: Any) -> Any:
        """Normalize asset entries to AssetSpec objects.

        Accepts plain RID strings, DictConfig from Hydra, AssetSpec objects,
        or dicts with 'rid' and optional 'cache' keys.
        """
        result = []
        for v in value:
            if isinstance(v, AssetSpec):
                result.append(v)
            elif isinstance(v, dict):
                # Dict with rid/cache keys (e.g., from JSON config)
                result.append(AssetSpec(**v))
            elif isinstance(v, DictConfig):
                # OmegaConf DictConfig from Hydra — may have rid+cache or just rid
                d = dict(v)
                if "rid" in d:
                    result.append(AssetSpec(**d))
                else:
                    # Bare DictConfig with just a .rid attribute.
                    result.append(AssetSpec(rid=v.rid, cache=getattr(v, "cache", False)))
            elif isinstance(v, str):
                result.append(AssetSpec(rid=v))
            else:
                # Unknown type — try string coercion
                result.append(AssetSpec(rid=str(v)))
        return result

    @staticmethod
    def load_configuration(path: Path) -> ExecutionConfiguration:
        """Creates an ExecutionConfiguration from a JSON file.

        Loads and parses a JSON configuration file into an ExecutionConfiguration
        instance. The file should contain a valid configuration specification.

        Args:
            path: Path to JSON configuration file.

        Returns:
            ExecutionConfiguration: Loaded configuration instance.

        Raises:
            ValueError: If JSON file is invalid or missing required fields.
            FileNotFoundError: If configuration file doesn't exist.

        Example:
            >>> config = ExecutionConfiguration.load_configuration(Path("config.json"))  # doctest: +SKIP
            >>> print(f"Workflow: {config.workflow}")  # doctest: +SKIP
            >>> print(f"Datasets: {len(config.datasets)}")  # doctest: +SKIP
        """
        with Path(path).open() as fd:
            config = json.load(fd)
        return ExecutionConfiguration.model_validate(config)

load_configuration staticmethod

load_configuration(
    path: Path,
) -> ExecutionConfiguration

Creates an ExecutionConfiguration from a JSON file.

Loads and parses a JSON configuration file into an ExecutionConfiguration instance. The file should contain a valid configuration specification.

Parameters:

Name Type Description Default
path Path

Path to JSON configuration file.

required

Returns:

Name Type Description
ExecutionConfiguration ExecutionConfiguration

Loaded configuration instance.

Raises:

Type Description
ValueError

If JSON file is invalid or missing required fields.

FileNotFoundError

If configuration file doesn't exist.

Example

config = ExecutionConfiguration.load_configuration(Path("config.json")) # doctest: +SKIP print(f"Workflow: {config.workflow}") # doctest: +SKIP print(f"Datasets: {len(config.datasets)}") # doctest: +SKIP

Source code in src/deriva_ml/execution/execution_configuration.py
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
@staticmethod
def load_configuration(path: Path) -> ExecutionConfiguration:
    """Creates an ExecutionConfiguration from a JSON file.

    Loads and parses a JSON configuration file into an ExecutionConfiguration
    instance. The file should contain a valid configuration specification.

    Args:
        path: Path to JSON configuration file.

    Returns:
        ExecutionConfiguration: Loaded configuration instance.

    Raises:
        ValueError: If JSON file is invalid or missing required fields.
        FileNotFoundError: If configuration file doesn't exist.

    Example:
        >>> config = ExecutionConfiguration.load_configuration(Path("config.json"))  # doctest: +SKIP
        >>> print(f"Workflow: {config.workflow}")  # doctest: +SKIP
        >>> print(f"Datasets: {len(config.datasets)}")  # doctest: +SKIP
    """
    with Path(path).open() as fd:
        config = json.load(fd)
    return ExecutionConfiguration.model_validate(config)

validate_assets classmethod

validate_assets(value: Any) -> Any

Normalize asset entries to AssetSpec objects.

Accepts plain RID strings, DictConfig from Hydra, AssetSpec objects, or dicts with 'rid' and optional 'cache' keys.

Source code in src/deriva_ml/execution/execution_configuration.py
 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
@field_validator("assets", mode="before")
@classmethod
def validate_assets(cls, value: Any) -> Any:
    """Normalize asset entries to AssetSpec objects.

    Accepts plain RID strings, DictConfig from Hydra, AssetSpec objects,
    or dicts with 'rid' and optional 'cache' keys.
    """
    result = []
    for v in value:
        if isinstance(v, AssetSpec):
            result.append(v)
        elif isinstance(v, dict):
            # Dict with rid/cache keys (e.g., from JSON config)
            result.append(AssetSpec(**v))
        elif isinstance(v, DictConfig):
            # OmegaConf DictConfig from Hydra — may have rid+cache or just rid
            d = dict(v)
            if "rid" in d:
                result.append(AssetSpec(**d))
            else:
                # Bare DictConfig with just a .rid attribute.
                result.append(AssetSpec(rid=v.rid, cache=getattr(v, "cache", False)))
        elif isinstance(v, str):
            result.append(AssetSpec(rid=v))
        else:
            # Unknown type — try string coercion
            result.append(AssetSpec(rid=str(v)))
    return result

ExecutionSummary

Bases: BaseModel

Compact view of an Execution row.

Surfaces just enough to identify the execution and decide whether to drill in. Use ml.lookup_execution(rid) for the live ExecutionRecord.

Attributes:

Name Type Description
rid RID

Execution RID.

description str | None

Execution description (may be None or empty).

workflow WorkflowSummary | None

Compact workflow descriptor (None if the execution has no workflow link).

status str

Catalog status string (e.g. "Uploaded").

Source code in src/deriva_ml/execution/lineage.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class ExecutionSummary(BaseModel):
    """Compact view of an Execution row.

    Surfaces just enough to identify the execution and decide whether
    to drill in. Use ``ml.lookup_execution(rid)`` for the live
    ``ExecutionRecord``.

    Attributes:
        rid: Execution RID.
        description: Execution description (may be None or empty).
        workflow: Compact workflow descriptor (None if the execution
            has no workflow link).
        status: Catalog status string (e.g. ``"Uploaded"``).
    """

    model_config = ConfigDict(extra="forbid")

    rid: RID
    description: str | None = None
    workflow: WorkflowSummary | None = None
    status: str

LineageNode

Bases: BaseModel

One execution node in the lineage tree.

Each node represents an execution that produced something further down the chain. parents holds the next layer up — the producing executions of this execution's consumed inputs.

Attributes:

Name Type Description
execution ExecutionSummary

Compact execution descriptor for this node.

consumed_datasets list[DatasetSummary]

Datasets this execution consumed as input.

consumed_assets list[AssetSummary]

Assets this execution consumed as input (asset_role="Input" in the <AssetTable>_Execution association).

parents list['LineageNode']

Producing executions of the consumed inputs. Deduplicated by execution RID.

already_shown bool

True if this execution was already expanded elsewhere in the tree (diamond DAG marker). When True, parents is left empty to avoid re-walking; consumers should look up the original node by execution.rid.

Source code in src/deriva_ml/execution/lineage.py
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
class LineageNode(BaseModel):
    """One execution node in the lineage tree.

    Each node represents an execution that produced something further
    down the chain. ``parents`` holds the next layer up — the
    producing executions of this execution's consumed inputs.

    Attributes:
        execution: Compact execution descriptor for this node.
        consumed_datasets: Datasets this execution consumed as input.
        consumed_assets: Assets this execution consumed as input
            (asset_role="Input" in the ``<AssetTable>_Execution``
            association).
        parents: Producing executions of the consumed inputs.
            Deduplicated by execution RID.
        already_shown: True if this execution was already expanded
            elsewhere in the tree (diamond DAG marker). When True,
            ``parents`` is left empty to avoid re-walking; consumers
            should look up the original node by ``execution.rid``.
    """

    model_config = ConfigDict(extra="forbid")

    execution: ExecutionSummary
    consumed_datasets: list[DatasetSummary] = Field(default_factory=list)
    consumed_assets: list[AssetSummary] = Field(default_factory=list)
    parents: list["LineageNode"] = Field(default_factory=list)
    already_shown: bool = False

LineageResult

Bases: BaseModel

Result returned by :meth:DerivaML.lookup_lineage.

Top-level transparency fields tell the caller whether the walk completed cleanly. walked_complete=False means the walk hit one of the defensive caps (max_executions) before reaching the root.

Attributes:

Name Type Description
root RootDescriptor

Descriptor of the artifact the walk started from.

lineage LineageNode | None

Tree of producing executions, rooted at the immediate producer of root. None when the root has no recorded producer.

executions_visited int

Number of distinct executions the walk expanded. Includes the root execution when present.

walked_complete bool

True if the walk ran to the natural root of every branch. False if max_executions was hit or a depth cap stopped the expansion.

cycle_detected bool

True if a true cycle was detected (the same execution appearing on its own active recursion path). Diamond DAGs (the same execution reached via two independent paths) are NOT cycles; they're handled by the already_shown flag on :class:LineageNode.

depth_capped bool

True if a positive depth argument prevented expansion of at least one branch.

Example

Walk lineage of an output asset and pretty-print the chain::

>>> result = ml.lookup_lineage("3JSE")  # doctest: +SKIP
>>> assert result.walked_complete  # doctest: +SKIP
>>> print(f"visited {result.executions_visited} executions")  # doctest: +SKIP
Source code in src/deriva_ml/execution/lineage.py
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
class LineageResult(BaseModel):
    """Result returned by :meth:`DerivaML.lookup_lineage`.

    Top-level transparency fields tell the caller whether the walk
    completed cleanly. ``walked_complete=False`` means the walk hit
    one of the defensive caps (``max_executions``) before reaching
    the root.

    Attributes:
        root: Descriptor of the artifact the walk started from.
        lineage: Tree of producing executions, rooted at the
            immediate producer of ``root``. None when the root has
            no recorded producer.
        executions_visited: Number of distinct executions the walk
            expanded. Includes the root execution when present.
        walked_complete: True if the walk ran to the natural root of
            every branch. False if ``max_executions`` was hit or a
            depth cap stopped the expansion.
        cycle_detected: True if a true cycle was detected (the same
            execution appearing on its own active recursion path).
            Diamond DAGs (the same execution reached via two
            independent paths) are NOT cycles; they're handled by
            the ``already_shown`` flag on :class:`LineageNode`.
        depth_capped: True if a positive ``depth`` argument
            prevented expansion of at least one branch.

    Example:
        Walk lineage of an output asset and pretty-print the chain::

            >>> result = ml.lookup_lineage("3JSE")  # doctest: +SKIP
            >>> assert result.walked_complete  # doctest: +SKIP
            >>> print(f"visited {result.executions_visited} executions")  # doctest: +SKIP
    """

    model_config = ConfigDict(extra="forbid")

    root: RootDescriptor
    lineage: LineageNode | None = None
    executions_visited: int = 0
    walked_complete: bool = True
    cycle_detected: bool = False
    depth_capped: bool = False

MultirunSpec dataclass

Specification for a multirun experiment.

Attributes:

Name Type Description
name str

Unique identifier for this multirun configuration.

overrides list[str]

List of Hydra override strings (same syntax as command line). Examples: - "+experiment=cifar10_quick,cifar10_extended" - "model_config.learning_rate=0.0001,0.001,0.01" - "model_config.epochs=5,10,25,50"

description str

Rich description for the parent execution. Supports full markdown formatting (headers, tables, bold, etc.).

Source code in src/deriva_ml/execution/multirun_config.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@dataclass
class MultirunSpec:
    """Specification for a multirun experiment.

    Attributes:
        name: Unique identifier for this multirun configuration.
        overrides: List of Hydra override strings (same syntax as command line).
            Examples:
            - "+experiment=cifar10_quick,cifar10_extended"
            - "model_config.learning_rate=0.0001,0.001,0.01"
            - "model_config.epochs=5,10,25,50"
        description: Rich description for the parent execution. Supports full
            markdown formatting (headers, tables, bold, etc.).
    """

    name: str
    overrides: list[str] = field(default_factory=list)
    description: str = ""

RootDescriptor

Bases: BaseModel

Describes the artifact the lineage walk started from.

Attributes:

Name Type Description
rid RID

RID of the root artifact passed to lookup_lineage.

type Literal['Dataset', 'Asset', 'Feature', 'Execution']

One of "Dataset", "Asset", "Feature", or "Execution". Determines how producing_execution was resolved.

description str | None

Description of the root, when available (Dataset.description, Asset.description, Execution.description). None for Feature values, which don't have a free-text description column at this layer.

producing_execution ExecutionSummary | None

The execution that produced this artifact, or None if the artifact has no recorded producer (manually inserted data, etc.). For an Execution root, this is the execution itself.

Source code in src/deriva_ml/execution/lineage.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
class RootDescriptor(BaseModel):
    """Describes the artifact the lineage walk started from.

    Attributes:
        rid: RID of the root artifact passed to ``lookup_lineage``.
        type: One of ``"Dataset"``, ``"Asset"``, ``"Feature"``, or
            ``"Execution"``. Determines how
            ``producing_execution`` was resolved.
        description: Description of the root, when available
            (Dataset.description, Asset.description,
            Execution.description). None for Feature values, which
            don't have a free-text description column at this layer.
        producing_execution: The execution that produced this
            artifact, or None if the artifact has no recorded
            producer (manually inserted data, etc.). For an
            Execution root, this is the execution itself.
    """

    model_config = ConfigDict(extra="forbid")

    rid: RID
    type: Literal["Dataset", "Asset", "Feature", "Execution"]
    description: str | None = None
    producing_execution: ExecutionSummary | None = None

Workflow

Bases: BaseModel

Represents a computational workflow in DerivaML.

A workflow defines a computational process or analysis pipeline. Each workflow has a unique identifier, source code location, and type. Workflows are typically associated with Git repositories for version control.

When a Workflow is retrieved via lookup_workflow(rid) or lookup_workflow_by_url(), it is bound to a catalog and its description and workflow_type properties become writable. Setting these properties will update the catalog record. If the catalog is read-only (a snapshot), attempting to set them will raise a DerivaMLException.

Attributes:

Name Type Description
name str

Human-readable name of the workflow.

url str

URI to the workflow source code (typically a GitHub URL).

workflow_type str | list[str]

Type(s) of workflow (must be controlled vocabulary terms). Accepts a single string or a list of strings. Internally normalized to a list. When the workflow is bound to a writable catalog, setting this property will update the catalog record. The new values must be valid terms from the Workflow_Type vocabulary.

version str | None

Version identifier (semantic versioning).

description str | None

Description of workflow purpose and behavior. When the workflow is bound to a writable catalog, setting this property will update the catalog record.

workflow_rid RID | None

Resource Identifier if registered in catalog.

checksum str | None

Git hash of workflow source code.

is_notebook bool

Whether workflow is a Jupyter notebook.

git_root Path | None

Filesystem root of the git checkout the source was resolved from, when known. Used to scope dynamic-version resolution; None when no git checkout was detected.

allow_dirty bool

When True, uncommitted changes in the source's git worktree are downgraded from a hard error to a warning (set by the --allow-dirty CLI flag, dry-run mode, or DERIVA_ML_ALLOW_DIRTY). Defaults to False, which keeps the clean-checkout precondition that makes provenance reproducible.

Note

The recommended way to create a Workflow is via :meth:DerivaML.create_workflow() <deriva_ml.DerivaML.create_workflow>, which validates the workflow type against the catalog vocabulary::

>>> workflow = ml.create_workflow(  # doctest: +SKIP
...     name="RNA Analysis",
...     workflow_type="python_notebook",
...     description="RNA sequence analysis"
... )
Example

Create a workflow directly (without catalog validation)::

>>> workflow = Workflow(  # doctest: +SKIP
...     name="RNA Analysis",
...     url="https://github.com/org/repo/analysis.ipynb",
...     workflow_type="python_notebook",
...     version="1.0.0",
...     description="RNA sequence analysis"
... )

Look up an existing workflow by RID and update its properties::

>>> workflow = ml.lookup_workflow("2-ABC1")  # doctest: +SKIP
>>> workflow.description = "Updated description for RNA analysis"  # doctest: +SKIP
>>> workflow.workflow_type = "python_script"  # doctest: +SKIP
>>> print(workflow.description)  # doctest: +SKIP
Updated description for RNA analysis

Look up by URL and update::

>>> url = "https://github.com/org/repo/blob/abc123/analysis.py"  # doctest: +SKIP
>>> workflow = ml.lookup_workflow_by_url(url)  # doctest: +SKIP
>>> workflow.description = "New description"  # doctest: +SKIP

Attempting to update on a read-only catalog raises an error::

>>> snapshot_ml = ml.catalog_snapshot("2023-01-15T10:30:00")  # doctest: +SKIP
>>> workflow = snapshot_ml.lookup_workflow("2-ABC1")  # doctest: +SKIP
>>> workflow.description = "New description"  # Raises DerivaMLException  # doctest: +SKIP
Source code in src/deriva_ml/execution/workflow.py
 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
class Workflow(BaseModel):
    """Represents a computational workflow in DerivaML.

    A workflow defines a computational process or analysis pipeline. Each workflow has
    a unique identifier, source code location, and type. Workflows are typically
    associated with Git repositories for version control.

    When a Workflow is retrieved via ``lookup_workflow(rid)`` or ``lookup_workflow_by_url()``,
    it is bound to a catalog and its ``description`` and ``workflow_type`` properties become
    writable. Setting these properties will update the catalog record. If the catalog is
    read-only (a snapshot), attempting to set them will raise a ``DerivaMLException``.

    Attributes:
        name (str): Human-readable name of the workflow.
        url (str): URI to the workflow source code (typically a GitHub URL).
        workflow_type (str | list[str]): Type(s) of workflow (must be controlled vocabulary terms).
            Accepts a single string or a list of strings. Internally normalized to a list.
            When the workflow is bound to a writable catalog, setting this property
            will update the catalog record. The new values must be valid terms from
            the Workflow_Type vocabulary.
        version (str | None): Version identifier (semantic versioning).
        description (str | None): Description of workflow purpose and behavior.
            When the workflow is bound to a writable catalog, setting this property
            will update the catalog record.
        workflow_rid (RID | None): Resource Identifier if registered in catalog.
        checksum (str | None): Git hash of workflow source code.
        is_notebook (bool): Whether workflow is a Jupyter notebook.
        git_root (Path | None): Filesystem root of the git checkout the source
            was resolved from, when known. Used to scope dynamic-version
            resolution; ``None`` when no git checkout was detected.
        allow_dirty (bool): When True, uncommitted changes in the source's git
            worktree are downgraded from a hard error to a warning (set by the
            ``--allow-dirty`` CLI flag, dry-run mode, or
            ``DERIVA_ML_ALLOW_DIRTY``). Defaults to False, which keeps the
            clean-checkout precondition that makes provenance reproducible.

    Note:
        The recommended way to create a Workflow is via :meth:`DerivaML.create_workflow()
        <deriva_ml.DerivaML.create_workflow>`, which validates the workflow type against
        the catalog vocabulary::

            >>> workflow = ml.create_workflow(  # doctest: +SKIP
            ...     name="RNA Analysis",
            ...     workflow_type="python_notebook",
            ...     description="RNA sequence analysis"
            ... )

    Example:
        Create a workflow directly (without catalog validation)::

            >>> workflow = Workflow(  # doctest: +SKIP
            ...     name="RNA Analysis",
            ...     url="https://github.com/org/repo/analysis.ipynb",
            ...     workflow_type="python_notebook",
            ...     version="1.0.0",
            ...     description="RNA sequence analysis"
            ... )

        Look up an existing workflow by RID and update its properties::

            >>> workflow = ml.lookup_workflow("2-ABC1")  # doctest: +SKIP
            >>> workflow.description = "Updated description for RNA analysis"  # doctest: +SKIP
            >>> workflow.workflow_type = "python_script"  # doctest: +SKIP
            >>> print(workflow.description)  # doctest: +SKIP
            Updated description for RNA analysis

        Look up by URL and update::

            >>> url = "https://github.com/org/repo/blob/abc123/analysis.py"  # doctest: +SKIP
            >>> workflow = ml.lookup_workflow_by_url(url)  # doctest: +SKIP
            >>> workflow.description = "New description"  # doctest: +SKIP

        Attempting to update on a read-only catalog raises an error::

            >>> snapshot_ml = ml.catalog_snapshot("2023-01-15T10:30:00")  # doctest: +SKIP
            >>> workflow = snapshot_ml.lookup_workflow("2-ABC1")  # doctest: +SKIP
            >>> workflow.description = "New description"  # Raises DerivaMLException  # doctest: +SKIP
    """

    # extra="forbid" guards against the silent kwarg-drop that masked the
    # rid -> workflow_rid rename regression (#226): the renamed field was
    # passed under its old name, Pydantic dropped the unknown kwarg without
    # error, and every find_workflows()/lookup_workflow() result silently
    # carried workflow_rid=None. Forbidding extra fields turns that class of
    # mistake into a loud ValidationError at construction time. Scoped to
    # Workflow only (mirrors the existing STRICT_VALIDATION_CONFIG idiom in
    # core/validation.py) rather than widening the shared VALIDATION_CONFIG.
    model_config = {**VALIDATION_CONFIG, "extra": "forbid"}

    name: str
    workflow_type: str | list[str]
    description: str | None = None
    url: str | None = None
    version: str | None = None
    workflow_rid: RID | None = None
    checksum: str | None = None
    is_notebook: bool = False
    git_root: Path | None = None
    allow_dirty: bool = False

    _ml_instance: "DerivaMLCatalog | None" = PrivateAttr(default=None)
    _logger: logging.Logger = PrivateAttr(default_factory=lambda: get_logger(__name__))

    @model_validator(mode="before")
    @classmethod
    def _migrate_legacy_rid_key(cls, data: Any) -> Any:
        """Map the pre-#226 legacy ``rid`` key to ``workflow_rid``.

        Workflow substructures serialized before the ``rid -> workflow_rid``
        rename (#226) -- e.g. the ``workflow`` block of older
        ``configuration.json`` execution-metadata files -- carry a ``rid``
        key. The current model renamed that field and sets ``extra="forbid"``
        (see ``model_config`` below), so those legacy payloads would otherwise
        fail to parse with ``rid -- extra_forbidden``.

        This normalizer renames ``rid`` to ``workflow_rid`` *before* validation
        so legacy configs load, WITHOUT relaxing ``extra="forbid"`` -- a
        genuinely-unknown field (the case #226's guard exists to catch) still
        raises. The canonical ``workflow_rid`` always wins when both keys are
        present (including an explicit ``workflow_rid=None``, via
        ``setdefault``), so a correctly-shaped payload is never altered.

        Only dict inputs are touched; non-dict inputs (e.g. an already-built
        ``Workflow`` instance) pass through untouched.
        """
        if isinstance(data, dict) and "rid" in data:
            # Copy rather than mutate the caller's dict -- a validator must not
            # have side effects on its input (the same payload may be reused).
            data = dict(data)
            legacy_rid = data.pop("rid")
            # Don't clobber a canonical value if both keys somehow appear.
            data.setdefault("workflow_rid", legacy_rid)
        return data

    @field_validator("workflow_type", mode="before")
    @classmethod
    def _normalize_workflow_type(cls, v: str | list[str]) -> list[str]:
        """Normalize workflow_type to always be a list of strings."""
        if isinstance(v, str):
            return [v]
        return list(v)

    def __setattr__(self, name: str, value: Any) -> None:
        """Override setattr to intercept description and workflow_type updates.

        When the workflow is bound to a catalog (via lookup_workflow), setting
        the ``description`` or ``workflow_type`` properties will update the catalog
        record. If the catalog is read-only (a snapshot), a DerivaMLException is raised.

        Args:
            name: The attribute name being set.
            value: The value to set.

        Raises:
            DerivaMLException: If attempting to set properties on a read-only
                catalog (snapshot), or if workflow_type is not a valid vocabulary term.

        Examples:
            Update description::

                >>> workflow = ml.lookup_workflow("2-ABC1")  # doctest: +SKIP
                >>> workflow.description = "Updated description"  # doctest: +SKIP

            Update workflow type::

                >>> workflow = ml.lookup_workflow("2-ABC1")  # doctest: +SKIP
                >>> workflow.workflow_type = "python_notebook"  # doctest: +SKIP
        """
        # Only intercept updates after full initialization
        # Use __dict__ check to avoid recursion during Pydantic model construction
        if (
            "__pydantic_private__" in self.__dict__
            and self.__dict__.get("__pydantic_private__", {}).get("_ml_instance") is not None
        ):
            if name == "description":
                self._update_description_in_catalog(value)
            elif name == "workflow_type":
                # Normalize to list
                if isinstance(value, str):
                    value = [value]
                self._update_workflow_types_in_catalog(value)
        super().__setattr__(name, value)

    def _check_writable_catalog(self, operation: str) -> None:
        """Check that the catalog is writable and workflow is registered.

        Delegates to the shared free helper in
        :mod:`deriva_ml.execution._helpers` — same contract used
        by :class:`ExecutionRecord`. Kept as a thin instance
        method so the in-class call sites (``description`` setter,
        ``_update_description_in_catalog``) read naturally.

        Args:
            operation: Description of the operation being attempted.

        Raises:
            DerivaMLException: If the workflow is not registered (no RID),
                or if the catalog is read-only (a snapshot).
        """
        from deriva_ml.execution._helpers import check_writable_catalog

        check_writable_catalog(
            rid=self.workflow_rid,
            ml_instance=self._ml_instance,
            entity_label="Workflow",
            operation=operation,
        )

    def _update_description_in_catalog(self, new_description: str | None) -> None:
        """Update the description field in the catalog.

        This internal method is called when the description property is set
        on a catalog-bound Workflow object.

        Args:
            new_description: The new description value.

        Raises:
            DerivaMLException: If the workflow is not registered (no RID),
                or if the catalog is read-only (a snapshot).
        """
        from deriva_ml.execution._helpers import update_field_in_catalog

        self._check_writable_catalog("update description")
        update_field_in_catalog(
            rid=self.workflow_rid,
            ml_instance=self._ml_instance,
            table_name="Workflow",
            updates={"Description": new_description},
        )

    def _get_workflow_type_association_table(self):
        """Get the association table for workflow types.

        Returns:
            Tuple of (table_name, table_path) for the Workflow-Workflow_Type association table.
        """
        atable_name = "Workflow_Workflow_Type"
        pb = self._ml_instance.pathBuilder()
        atable_path = pb.schemas[self._ml_instance.ml_schema].tables[atable_name]
        return atable_name, atable_path

    @property
    def workflow_types(self) -> list[str]:
        """Get the workflow types from the catalog.

        This property fetches the current workflow types directly from the catalog,
        ensuring consistency when multiple Workflow instances reference the same
        workflow or when types are modified externally.

        When not bound to a catalog, returns the local ``workflow_type`` field.

        Returns:
            List of workflow type term names from the Workflow_Type vocabulary.
        """
        if self._ml_instance is not None:
            _, atable_path = self._get_workflow_type_association_table()
            wt_types = (
                atable_path.filter(atable_path.Workflow == self.workflow_rid)
                .attributes(atable_path.Workflow_Type)
                .fetch()
            )
            return [wt[MLVocab.workflow_type] for wt in wt_types]
        return list(self.workflow_type)

    def add_workflow_type(self, workflow_type: str | VocabularyTerm) -> None:
        """Add a workflow type to this workflow.

        Adds a type term to this workflow if it's not already present. The term must
        exist in the Workflow_Type vocabulary.

        Args:
            workflow_type: Term name (string) or VocabularyTerm object from Workflow_Type vocabulary.

        Raises:
            DerivaMLException: If the workflow is not registered (no RID),
                the catalog is read-only, or the term doesn't exist.
        """
        self._check_writable_catalog("add workflow_type")

        if isinstance(workflow_type, VocabularyTerm):
            vocab_term = workflow_type
        else:
            vocab_term = self._ml_instance.lookup_term(MLVocab.workflow_type, workflow_type)

        if vocab_term.name in self.workflow_types:
            return

        _, atable_path = self._get_workflow_type_association_table()
        atable_path.insert([{MLVocab.workflow_type: vocab_term.name, "Workflow": self.workflow_rid}])

    def remove_workflow_type(self, workflow_type: str | VocabularyTerm) -> None:
        """Remove a workflow type from this workflow.

        Removes a type term from this workflow if it's currently associated.

        Args:
            workflow_type: Term name (string) or VocabularyTerm object from Workflow_Type vocabulary.

        Raises:
            DerivaMLException: If the workflow is not registered (no RID),
                the catalog is read-only, or the term doesn't exist.
        """
        self._check_writable_catalog("remove workflow_type")

        if isinstance(workflow_type, VocabularyTerm):
            vocab_term = workflow_type
        else:
            vocab_term = self._ml_instance.lookup_term(MLVocab.workflow_type, workflow_type)

        if vocab_term.name not in self.workflow_types:
            return

        _, atable_path = self._get_workflow_type_association_table()
        atable_path.filter(
            (atable_path.Workflow == self.workflow_rid) & (atable_path.Workflow_Type == vocab_term.name)
        ).delete()

    def add_workflow_types(self, workflow_types: str | VocabularyTerm | list[str | VocabularyTerm]) -> None:
        """Add one or more workflow types to this workflow.

        Args:
            workflow_types: Single term or list of terms. Can be strings (term names)
                or VocabularyTerm objects.

        Raises:
            DerivaMLException: If any term doesn't exist in the Workflow_Type vocabulary.
        """
        types_to_add = [workflow_types] if not isinstance(workflow_types, list) else workflow_types

        for term in types_to_add:
            self.add_workflow_type(term)

    def _update_workflow_types_in_catalog(self, new_workflow_types: list[str]) -> None:
        """Replace all workflow types in the catalog with the given list.

        This internal method is called when the workflow_type property is set
        on a catalog-bound Workflow object. Each new type must be a valid
        term from the Workflow_Type vocabulary.

        Args:
            new_workflow_types: List of new workflow type names.

        Raises:
            DerivaMLException: If the workflow is not registered (no RID),
                the catalog is read-only (a snapshot), or any workflow_type
                is not a valid vocabulary term.
        """
        self._check_writable_catalog("update workflow_type")

        # Validate all new types exist in vocabulary
        for wt in new_workflow_types:
            self._ml_instance.lookup_term(MLVocab.workflow_type, wt)

        # Delete all existing type associations
        _, atable_path = self._get_workflow_type_association_table()
        atable_path.filter(atable_path.Workflow == self.workflow_rid).delete()

        # Insert new type associations
        if new_workflow_types:
            atable_path.insert(
                [{MLVocab.workflow_type: wt, "Workflow": self.workflow_rid} for wt in new_workflow_types]
            )

    @model_validator(mode="after")
    def setup_url_checksum(self) -> "Workflow":
        """Pydantic post-construction validator that fills in ``url`` and ``checksum``.

        Runs automatically after every ``Workflow(...)`` construction
        (it is a ``@model_validator(mode="after")``). For any field
        the caller did not provide, the validator derives a value from
        the current execution context:

        - ``url`` — set to the resolved source URL of the calling
          script/notebook. Resolution prefers a Docker image
          identifier (when ``DERIVA_MCP_IN_DOCKER=true``), otherwise a
          GitHub ``/blob/<commit>/<path>`` URL from the local git
          checkout. When the script is not in a git repo and
          ``allow_dirty=True``, ``url`` is left empty (``""``) — there
          is no ``file://`` fallback.
        - ``checksum`` — set to the git commit SHA of the calling
          script (or the Docker image digest when running in Docker).
        - ``version`` — in the local-git path (the common case) it is
          set from ``get_dynamic_version()`` (the version derived from
          the local git checkout); in the Docker path it is set from
          ``DERIVA_MCP_VERSION`` instead.

        Caller-supplied values are never overwritten — this is a
        "fill in the blanks" validator, not a re-derivation.

        Environment variable overrides:
            - ``DERIVA_ML_WORKFLOW_URL``: force-set ``url``.
            - ``DERIVA_ML_WORKFLOW_CHECKSUM``: force-set ``checksum``.
            - ``DERIVA_MCP_IN_DOCKER=true``: use Docker image metadata
              instead of git.

        Docker-only environment variables (consulted when
        ``DERIVA_MCP_IN_DOCKER=true``):
            - ``DERIVA_MCP_VERSION``: semantic version of the Docker image.
            - ``DERIVA_MCP_GIT_COMMIT``: git commit hash at image build time.
            - ``DERIVA_MCP_IMAGE_DIGEST``: image digest (unique identifier).
            - ``DERIVA_MCP_IMAGE_NAME``: image name (e.g.
              ``ghcr.io/informatics-isi-edu/deriva-ml-mcp``).

        Returns:
            Workflow: ``self`` (the same instance, mutated in place).
            Pydantic ``mode="after"`` validators must return the
            model.

        Raises:
            DerivaMLException: If the validator cannot determine a
                URL or checksum from any source (e.g. not in a git
                repo, Docker env vars missing, no explicit overrides).
        """
        self._logger = get_logger(__name__)

        # Loaded from a catalog row: provenance is already known.
        # ``workflow_rid`` is set only for a workflow that already exists in
        # the catalog (``lookup_workflow`` / ``find_workflows`` pass it; the
        # create path does not). Its ``url`` / ``checksum`` / ``version`` are
        # stored columns, so re-deriving them from the runtime environment is
        # both wrong and fragile -- the derivation calls setuptools-scm and
        # raises in any non-git, non-Docker working directory. Trust the
        # stored values and skip all derivation.
        if self.workflow_rid is not None:
            return self

        # Check if running in Docker container (no git repo available)
        if os.environ.get("DERIVA_MCP_IN_DOCKER", "").lower() == "true":
            # Use Docker image metadata for provenance
            self.version = self.version or os.environ.get("DERIVA_MCP_VERSION", "")

            # Use image digest as checksum (unique identifier for the container)
            # Fall back to git commit if digest not available
            self.checksum = self.checksum or (
                os.environ.get("DERIVA_MCP_IMAGE_DIGEST", "") or os.environ.get("DERIVA_MCP_GIT_COMMIT", "")
            )

            # Build URL pointing to the Docker image or source repo
            if not self.url:
                image_name = os.environ.get(
                    "DERIVA_MCP_IMAGE_NAME",
                    "ghcr.io/informatics-isi-edu/deriva-ml-mcp",
                )
                image_digest = os.environ.get("DERIVA_MCP_IMAGE_DIGEST", "")
                if image_digest:
                    # URL format: image@sha256:digest
                    self.url = f"{image_name}@{image_digest}"
                else:
                    # Fall back to source repo with git commit
                    source_url = "https://github.com/informatics-isi-edu/deriva-ml-mcp"
                    git_commit = os.environ.get("DERIVA_MCP_GIT_COMMIT", "")
                    self.url = f"{source_url}/commit/{git_commit}" if git_commit else source_url

            return self

        # Check to see if execution file info is being passed in by calling program (notebook runner)
        if "DERIVA_ML_WORKFLOW_URL" in os.environ:
            self.url = os.environ["DERIVA_ML_WORKFLOW_URL"]
            self.checksum = os.environ.get("DERIVA_ML_WORKFLOW_CHECKSUM", "")
            notebook_path = os.environ.get("DERIVA_ML_NOTEBOOK_PATH")
            if notebook_path:
                self.git_root = Workflow._get_git_root(Path(notebook_path))
            self.is_notebook = True
            return self

        # Standard git detection for local development
        # Check env var for allow_dirty (set by CLI --allow-dirty flag or dry-run mode)
        if os.environ.get("DERIVA_ML_ALLOW_DIRTY", "").lower() == "true":
            self.allow_dirty = True
        if os.environ.get("DERIVA_ML_DRY_RUN", "").lower() == "true":
            self.allow_dirty = True

        if not self.url:
            path, self.is_notebook = Workflow._get_python_script()
            self.url, self.checksum = Workflow.get_url_and_checksum(path, allow_dirty=self.allow_dirty)
            self.git_root = Workflow._get_git_root(path)

        self.version = self.version or Workflow.get_dynamic_version(root=str(self.git_root or Path.cwd()))
        return self

    @staticmethod
    def get_url_and_checksum(executable_path: Path, allow_dirty: bool = False) -> tuple[str, str]:
        """Determines the Git URL and checksum for a file.

        Computes the Git repository URL and file checksum for the specified path.
        For notebooks, strips cell outputs before computing the checksum.

        Args:
            executable_path: Path to the workflow file.
            allow_dirty: If True, log a warning instead of raising an error
                when the file has uncommitted changes. Defaults to False.

        Returns:
            tuple[str, str]: (GitHub URL, Git object hash)

        Raises:
            DerivaMLException: If not in a Git repository.
            DerivaMLDirtyWorkflowError: If the file has uncommitted changes
                and allow_dirty is False.

        Example:
            >>> url, checksum = Workflow.get_url_and_checksum(Path("analysis.ipynb"))  # doctest: +SKIP
            >>> print(f"URL: {url}")  # doctest: +SKIP
            >>> print(f"Checksum: {checksum}")  # doctest: +SKIP
        """
        # The "must be inside a git checkout" guard is a precondition
        # for honest provenance. But ``allow_dirty=True`` is the
        # documented escape hatch for ad-hoc / dry-run / notebook
        # workflows that don't need a clean checkout — refusing to
        # run those because the cwd isn't inside git defeats the
        # intent of the flag. When ``allow_dirty=True``, downgrade
        # the no-git precondition to a warning and return empty
        # provenance (URL/checksum both empty strings); when False
        # (the default), keep the hard refuse.
        try:
            subprocess.run(
                ["git", "rev-parse", "--is-inside-work-tree"],
                capture_output=True,
                text=True,
                check=True,
            )
        except subprocess.CalledProcessError:
            if allow_dirty:
                logger.warning(
                    "Not executing in a Git repository; allow_dirty=True, "
                    "returning empty URL/checksum. Provenance will not be "
                    "recoverable for this workflow."
                )
                return "", ""
            raise DerivaMLException("Not executing in a Git repository.")

        github_url, dirty_paths = Workflow._github_url(executable_path)

        if dirty_paths:
            if allow_dirty:
                offending = ", ".join(p.strip() for p in dirty_paths[:3])
                more = f" (and {len(dirty_paths) - 3} more)" if len(dirty_paths) > 3 else ""
                logger.warning(
                    f"Worktree has uncommitted changes affecting provenance: "
                    f"{offending}{more}. Proceeding with --allow-dirty override."
                )
            else:
                raise DerivaMLDirtyWorkflowError(str(executable_path), dirty_paths=dirty_paths)

        # If you are in a notebook, strip out the outputs before computing the checksum.
        if executable_path != "REPL":
            if "ipynb" == executable_path.suffix:
                strip_proc = subprocess.run(
                    ["nbstripout", "-t", str(executable_path)],
                    capture_output=True,
                )
                hash_proc = subprocess.run(
                    ["git", "hash-object", "--stdin"],
                    input=strip_proc.stdout,
                    capture_output=True,
                    text=True,
                )
                checksum = hash_proc.stdout.strip()
            else:
                checksum = subprocess.run(
                    ["git", "hash-object", str(executable_path)],
                    capture_output=True,
                    text=True,
                    check=False,
                ).stdout.strip()
        else:
            checksum = "1"
        return github_url, checksum

    # Default paths excluded from the dirty-tree check. These are
    # directories the project conventions treat as scratch / output /
    # findings space — not code the workflow could have read, so changes
    # under them don't affect provenance.
    _DEFAULT_DIRTY_CHECK_EXCLUSIONS: ClassVar[tuple[str, ...]] = (
        "findings/",
        "outputs/",
        ".scratch/",
    )

    @staticmethod
    def _filter_dirty_paths(porcelain_output: str) -> list[str]:
        """Parse ``git status --porcelain`` output, drop excluded paths.

        Lines whose target path sits under one of the default exclusion
        prefixes (``findings/``, ``outputs/``, ``.scratch/``) or under
        any prefix from the ``DERIVA_ML_DIRTY_CHECK_IGNORE`` env var
        (colon-separated, ``PATH``-like) are removed. The remaining lines
        — actual code/config changes — are returned in order.

        The helper handles git-status rename lines (``R  old -> new``)
        by checking the destination path; if the destination is under an
        excluded prefix the line is dropped.

        Args:
            porcelain_output: Raw stdout from ``git status --porcelain``.
                May be empty (clean tree).

        Returns:
            A list of porcelain lines (verbatim, including the two-letter
            status code) that survived the exclusion filter. Empty list
            means "tree is clean for provenance purposes."

        Example:
            >>> Workflow._filter_dirty_paths(" M src/models/train.py\\n?? findings/x.txt\\n")
            [' M src/models/train.py']
        """
        if not porcelain_output.strip():
            return []

        # Build the full exclusion list: built-in defaults + env-var extras.
        # Env-var format mirrors PATH (colon-separated). An empty string
        # value means "no extra exclusions" (NOT a single empty-prefix
        # that would match every path).
        extra = os.environ.get("DERIVA_ML_DIRTY_CHECK_IGNORE", "")
        extra_prefixes = tuple(p for p in extra.split(":") if p)
        exclusions = Workflow._DEFAULT_DIRTY_CHECK_EXCLUSIONS + extra_prefixes

        kept: list[str] = []
        for line in porcelain_output.splitlines():
            if not line.strip():
                continue
            # Porcelain format: two status chars, a space, then the path.
            # Renames are written as ``R  old -> new``; we want to match
            # against the destination.
            path_part = line[3:]
            if " -> " in path_part:
                path_part = path_part.split(" -> ", 1)[1]
            if any(path_part.startswith(prefix) for prefix in exclusions):
                continue
            kept.append(line)
        return kept

    @staticmethod
    def _get_git_root(executable_path: Path) -> str | None:
        """Gets the root directory of the Git repository.

        Args:
            executable_path: Path to check for Git repository.

        Returns:
            str | None: Absolute path to repository root, or None if not in repository.
        """
        try:
            result = subprocess.run(
                ["git", "rev-parse", "--show-toplevel"],
                cwd=executable_path.parent,
                stdout=subprocess.PIPE,
                stderr=subprocess.DEVNULL,
                text=True,
                check=True,
            )
            return result.stdout.strip()
        except subprocess.CalledProcessError:
            return None  # Not in a git repository

    @staticmethod
    def _check_nbstrip_status() -> None:
        """Checks if nbstripout is installed and configured.

        Verifies that the nbstripout tool is available and properly installed in the
        Git repository. Issues warnings if setup is incomplete.
        """
        logger = get_logger(__name__)
        try:
            if subprocess.run(
                ["nbstripout", "--is-installed"],
                check=False,
                capture_output=True,
            ).returncode:
                logger.warning("nbstripout is not installed in repository. Please run nbstripout --install")
        except (subprocess.CalledProcessError, FileNotFoundError):
            logger.warning("nbstripout is not found. Please install it with: pip install nbstripout")

    @staticmethod
    def _in_repl():
        # Standard Python interactive mode
        if hasattr(sys, "ps1"):
            return True

        # Interactive mode forced by -i
        if sys.flags.interactive:
            return True

        # IPython / Jupyter detection
        try:
            from IPython import get_ipython

            if get_ipython() is not None:
                return True
        except ImportError:
            pass

        return False

    @staticmethod
    def _get_python_script() -> tuple[Path, bool]:
        """Return the path to the currently executing script.

        Returns:
            ``(script_path, is_notebook)`` — ``script_path`` is the
            resolved absolute path; ``is_notebook`` is ``True`` when
            running inside a Jupyter notebook (``.ipynb`` path
            resolves).
        """
        # ``find_caller._get_notebook_path()`` is the single source
        # of truth for Jupyter session lookup (audit §2.7 / §4.6).
        from deriva_ml.execution.find_caller import _get_notebook_path

        is_notebook = _get_notebook_path() is not None
        return Path(_get_calling_module()), is_notebook

    @staticmethod
    def _github_url(executable_path: Path) -> tuple[str, list[str]]:
        """Return a GitHub URL for the latest commit of the script from which this routine is called.

        This routine is used to be called from a script or notebook (e.g., python -m file). It assumes that
        the file is in a GitHub repository and committed.  It returns a URL to the last commited version of this
        file in GitHub.

        Returns: A tuple with the github_url and a list of porcelain lines describing
            uncommitted changes that affect provenance (empty if clean).

        """

        # Get repo URL from local GitHub repo.
        if executable_path == "REPL":
            return "REPL", ["REPL"]
        # ``check=True`` is load-bearing: without it ``subprocess.run``
        # never raises, ``result.stdout`` for a missing ``origin``
        # remote is an empty string, and ``github_url`` becomes
        # ``""`` — silently recorded as provenance pointing at
        # ``/blob/<sha>/<path>`` with no host. The
        # ``CalledProcessError`` catch was unreachable until this
        # flag was added.
        try:
            result = subprocess.run(
                ["git", "remote", "get-url", "origin"],
                capture_output=True,
                text=True,
                cwd=executable_path.parent,
                check=True,
            )
            github_url = result.stdout.strip().removesuffix(".git")
        except subprocess.CalledProcessError:
            raise DerivaMLException("No GIT remote found")

        # Find the root directory for the repository
        repo_root = Workflow._get_git_root(executable_path)

        # Check whether the working tree is clean. Any non-empty
        # ``git status --porcelain`` output means *something* about
        # the repo differs from HEAD -- staged, unstaged, untracked,
        # renamed, deleted, or merge-conflicted. Provenance demands
        # we treat all of these as dirty: a workflow's recorded
        # commit hash only reproduces if every file the workflow
        # could read from the repo matches that commit.
        #
        # The previous ``"M " in result.stdout.strip()`` heuristic
        # only matched the two-letter code for "staged modified",
        # silently missing unstaged edits (`` M``), untracked files
        # (``??``), renames (``R ``), deletes (``D ``), conflicts
        # (``UU``), etc. -- exactly the cases ``DERIVA_ML_ALLOW_DIRTY``
        # is supposed to gate honesty about.
        #
        # ``_filter_dirty_paths`` then drops lines whose path sits
        # under one of the project-convention scratch/output prefixes
        # (``findings/``, ``outputs/``, ``.scratch/``) or any prefix
        # from ``DERIVA_ML_DIRTY_CHECK_IGNORE``. Those directories
        # aren't on the workflow's read path, so changes under them
        # don't compromise reproducibility.
        try:
            # ``--untracked-files=all`` expands directory-level untracked
            # entries (``?? src/``) into per-file entries (``?? src/extra.py``)
            # so the per-prefix filter and the per-path error message both
            # operate on the leaf filename rather than the parent directory.
            result = subprocess.run(
                ["git", "status", "--porcelain", "--untracked-files=all"],
                cwd=repo_root,
                capture_output=True,
                text=True,
                check=False,
            )
            dirty_paths = Workflow._filter_dirty_paths(result.stdout)
        except subprocess.CalledProcessError:
            dirty_paths = []  # If the Git command fails, assume no changes

        # Get SHA-1 hash of latest commit of the file in the
        # repository. ``check=False`` here is deliberate: a file
        # that has never been committed (a new script in a worktree
        # the user is iterating on) legitimately has no log; the
        # empty ``sha`` string yields a URL pointing at ``/blob//``,
        # which the dirty-flow already treats as a non-clean
        # provenance signal upstream.
        result = subprocess.run(
            ["git", "log", "-n", "1", "--pretty=format:%H", executable_path],
            cwd=repo_root,
            capture_output=True,
            text=True,
            check=False,
        )
        sha = result.stdout.strip()
        url = f"{github_url}/blob/{sha}/{executable_path.relative_to(repo_root)}"
        return url, dirty_paths

    @staticmethod
    def get_dynamic_version(root: str | os.PathLike | None = None) -> str:
        """Return a dynamic version string derived from VCS state.

        Wraps :func:`setuptools_scm.get_version` (the same mechanism used at
        build time). The returned string includes distance-from-tag and an
        optional ``.dirty`` suffix when the working tree has uncommitted
        changes.

        Args:
            root: Repository root to introspect. When ``None``, uses the
                installed deriva-ml package's parent directory (i.e. the
                source checkout that's being developed against).

        Returns:
            A setuptools-scm-style version string (e.g. ``"1.2.3"``,
            ``"1.2.3.post2+g1234abc"``, or ``"1.2.3.post2+g1234abc.dirty"``).

        Raises:
            RuntimeError: If ``setuptools_scm`` is not importable in the
                current environment.
        """
        # Historical note: this routine used to unconditionally set
        # ``os.environ["SETUPTOOLS_USE_DISTUTILS"] = "stdlib"`` as a
        # defensive measure against a ``_distutils_hack`` assertion that
        # older setuptools versions hit on some macOS configurations.
        #
        # That mutation is process-wide and leaks into subprocess.Popen
        # inheritance, which broke third-party packages on Python 3.12+
        # that still import ``distutils.version`` (distutils is removed
        # from the stdlib per PEP 632 but setuptools vendors it back in
        # its own package — the env var short-circuits that vendored
        # fallback). Net effect: any test that called a workflow
        # helper would poison the process env, and any later subprocess
        # under Python 3.13+ would crash importing ``distutils``.
        #
        # Python 3.12 is the floor for this project (pyproject.toml:
        # ``requires-python = ">=3.12"``) so the distutils_hack concern
        # is moot — distutils is simply gone, and setuptools's own
        # fallback handles it. We drop the env mutation entirely.
        warnings.filterwarnings(
            "ignore",
            category=UserWarning,
            module="_distutils_hack",
        )
        try:
            from setuptools_scm import get_version
        except Exception as e:  # ImportError or anything environment-specific
            raise RuntimeError(f"setuptools_scm is not available: {e}") from e

        if root is None:
            # Adjust this to point at your repo root if needed
            root = Path(__file__).resolve().parents[1]

        return get_version(root=root)

workflow_types property

workflow_types: list[str]

Get the workflow types from the catalog.

This property fetches the current workflow types directly from the catalog, ensuring consistency when multiple Workflow instances reference the same workflow or when types are modified externally.

When not bound to a catalog, returns the local workflow_type field.

Returns:

Type Description
list[str]

List of workflow type term names from the Workflow_Type vocabulary.

__setattr__

__setattr__(
    name: str, value: Any
) -> None

Override setattr to intercept description and workflow_type updates.

When the workflow is bound to a catalog (via lookup_workflow), setting the description or workflow_type properties will update the catalog record. If the catalog is read-only (a snapshot), a DerivaMLException is raised.

Parameters:

Name Type Description Default
name str

The attribute name being set.

required
value Any

The value to set.

required

Raises:

Type Description
DerivaMLException

If attempting to set properties on a read-only catalog (snapshot), or if workflow_type is not a valid vocabulary term.

Examples:

Update description::

>>> workflow = ml.lookup_workflow("2-ABC1")  # doctest: +SKIP
>>> workflow.description = "Updated description"  # doctest: +SKIP

Update workflow type::

>>> workflow = ml.lookup_workflow("2-ABC1")  # doctest: +SKIP
>>> workflow.workflow_type = "python_notebook"  # doctest: +SKIP
Source code in src/deriva_ml/execution/workflow.py
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
def __setattr__(self, name: str, value: Any) -> None:
    """Override setattr to intercept description and workflow_type updates.

    When the workflow is bound to a catalog (via lookup_workflow), setting
    the ``description`` or ``workflow_type`` properties will update the catalog
    record. If the catalog is read-only (a snapshot), a DerivaMLException is raised.

    Args:
        name: The attribute name being set.
        value: The value to set.

    Raises:
        DerivaMLException: If attempting to set properties on a read-only
            catalog (snapshot), or if workflow_type is not a valid vocabulary term.

    Examples:
        Update description::

            >>> workflow = ml.lookup_workflow("2-ABC1")  # doctest: +SKIP
            >>> workflow.description = "Updated description"  # doctest: +SKIP

        Update workflow type::

            >>> workflow = ml.lookup_workflow("2-ABC1")  # doctest: +SKIP
            >>> workflow.workflow_type = "python_notebook"  # doctest: +SKIP
    """
    # Only intercept updates after full initialization
    # Use __dict__ check to avoid recursion during Pydantic model construction
    if (
        "__pydantic_private__" in self.__dict__
        and self.__dict__.get("__pydantic_private__", {}).get("_ml_instance") is not None
    ):
        if name == "description":
            self._update_description_in_catalog(value)
        elif name == "workflow_type":
            # Normalize to list
            if isinstance(value, str):
                value = [value]
            self._update_workflow_types_in_catalog(value)
    super().__setattr__(name, value)

add_workflow_type

add_workflow_type(
    workflow_type: str | VocabularyTerm,
) -> None

Add a workflow type to this workflow.

Adds a type term to this workflow if it's not already present. The term must exist in the Workflow_Type vocabulary.

Parameters:

Name Type Description Default
workflow_type str | VocabularyTerm

Term name (string) or VocabularyTerm object from Workflow_Type vocabulary.

required

Raises:

Type Description
DerivaMLException

If the workflow is not registered (no RID), the catalog is read-only, or the term doesn't exist.

Source code in src/deriva_ml/execution/workflow.py
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
def add_workflow_type(self, workflow_type: str | VocabularyTerm) -> None:
    """Add a workflow type to this workflow.

    Adds a type term to this workflow if it's not already present. The term must
    exist in the Workflow_Type vocabulary.

    Args:
        workflow_type: Term name (string) or VocabularyTerm object from Workflow_Type vocabulary.

    Raises:
        DerivaMLException: If the workflow is not registered (no RID),
            the catalog is read-only, or the term doesn't exist.
    """
    self._check_writable_catalog("add workflow_type")

    if isinstance(workflow_type, VocabularyTerm):
        vocab_term = workflow_type
    else:
        vocab_term = self._ml_instance.lookup_term(MLVocab.workflow_type, workflow_type)

    if vocab_term.name in self.workflow_types:
        return

    _, atable_path = self._get_workflow_type_association_table()
    atable_path.insert([{MLVocab.workflow_type: vocab_term.name, "Workflow": self.workflow_rid}])

add_workflow_types

add_workflow_types(
    workflow_types: str
    | VocabularyTerm
    | list[str | VocabularyTerm],
) -> None

Add one or more workflow types to this workflow.

Parameters:

Name Type Description Default
workflow_types str | VocabularyTerm | list[str | VocabularyTerm]

Single term or list of terms. Can be strings (term names) or VocabularyTerm objects.

required

Raises:

Type Description
DerivaMLException

If any term doesn't exist in the Workflow_Type vocabulary.

Source code in src/deriva_ml/execution/workflow.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
def add_workflow_types(self, workflow_types: str | VocabularyTerm | list[str | VocabularyTerm]) -> None:
    """Add one or more workflow types to this workflow.

    Args:
        workflow_types: Single term or list of terms. Can be strings (term names)
            or VocabularyTerm objects.

    Raises:
        DerivaMLException: If any term doesn't exist in the Workflow_Type vocabulary.
    """
    types_to_add = [workflow_types] if not isinstance(workflow_types, list) else workflow_types

    for term in types_to_add:
        self.add_workflow_type(term)

get_dynamic_version staticmethod

get_dynamic_version(
    root: str | PathLike | None = None,
) -> str

Return a dynamic version string derived from VCS state.

Wraps :func:setuptools_scm.get_version (the same mechanism used at build time). The returned string includes distance-from-tag and an optional .dirty suffix when the working tree has uncommitted changes.

Parameters:

Name Type Description Default
root str | PathLike | None

Repository root to introspect. When None, uses the installed deriva-ml package's parent directory (i.e. the source checkout that's being developed against).

None

Returns:

Type Description
str

A setuptools-scm-style version string (e.g. "1.2.3",

str

"1.2.3.post2+g1234abc", or "1.2.3.post2+g1234abc.dirty").

Raises:

Type Description
RuntimeError

If setuptools_scm is not importable in the current environment.

Source code in src/deriva_ml/execution/workflow.py
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
@staticmethod
def get_dynamic_version(root: str | os.PathLike | None = None) -> str:
    """Return a dynamic version string derived from VCS state.

    Wraps :func:`setuptools_scm.get_version` (the same mechanism used at
    build time). The returned string includes distance-from-tag and an
    optional ``.dirty`` suffix when the working tree has uncommitted
    changes.

    Args:
        root: Repository root to introspect. When ``None``, uses the
            installed deriva-ml package's parent directory (i.e. the
            source checkout that's being developed against).

    Returns:
        A setuptools-scm-style version string (e.g. ``"1.2.3"``,
        ``"1.2.3.post2+g1234abc"``, or ``"1.2.3.post2+g1234abc.dirty"``).

    Raises:
        RuntimeError: If ``setuptools_scm`` is not importable in the
            current environment.
    """
    # Historical note: this routine used to unconditionally set
    # ``os.environ["SETUPTOOLS_USE_DISTUTILS"] = "stdlib"`` as a
    # defensive measure against a ``_distutils_hack`` assertion that
    # older setuptools versions hit on some macOS configurations.
    #
    # That mutation is process-wide and leaks into subprocess.Popen
    # inheritance, which broke third-party packages on Python 3.12+
    # that still import ``distutils.version`` (distutils is removed
    # from the stdlib per PEP 632 but setuptools vendors it back in
    # its own package — the env var short-circuits that vendored
    # fallback). Net effect: any test that called a workflow
    # helper would poison the process env, and any later subprocess
    # under Python 3.13+ would crash importing ``distutils``.
    #
    # Python 3.12 is the floor for this project (pyproject.toml:
    # ``requires-python = ">=3.12"``) so the distutils_hack concern
    # is moot — distutils is simply gone, and setuptools's own
    # fallback handles it. We drop the env mutation entirely.
    warnings.filterwarnings(
        "ignore",
        category=UserWarning,
        module="_distutils_hack",
    )
    try:
        from setuptools_scm import get_version
    except Exception as e:  # ImportError or anything environment-specific
        raise RuntimeError(f"setuptools_scm is not available: {e}") from e

    if root is None:
        # Adjust this to point at your repo root if needed
        root = Path(__file__).resolve().parents[1]

    return get_version(root=root)

get_url_and_checksum staticmethod

get_url_and_checksum(
    executable_path: Path,
    allow_dirty: bool = False,
) -> tuple[str, str]

Determines the Git URL and checksum for a file.

Computes the Git repository URL and file checksum for the specified path. For notebooks, strips cell outputs before computing the checksum.

Parameters:

Name Type Description Default
executable_path Path

Path to the workflow file.

required
allow_dirty bool

If True, log a warning instead of raising an error when the file has uncommitted changes. Defaults to False.

False

Returns:

Type Description
tuple[str, str]

tuple[str, str]: (GitHub URL, Git object hash)

Raises:

Type Description
DerivaMLException

If not in a Git repository.

DerivaMLDirtyWorkflowError

If the file has uncommitted changes and allow_dirty is False.

Example

url, checksum = Workflow.get_url_and_checksum(Path("analysis.ipynb")) # doctest: +SKIP print(f"URL: {url}") # doctest: +SKIP print(f"Checksum: {checksum}") # doctest: +SKIP

Source code in src/deriva_ml/execution/workflow.py
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
@staticmethod
def get_url_and_checksum(executable_path: Path, allow_dirty: bool = False) -> tuple[str, str]:
    """Determines the Git URL and checksum for a file.

    Computes the Git repository URL and file checksum for the specified path.
    For notebooks, strips cell outputs before computing the checksum.

    Args:
        executable_path: Path to the workflow file.
        allow_dirty: If True, log a warning instead of raising an error
            when the file has uncommitted changes. Defaults to False.

    Returns:
        tuple[str, str]: (GitHub URL, Git object hash)

    Raises:
        DerivaMLException: If not in a Git repository.
        DerivaMLDirtyWorkflowError: If the file has uncommitted changes
            and allow_dirty is False.

    Example:
        >>> url, checksum = Workflow.get_url_and_checksum(Path("analysis.ipynb"))  # doctest: +SKIP
        >>> print(f"URL: {url}")  # doctest: +SKIP
        >>> print(f"Checksum: {checksum}")  # doctest: +SKIP
    """
    # The "must be inside a git checkout" guard is a precondition
    # for honest provenance. But ``allow_dirty=True`` is the
    # documented escape hatch for ad-hoc / dry-run / notebook
    # workflows that don't need a clean checkout — refusing to
    # run those because the cwd isn't inside git defeats the
    # intent of the flag. When ``allow_dirty=True``, downgrade
    # the no-git precondition to a warning and return empty
    # provenance (URL/checksum both empty strings); when False
    # (the default), keep the hard refuse.
    try:
        subprocess.run(
            ["git", "rev-parse", "--is-inside-work-tree"],
            capture_output=True,
            text=True,
            check=True,
        )
    except subprocess.CalledProcessError:
        if allow_dirty:
            logger.warning(
                "Not executing in a Git repository; allow_dirty=True, "
                "returning empty URL/checksum. Provenance will not be "
                "recoverable for this workflow."
            )
            return "", ""
        raise DerivaMLException("Not executing in a Git repository.")

    github_url, dirty_paths = Workflow._github_url(executable_path)

    if dirty_paths:
        if allow_dirty:
            offending = ", ".join(p.strip() for p in dirty_paths[:3])
            more = f" (and {len(dirty_paths) - 3} more)" if len(dirty_paths) > 3 else ""
            logger.warning(
                f"Worktree has uncommitted changes affecting provenance: "
                f"{offending}{more}. Proceeding with --allow-dirty override."
            )
        else:
            raise DerivaMLDirtyWorkflowError(str(executable_path), dirty_paths=dirty_paths)

    # If you are in a notebook, strip out the outputs before computing the checksum.
    if executable_path != "REPL":
        if "ipynb" == executable_path.suffix:
            strip_proc = subprocess.run(
                ["nbstripout", "-t", str(executable_path)],
                capture_output=True,
            )
            hash_proc = subprocess.run(
                ["git", "hash-object", "--stdin"],
                input=strip_proc.stdout,
                capture_output=True,
                text=True,
            )
            checksum = hash_proc.stdout.strip()
        else:
            checksum = subprocess.run(
                ["git", "hash-object", str(executable_path)],
                capture_output=True,
                text=True,
                check=False,
            ).stdout.strip()
    else:
        checksum = "1"
    return github_url, checksum

remove_workflow_type

remove_workflow_type(
    workflow_type: str | VocabularyTerm,
) -> None

Remove a workflow type from this workflow.

Removes a type term from this workflow if it's currently associated.

Parameters:

Name Type Description Default
workflow_type str | VocabularyTerm

Term name (string) or VocabularyTerm object from Workflow_Type vocabulary.

required

Raises:

Type Description
DerivaMLException

If the workflow is not registered (no RID), the catalog is read-only, or the term doesn't exist.

Source code in src/deriva_ml/execution/workflow.py
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
def remove_workflow_type(self, workflow_type: str | VocabularyTerm) -> None:
    """Remove a workflow type from this workflow.

    Removes a type term from this workflow if it's currently associated.

    Args:
        workflow_type: Term name (string) or VocabularyTerm object from Workflow_Type vocabulary.

    Raises:
        DerivaMLException: If the workflow is not registered (no RID),
            the catalog is read-only, or the term doesn't exist.
    """
    self._check_writable_catalog("remove workflow_type")

    if isinstance(workflow_type, VocabularyTerm):
        vocab_term = workflow_type
    else:
        vocab_term = self._ml_instance.lookup_term(MLVocab.workflow_type, workflow_type)

    if vocab_term.name not in self.workflow_types:
        return

    _, atable_path = self._get_workflow_type_association_table()
    atable_path.filter(
        (atable_path.Workflow == self.workflow_rid) & (atable_path.Workflow_Type == vocab_term.name)
    ).delete()

setup_url_checksum

setup_url_checksum() -> 'Workflow'

Pydantic post-construction validator that fills in url and checksum.

Runs automatically after every Workflow(...) construction (it is a @model_validator(mode="after")). For any field the caller did not provide, the validator derives a value from the current execution context:

  • url — set to the resolved source URL of the calling script/notebook. Resolution prefers a Docker image identifier (when DERIVA_MCP_IN_DOCKER=true), otherwise a GitHub /blob/<commit>/<path> URL from the local git checkout. When the script is not in a git repo and allow_dirty=True, url is left empty ("") — there is no file:// fallback.
  • checksum — set to the git commit SHA of the calling script (or the Docker image digest when running in Docker).
  • version — in the local-git path (the common case) it is set from get_dynamic_version() (the version derived from the local git checkout); in the Docker path it is set from DERIVA_MCP_VERSION instead.

Caller-supplied values are never overwritten — this is a "fill in the blanks" validator, not a re-derivation.

Environment variable overrides
  • DERIVA_ML_WORKFLOW_URL: force-set url.
  • DERIVA_ML_WORKFLOW_CHECKSUM: force-set checksum.
  • DERIVA_MCP_IN_DOCKER=true: use Docker image metadata instead of git.

Docker-only environment variables (consulted when DERIVA_MCP_IN_DOCKER=true): - DERIVA_MCP_VERSION: semantic version of the Docker image. - DERIVA_MCP_GIT_COMMIT: git commit hash at image build time. - DERIVA_MCP_IMAGE_DIGEST: image digest (unique identifier). - DERIVA_MCP_IMAGE_NAME: image name (e.g. ghcr.io/informatics-isi-edu/deriva-ml-mcp).

Returns:

Name Type Description
Workflow 'Workflow'

self (the same instance, mutated in place).

'Workflow'

Pydantic mode="after" validators must return the

'Workflow'

model.

Raises:

Type Description
DerivaMLException

If the validator cannot determine a URL or checksum from any source (e.g. not in a git repo, Docker env vars missing, no explicit overrides).

Source code in src/deriva_ml/execution/workflow.py
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
@model_validator(mode="after")
def setup_url_checksum(self) -> "Workflow":
    """Pydantic post-construction validator that fills in ``url`` and ``checksum``.

    Runs automatically after every ``Workflow(...)`` construction
    (it is a ``@model_validator(mode="after")``). For any field
    the caller did not provide, the validator derives a value from
    the current execution context:

    - ``url`` — set to the resolved source URL of the calling
      script/notebook. Resolution prefers a Docker image
      identifier (when ``DERIVA_MCP_IN_DOCKER=true``), otherwise a
      GitHub ``/blob/<commit>/<path>`` URL from the local git
      checkout. When the script is not in a git repo and
      ``allow_dirty=True``, ``url`` is left empty (``""``) — there
      is no ``file://`` fallback.
    - ``checksum`` — set to the git commit SHA of the calling
      script (or the Docker image digest when running in Docker).
    - ``version`` — in the local-git path (the common case) it is
      set from ``get_dynamic_version()`` (the version derived from
      the local git checkout); in the Docker path it is set from
      ``DERIVA_MCP_VERSION`` instead.

    Caller-supplied values are never overwritten — this is a
    "fill in the blanks" validator, not a re-derivation.

    Environment variable overrides:
        - ``DERIVA_ML_WORKFLOW_URL``: force-set ``url``.
        - ``DERIVA_ML_WORKFLOW_CHECKSUM``: force-set ``checksum``.
        - ``DERIVA_MCP_IN_DOCKER=true``: use Docker image metadata
          instead of git.

    Docker-only environment variables (consulted when
    ``DERIVA_MCP_IN_DOCKER=true``):
        - ``DERIVA_MCP_VERSION``: semantic version of the Docker image.
        - ``DERIVA_MCP_GIT_COMMIT``: git commit hash at image build time.
        - ``DERIVA_MCP_IMAGE_DIGEST``: image digest (unique identifier).
        - ``DERIVA_MCP_IMAGE_NAME``: image name (e.g.
          ``ghcr.io/informatics-isi-edu/deriva-ml-mcp``).

    Returns:
        Workflow: ``self`` (the same instance, mutated in place).
        Pydantic ``mode="after"`` validators must return the
        model.

    Raises:
        DerivaMLException: If the validator cannot determine a
            URL or checksum from any source (e.g. not in a git
            repo, Docker env vars missing, no explicit overrides).
    """
    self._logger = get_logger(__name__)

    # Loaded from a catalog row: provenance is already known.
    # ``workflow_rid`` is set only for a workflow that already exists in
    # the catalog (``lookup_workflow`` / ``find_workflows`` pass it; the
    # create path does not). Its ``url`` / ``checksum`` / ``version`` are
    # stored columns, so re-deriving them from the runtime environment is
    # both wrong and fragile -- the derivation calls setuptools-scm and
    # raises in any non-git, non-Docker working directory. Trust the
    # stored values and skip all derivation.
    if self.workflow_rid is not None:
        return self

    # Check if running in Docker container (no git repo available)
    if os.environ.get("DERIVA_MCP_IN_DOCKER", "").lower() == "true":
        # Use Docker image metadata for provenance
        self.version = self.version or os.environ.get("DERIVA_MCP_VERSION", "")

        # Use image digest as checksum (unique identifier for the container)
        # Fall back to git commit if digest not available
        self.checksum = self.checksum or (
            os.environ.get("DERIVA_MCP_IMAGE_DIGEST", "") or os.environ.get("DERIVA_MCP_GIT_COMMIT", "")
        )

        # Build URL pointing to the Docker image or source repo
        if not self.url:
            image_name = os.environ.get(
                "DERIVA_MCP_IMAGE_NAME",
                "ghcr.io/informatics-isi-edu/deriva-ml-mcp",
            )
            image_digest = os.environ.get("DERIVA_MCP_IMAGE_DIGEST", "")
            if image_digest:
                # URL format: image@sha256:digest
                self.url = f"{image_name}@{image_digest}"
            else:
                # Fall back to source repo with git commit
                source_url = "https://github.com/informatics-isi-edu/deriva-ml-mcp"
                git_commit = os.environ.get("DERIVA_MCP_GIT_COMMIT", "")
                self.url = f"{source_url}/commit/{git_commit}" if git_commit else source_url

        return self

    # Check to see if execution file info is being passed in by calling program (notebook runner)
    if "DERIVA_ML_WORKFLOW_URL" in os.environ:
        self.url = os.environ["DERIVA_ML_WORKFLOW_URL"]
        self.checksum = os.environ.get("DERIVA_ML_WORKFLOW_CHECKSUM", "")
        notebook_path = os.environ.get("DERIVA_ML_NOTEBOOK_PATH")
        if notebook_path:
            self.git_root = Workflow._get_git_root(Path(notebook_path))
        self.is_notebook = True
        return self

    # Standard git detection for local development
    # Check env var for allow_dirty (set by CLI --allow-dirty flag or dry-run mode)
    if os.environ.get("DERIVA_ML_ALLOW_DIRTY", "").lower() == "true":
        self.allow_dirty = True
    if os.environ.get("DERIVA_ML_DRY_RUN", "").lower() == "true":
        self.allow_dirty = True

    if not self.url:
        path, self.is_notebook = Workflow._get_python_script()
        self.url, self.checksum = Workflow.get_url_and_checksum(path, allow_dirty=self.allow_dirty)
        self.git_root = Workflow._get_git_root(path)

    self.version = self.version or Workflow.get_dynamic_version(root=str(self.git_root or Path.cwd()))
    return self

WorkflowSummary

Bases: BaseModel

Compact view of a Workflow row.

Only the fields a lineage consumer typically needs at a glance. Drill into the full record with ml.lookup_workflow(rid).

Attributes:

Name Type Description
rid RID

Workflow RID.

name str | None

Human-readable workflow name (None if the row has no name set).

Source code in src/deriva_ml/execution/lineage.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class WorkflowSummary(BaseModel):
    """Compact view of a Workflow row.

    Only the fields a lineage consumer typically needs at a glance.
    Drill into the full record with ``ml.lookup_workflow(rid)``.

    Attributes:
        rid: Workflow RID.
        name: Human-readable workflow name (None if the row has no
            name set).
    """

    model_config = ConfigDict(extra="forbid")

    rid: RID
    name: str | None = None

__getattr__

__getattr__(name)

Lazy import to avoid circular dependencies.

Source code in src/deriva_ml/execution/__init__.py
54
55
56
57
58
59
60
def __getattr__(name):
    """Lazy import to avoid circular dependencies."""
    if name == "Execution":
        from deriva_ml.execution.execution import Execution

        return Execution
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

create_model_config

create_model_config(
    ml_class: type["DerivaML"]
    | None = None,
    description: str = "Model execution",
    hydra_defaults: list | None = None,
) -> Any

Create a hydra-zen configuration for run_model.

This helper creates a properly configured hydra-zen builds() for run_model with the specified DerivaML class bound via partial application.

Parameters

ml_class : type[DerivaML], optional The DerivaML class (or subclass) to use. If None, uses the base DerivaML.

str, optional

Default description for executions. Can be overridden at runtime.

list, optional

Custom hydra defaults. If None, uses standard defaults for deriva_ml, datasets, assets, workflow, and model_config groups.

Returns

Any A hydra-zen builds() configuration ready to be registered with store().

Examples

Basic usage with DerivaML:

>>> from deriva_ml.execution.runner import create_model_config  # doctest: +SKIP
>>> model_config = create_model_config()  # doctest: +SKIP
>>> store(model_config, name="deriva_model")  # doctest: +SKIP

With a custom subclass:

>>> from eye_ai import EyeAI  # doctest: +SKIP
>>> model_config = create_model_config(EyeAI, description="EyeAI analysis")  # doctest: +SKIP
>>> store(model_config, name="eyeai_model")  # doctest: +SKIP

With custom hydra defaults:

>>> model_config = create_model_config(  # doctest: +SKIP
...     hydra_defaults=[
...         "_self_",
...         {"deriva_ml": "production"},
...         {"datasets": "full_dataset"},
...     ]
... )
Source code in src/deriva_ml/execution/runner.py
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
def create_model_config(
    ml_class: type["DerivaML"] | None = None,
    description: str = "Model execution",
    hydra_defaults: list | None = None,
) -> Any:
    """Create a hydra-zen configuration for run_model.

    This helper creates a properly configured hydra-zen builds() for run_model
    with the specified DerivaML class bound via partial application.

    Parameters
    ----------
    ml_class : type[DerivaML], optional
        The DerivaML class (or subclass) to use. If None, uses the base DerivaML.

    description : str, optional
        Default description for executions. Can be overridden at runtime.

    hydra_defaults : list, optional
        Custom hydra defaults. If None, uses standard defaults for deriva_ml,
        datasets, assets, workflow, and model_config groups.

    Returns
    -------
    Any
        A hydra-zen builds() configuration ready to be registered with store().

    Examples
    --------
    Basic usage with DerivaML:

        >>> from deriva_ml.execution.runner import create_model_config  # doctest: +SKIP
        >>> model_config = create_model_config()  # doctest: +SKIP
        >>> store(model_config, name="deriva_model")  # doctest: +SKIP

    With a custom subclass:

        >>> from eye_ai import EyeAI  # doctest: +SKIP
        >>> model_config = create_model_config(EyeAI, description="EyeAI analysis")  # doctest: +SKIP
        >>> store(model_config, name="eyeai_model")  # doctest: +SKIP

    With custom hydra defaults:

        >>> model_config = create_model_config(  # doctest: +SKIP
        ...     hydra_defaults=[
        ...         "_self_",
        ...         {"deriva_ml": "production"},
        ...         {"datasets": "full_dataset"},
        ...     ]
        ... )
    """
    from functools import partial

    if hydra_defaults is None:
        hydra_defaults = [
            "_self_",
            {"deriva_ml": "default_deriva"},
            {"datasets": "default_dataset"},
            {"assets": "default_asset"},
            {"workflow": "default_workflow"},
            {"model_config": "default_model"},
        ]

    # Create a partial function with ml_class bound
    if ml_class is not None:
        run_func = partial(run_model, ml_class=ml_class)
    else:
        run_func = run_model

    return builds(
        run_func,
        description=description,
        populate_full_signature=True,
        hydra_defaults=hydra_defaults,
    )

get_all_multirun_configs

get_all_multirun_configs() -> dict[
    str, MultirunSpec
]

Get all registered multirun configurations.

Returns:

Type Description
dict[str, MultirunSpec]

Dictionary mapping names to MultirunSpec instances.

Source code in src/deriva_ml/execution/multirun_config.py
147
148
149
150
151
152
153
def get_all_multirun_configs() -> dict[str, MultirunSpec]:
    """Get all registered multirun configurations.

    Returns:
        Dictionary mapping names to MultirunSpec instances.
    """
    return dict(_multirun_registry)

get_multirun_config

get_multirun_config(
    name: str,
) -> MultirunSpec | None

Look up a registered multirun configuration by name.

Parameters:

Name Type Description Default
name str

The name of the multirun configuration.

required

Returns:

Type Description
MultirunSpec | None

The MultirunSpec if found, None otherwise.

Source code in src/deriva_ml/execution/multirun_config.py
126
127
128
129
130
131
132
133
134
135
def get_multirun_config(name: str) -> MultirunSpec | None:
    """Look up a registered multirun configuration by name.

    Args:
        name: The name of the multirun configuration.

    Returns:
        The MultirunSpec if found, None otherwise.
    """
    return _multirun_registry.get(name)

get_notebook_configuration

get_notebook_configuration(
    config_class: type[T],
    config_name: str,
    overrides: list[str] | None = None,
    job_name: str = "notebook",
    version_base: str = "1.3",
) -> T

Load and return a hydra-zen configuration for use in notebooks.

This function is the notebook equivalent of run_model. While run_model launches a full execution with model training, get_notebook_configuration simply resolves the configuration and returns it for interactive use.

The function handles: - Adding configurations to the hydra store - Launching hydra-zen to resolve defaults and overrides - Returning the instantiated configuration object

Parameters:

Name Type Description Default
config_class type[T]

The hydra-zen builds() class for the configuration. This should be a class created with builds(YourConfig, ...).

required
config_name str

Name of the configuration in the hydra store. Must match the name used when calling store(config_class, name=...).

required
overrides list[str] | None

Optional list of Hydra override strings (e.g., ["param=value"]).

None
job_name str

Name for the Hydra job (default: "notebook").

'notebook'
version_base str

Hydra version base (default: "1.3").

'1.3'

Returns:

Type Description
T

The instantiated configuration object with all defaults resolved.

Example

In your notebook's configuration module (e.g., configs/roc_analysis.py):

from dataclasses import dataclass, field # doctest: +SKIP from hydra_zen import builds, store # doctest: +SKIP from deriva_ml.execution import BaseConfig # doctest: +SKIP

@dataclass # doctest: +SKIP ... class ROCAnalysisConfig(BaseConfig): ... execution_rids: list[str] = field(default_factory=list)

ROCAnalysisConfigBuilds = builds( # doctest: +SKIP ... ROCAnalysisConfig, ... populate_full_signature=True, ... hydra_defaults=["self", {"deriva_ml": "default_deriva"}], ... ) store(ROCAnalysisConfigBuilds, name="roc_analysis") # doctest: +SKIP

In your notebook:

from configs import load_all_configs # doctest: +SKIP from configs.roc_analysis import ROCAnalysisConfigBuilds # doctest: +SKIP from deriva_ml.execution import get_notebook_configuration # doctest: +SKIP

Load all project configs into hydra store

load_all_configs() # doctest: +SKIP

Get resolved configuration

config = get_notebook_configuration( # doctest: +SKIP ... ROCAnalysisConfigBuilds, ... config_name="roc_analysis", ... overrides=["execution_rids=[3JRC,3KT0]"], ... )

Use the configuration

print(config.execution_rids) # ['3JRC', '3KT0'] # doctest: +SKIP print(config.deriva_ml.hostname) # From default_deriva config # doctest: +SKIP

Environment Variables

DERIVA_ML_HYDRA_OVERRIDES: JSON-encoded list of override strings. When running via deriva-ml-run-notebook, this is automatically set from command-line arguments. Overrides from this environment variable are applied first, then any overrides passed directly to this function are applied (taking precedence).

Source code in src/deriva_ml/execution/base_config.py
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
def get_notebook_configuration(
    config_class: type[T],
    config_name: str,
    overrides: list[str] | None = None,
    job_name: str = "notebook",
    version_base: str = "1.3",
) -> T:
    """Load and return a hydra-zen configuration for use in notebooks.

    This function is the notebook equivalent of `run_model`. While `run_model`
    launches a full execution with model training, `get_notebook_configuration`
    simply resolves the configuration and returns it for interactive use.

    The function handles:
    - Adding configurations to the hydra store
    - Launching hydra-zen to resolve defaults and overrides
    - Returning the instantiated configuration object

    Args:
        config_class: The hydra-zen builds() class for the configuration.
            This should be a class created with `builds(YourConfig, ...)`.
        config_name: Name of the configuration in the hydra store.
            Must match the name used when calling `store(config_class, name=...)`.
        overrides: Optional list of Hydra override strings (e.g., ["param=value"]).
        job_name: Name for the Hydra job (default: "notebook").
        version_base: Hydra version base (default: "1.3").

    Returns:
        The instantiated configuration object with all defaults resolved.

    Example:
        In your notebook's configuration module (e.g., `configs/roc_analysis.py`):

        >>> from dataclasses import dataclass, field  # doctest: +SKIP
        >>> from hydra_zen import builds, store  # doctest: +SKIP
        >>> from deriva_ml.execution import BaseConfig  # doctest: +SKIP
        >>>
        >>> @dataclass  # doctest: +SKIP
        ... class ROCAnalysisConfig(BaseConfig):
        ...     execution_rids: list[str] = field(default_factory=list)
        >>>
        >>> ROCAnalysisConfigBuilds = builds(  # doctest: +SKIP
        ...     ROCAnalysisConfig,
        ...     populate_full_signature=True,
        ...     hydra_defaults=["_self_", {"deriva_ml": "default_deriva"}],
        ... )
        >>> store(ROCAnalysisConfigBuilds, name="roc_analysis")  # doctest: +SKIP

        In your notebook:

        >>> from configs import load_all_configs  # doctest: +SKIP
        >>> from configs.roc_analysis import ROCAnalysisConfigBuilds  # doctest: +SKIP
        >>> from deriva_ml.execution import get_notebook_configuration  # doctest: +SKIP
        >>>
        >>> # Load all project configs into hydra store
        >>> load_all_configs()  # doctest: +SKIP
        >>>
        >>> # Get resolved configuration
        >>> config = get_notebook_configuration(  # doctest: +SKIP
        ...     ROCAnalysisConfigBuilds,
        ...     config_name="roc_analysis",
        ...     overrides=["execution_rids=[3JRC,3KT0]"],
        ... )
        >>>
        >>> # Use the configuration
        >>> print(config.execution_rids)  # ['3JRC', '3KT0']  # doctest: +SKIP
        >>> print(config.deriva_ml.hostname)  # From default_deriva config  # doctest: +SKIP

    Environment Variables:
        DERIVA_ML_HYDRA_OVERRIDES: JSON-encoded list of override strings.
            When running via `deriva-ml-run-notebook`, this is automatically
            set from command-line arguments. Overrides from this environment
            variable are applied first, then any overrides passed directly
            to this function are applied (taking precedence).
    """
    # Ensure configs are in the hydra store
    store.add_to_hydra_store(overwrite_ok=True)

    # Collect overrides from environment variable (set by run_notebook CLI)
    env_overrides_json = os.environ.get("DERIVA_ML_HYDRA_OVERRIDES")
    env_overrides = json.loads(env_overrides_json) if env_overrides_json else []

    # Merge overrides: env overrides first, then explicit overrides (higher precedence)
    all_overrides = env_overrides + (overrides or [])

    # Variables to capture from within the task function
    captured_choices: dict[str, str] = {}
    captured_output_dir: str | None = None

    # Define a task function that instantiates and returns the config
    # The cfg from launch() is an OmegaConf DictConfig, so we need to
    # use hydra_zen.instantiate() to convert it to actual Python objects
    def return_instantiated_config(cfg: Any) -> T:
        nonlocal captured_choices, captured_output_dir
        # Capture the Hydra runtime choices (which config names were selected)
        # and runtime output directory (for uploading hydra config files)
        # Filter out None values (some Hydra internal groups have None choices)
        try:
            from hydra.core.hydra_config import HydraConfig

            hydra_cfg = HydraConfig.get()
            choices = hydra_cfg.runtime.choices
            captured_choices = {k: v for k, v in choices.items() if v is not None}
            captured_output_dir = hydra_cfg.runtime.output_dir
        except Exception:
            # If HydraConfig is not available, leave choices empty
            pass
        return instantiate(cfg)

    # Launch hydra-zen to resolve the configuration
    result = launch(
        config_class,
        return_instantiated_config,
        version_base=version_base,
        config_name=config_name,
        job_name=job_name,
        overrides=all_overrides,
    )

    # Inject the captured choices into the config object
    config = result.return_value
    if hasattr(config, "config_choices"):
        config.config_choices = captured_choices

    # Store the hydra output dir in module-level variable for run_notebook() to use.
    # This is NOT stored on the config because it's a runtime artifact, not a
    # configuration parameter, and adding it to the structured config causes
    # Hydra OmegaConf composition errors.
    global _captured_hydra_output_dir
    _captured_hydra_output_dir = captured_output_dir

    return config

list_multirun_configs

list_multirun_configs() -> list[str]

List all registered multirun configuration names.

Returns:

Type Description
list[str]

List of registered multirun config names.

Source code in src/deriva_ml/execution/multirun_config.py
138
139
140
141
142
143
144
def list_multirun_configs() -> list[str]:
    """List all registered multirun configuration names.

    Returns:
        List of registered multirun config names.
    """
    return list(_multirun_registry.keys())

load_configs

load_configs(
    package_name: str = "configs",
) -> list[str]

Dynamically import all configuration modules from a package.

This function discovers and imports all Python modules in the specified package. Each module is expected to register its configurations with the hydra-zen store as a side effect of being imported.

Parameters:

Name Type Description Default
package_name str

Name of the package containing config modules. Default is "configs" which works for the standard project layout.

'configs'

Returns:

Type Description
list[str]

List of module names that were successfully loaded.

Raises:

Type Description
ImportError

If a config module fails to import.

Example

In your main script or notebook

from deriva_ml.execution import load_configs

load_configs() # Loads from "configs" package

or

load_configs("my_project.configs") # Custom package

Note

The "experiments" module (if present) is loaded last because it typically depends on other configs being registered first.

Source code in src/deriva_ml/execution/base_config.py
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
def load_configs(package_name: str = "configs") -> list[str]:
    """Dynamically import all configuration modules from a package.

    This function discovers and imports all Python modules in the specified
    package. Each module is expected to register its configurations with
    the hydra-zen store as a side effect of being imported.

    Args:
        package_name: Name of the package containing config modules.
            Default is "configs" which works for the standard project layout.

    Returns:
        List of module names that were successfully loaded.

    Raises:
        ImportError: If a config module fails to import.

    Example:
        # In your main script or notebook
        from deriva_ml.execution import load_configs

        load_configs()  # Loads from "configs" package
        # or
        load_configs("my_project.configs")  # Custom package

    Note:
        The "experiments" module (if present) is loaded last because it
        typically depends on other configs being registered first.
    """
    loaded_modules = []

    try:
        package = importlib.import_module(package_name)
    except ImportError:
        # Package doesn't exist, return empty
        return []

    package_dir = Path(package.__file__).parent

    # Collect module names, recursing into subpackages
    modules_to_load = []
    for module_info in pkgutil.iter_modules([str(package_dir)]):
        if module_info.ispkg:
            # Recurse into subpackages (e.g., configs/dev/)
            sub_loaded = load_configs(f"{package_name}.{module_info.name}")
            loaded_modules.extend(sub_loaded)
        else:
            modules_to_load.append(module_info.name)

    # Sort modules but ensure 'experiments' is loaded last
    modules_to_load.sort()
    if "experiments" in modules_to_load:
        modules_to_load.remove("experiments")
        modules_to_load.append("experiments")

    for module_name in modules_to_load:
        full_name = f"{package_name}.{module_name}"
        importlib.import_module(full_name)
        loaded_modules.append(full_name)

    return sorted(loaded_modules)

notebook_config

notebook_config(
    name: str,
    config_class: type[BaseConfig]
    | None = None,
    defaults: dict[str, str]
    | None = None,
    **field_defaults: Any,
) -> Any

Register a notebook configuration with simplified syntax.

This is the recommended way to create notebook configurations. It handles all the hydra-zen boilerplate (builds, store, defaults) automatically.

For simple notebooks that only use BaseConfig fields (deriva_ml, datasets, assets, etc.), just specify which defaults to use. For notebooks with custom parameters, provide a config_class that inherits from BaseConfig.

Parameters:

Name Type Description Default
name str

Configuration name. Used both as the hydra config name and to look up the config in run_notebook().

required
config_class type[BaseConfig] | None

Optional dataclass inheriting from BaseConfig. If None, uses BaseConfig directly (suitable for notebooks that only need the standard fields).

None
defaults dict[str, str] | None

Dict mapping config group names to config names. These override the base defaults. Common groups: - "deriva_ml": Connection config (e.g., "default_deriva", "eye_ai") - "datasets": Dataset config (e.g., "cifar10_training") - "assets": Asset config (e.g., "model_weights") - "workflow": Workflow config (e.g., "default_workflow")

None
**field_defaults Any

Default values for fields in config_class.

{}

Returns:

Type Description
Any

The hydra-zen builds() class, in case you need to reference it directly.

Examples:

Simple notebook using only standard fields:

# configs/roc_analysis.py
from deriva_ml.execution import notebook_config

notebook_config(
    "roc_analysis",
    defaults={"assets": "roc_comparison_probabilities"},
)

Notebook with custom parameters:

# configs/training_analysis.py
from dataclasses import dataclass
from deriva_ml.execution import BaseConfig, notebook_config

@dataclass
class TrainingAnalysisConfig(BaseConfig):
    learning_rate: float = 0.001
    batch_size: int = 32

notebook_config(
    "training_analysis",
    config_class=TrainingAnalysisConfig,
    defaults={"datasets": "cifar10_training"},
    learning_rate=0.01,  # Override default
)
Source code in src/deriva_ml/execution/base_config.py
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
def notebook_config(
    name: str,
    config_class: type[BaseConfig] | None = None,
    defaults: dict[str, str] | None = None,
    **field_defaults: Any,
) -> Any:
    """Register a notebook configuration with simplified syntax.

    This is the recommended way to create notebook configurations. It handles
    all the hydra-zen boilerplate (builds, store, defaults) automatically.

    For simple notebooks that only use BaseConfig fields (deriva_ml, datasets,
    assets, etc.), just specify which defaults to use. For notebooks with
    custom parameters, provide a config_class that inherits from BaseConfig.

    Args:
        name: Configuration name. Used both as the hydra config name and
            to look up the config in run_notebook().
        config_class: Optional dataclass inheriting from BaseConfig. If None,
            uses BaseConfig directly (suitable for notebooks that only need
            the standard fields).
        defaults: Dict mapping config group names to config names. These
            override the base defaults. Common groups:
            - "deriva_ml": Connection config (e.g., "default_deriva", "eye_ai")
            - "datasets": Dataset config (e.g., "cifar10_training")
            - "assets": Asset config (e.g., "model_weights")
            - "workflow": Workflow config (e.g., "default_workflow")
        **field_defaults: Default values for fields in config_class.

    Returns:
        The hydra-zen builds() class, in case you need to reference it directly.

    Examples:
        Simple notebook using only standard fields:

            # configs/roc_analysis.py
            from deriva_ml.execution import notebook_config

            notebook_config(
                "roc_analysis",
                defaults={"assets": "roc_comparison_probabilities"},
            )

        Notebook with custom parameters:

            # configs/training_analysis.py
            from dataclasses import dataclass
            from deriva_ml.execution import BaseConfig, notebook_config

            @dataclass
            class TrainingAnalysisConfig(BaseConfig):
                learning_rate: float = 0.001
                batch_size: int = 32

            notebook_config(
                "training_analysis",
                config_class=TrainingAnalysisConfig,
                defaults={"datasets": "cifar10_training"},
                learning_rate=0.01,  # Override default
            )
    """
    # Use BaseConfig if no custom class provided
    actual_class = config_class or BaseConfig

    # Build the hydra defaults list
    hydra_defaults = ["_self_"]

    # Start with base defaults, then apply overrides
    default_groups = {
        "deriva_ml": "default_deriva",
        "datasets": "default_dataset",
        "assets": "default_asset",
    }
    if defaults:
        default_groups.update(defaults)

    for group, config_name in default_groups.items():
        hydra_defaults.append({group: config_name})

    # Create the hydra-zen builds() class
    config_builds = builds(
        actual_class,
        populate_full_signature=True,
        hydra_defaults=hydra_defaults,
        **field_defaults,
    )

    # Register with hydra-zen store
    store(config_builds, name=name)

    # Also register in our internal registry for run_notebook()
    _notebook_configs[name] = (config_builds, name)

    return config_builds

reset_multirun_state

reset_multirun_state() -> None

Reset the global multirun state.

This is primarily useful for testing to ensure clean state between tests.

Source code in src/deriva_ml/execution/runner.py
742
743
744
745
746
747
748
749
750
751
752
def reset_multirun_state() -> None:
    """Reset the global multirun state.

    This is primarily useful for testing to ensure clean state between tests.
    """
    global _multirun_state
    _multirun_state.parent_execution_rid = None
    _multirun_state.parent_execution = None
    _multirun_state.ml_instance = None
    _multirun_state.job_sequence = 0
    _multirun_state.sweep_dir = None

run_model

run_model(
    deriva_ml: "DerivaMLConfig",
    datasets: list["DatasetSpec"],
    assets: list["RID"],
    description: str,
    workflow: "Workflow",
    model_config: Any,
    dry_run: bool = False,
    ml_class: type["DerivaML"]
    | None = None,
    script_config: Any = None,
) -> None

Execute a machine learning model within a DerivaML execution context.

This function serves as the main entry point called by hydra-zen after configuration resolution. It orchestrates the complete execution lifecycle: connecting to Deriva, creating an execution record, running the model, and (when not a dry run) uploading results.

In multirun mode, this function also: - Creates a parent execution on the first job to group all sweep jobs - Links each child execution to the parent with sequence ordering

Parameters:

Name Type Description Default
deriva_ml 'DerivaMLConfig'

Configuration for the DerivaML connection. Contains server URL, catalog ID, credentials, and other connection parameters.

required
datasets list['DatasetSpec']

Specifications for datasets to use in this execution. Each DatasetSpec identifies a dataset in the Deriva catalog to be made available to the model.

required
assets list['RID']

Resource IDs (RIDs) of assets to include in the execution. Typically model weight files, pretrained checkpoints, or other artifacts needed by the model.

required
description str

Human-readable description of this execution run. Stored in the Deriva catalog for provenance tracking. In multirun mode, this is also used for the parent execution if running via multirun_config.

required
workflow 'Workflow'

The workflow definition to associate with this execution. Defines the computational pipeline and its metadata.

required
model_config Any

A hydra-zen callable that wraps the actual model code. When called with ml_instance and execution arguments, it runs the model training or inference logic.

required
dry_run bool

If True, create the execution record but skip the model run and the result upload. When script_config is set, the script is still invoked once with execution=None to print a preview; a plain model_config is skipped entirely (it may not handle execution=None). Useful for testing configuration without running expensive computations. Defaults to False.

False
ml_class type['DerivaML'] | None

The DerivaML class (or subclass) to instantiate. If None, uses the base DerivaML class. Use this to instantiate domain-specific classes like EyeAI or GUDMAP.

None
script_config Any

Optional alternate hydra-zen callable that, when provided, takes precedence over model_config as the code to invoke. Lets skill-generated scripts share this runner while living in their own config group. It is also the only path that runs during a dry run (see dry_run).

None

Returns:

Type Description
None

None. On a non-dry run, results are committed to the Deriva catalog as

None

execution output assets; on a dry run, nothing is uploaded.

Example

This function is typically not called directly, but through hydra::

# From the command line:
# python deriva_run.py +experiment=cifar10_cnn dry_run=True

# Multirun (creates parent + child executions):
# python deriva_run.py --multirun             #     +experiment=cifar10_quick,cifar10_extended

# With a custom DerivaML subclass (in your script):
>>> from functools import partial  # doctest: +SKIP
>>> run_model_eyeai = partial(run_model, ml_class=EyeAI)  # doctest: +SKIP
Source code in src/deriva_ml/execution/runner.py
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
def run_model(
    deriva_ml: "DerivaMLConfig",
    datasets: list["DatasetSpec"],
    assets: list["RID"],
    description: str,
    workflow: "Workflow",
    model_config: Any,
    dry_run: bool = False,
    ml_class: type["DerivaML"] | None = None,
    script_config: Any = None,
) -> None:
    """Execute a machine learning model within a DerivaML execution context.

    This function serves as the main entry point called by hydra-zen after
    configuration resolution. It orchestrates the complete execution lifecycle:
    connecting to Deriva, creating an execution record, running the model,
    and (when not a dry run) uploading results.

    In multirun mode, this function also:
    - Creates a parent execution on the first job to group all sweep jobs
    - Links each child execution to the parent with sequence ordering

    Args:
        deriva_ml: Configuration for the DerivaML connection. Contains server
            URL, catalog ID, credentials, and other connection parameters.
        datasets: Specifications for datasets to use in this execution. Each
            ``DatasetSpec`` identifies a dataset in the Deriva catalog to be
            made available to the model.
        assets: Resource IDs (RIDs) of assets to include in the execution.
            Typically model weight files, pretrained checkpoints, or other
            artifacts needed by the model.
        description: Human-readable description of this execution run. Stored
            in the Deriva catalog for provenance tracking. In multirun mode,
            this is also used for the parent execution if running via
            ``multirun_config``.
        workflow: The workflow definition to associate with this execution.
            Defines the computational pipeline and its metadata.
        model_config: A hydra-zen callable that wraps the actual model code.
            When called with ``ml_instance`` and ``execution`` arguments, it
            runs the model training or inference logic.
        dry_run: If True, create the execution record but skip the model run
            and the result upload. When ``script_config`` is set, the script
            is still invoked once with ``execution=None`` to print a preview;
            a plain ``model_config`` is skipped entirely (it may not handle
            ``execution=None``). Useful for testing configuration without
            running expensive computations. Defaults to False.
        ml_class: The DerivaML class (or subclass) to instantiate. If None,
            uses the base DerivaML class. Use this to instantiate
            domain-specific classes like EyeAI or GUDMAP.
        script_config: Optional alternate hydra-zen callable that, when
            provided, **takes precedence over** ``model_config`` as the code
            to invoke. Lets skill-generated scripts share this runner while
            living in their own config group. It is also the only path that
            runs during a dry run (see ``dry_run``).

    Returns:
        None. On a non-dry run, results are committed to the Deriva catalog as
        execution output assets; on a dry run, nothing is uploaded.

    Example:
        This function is typically not called directly, but through hydra::

            # From the command line:
            # python deriva_run.py +experiment=cifar10_cnn dry_run=True

            # Multirun (creates parent + child executions):
            # python deriva_run.py --multirun \
            #     +experiment=cifar10_quick,cifar10_extended

            # With a custom DerivaML subclass (in your script):
            >>> from functools import partial  # doctest: +SKIP
            >>> run_model_eyeai = partial(run_model, ml_class=EyeAI)  # doctest: +SKIP
    """
    global _multirun_state

    # Import here to avoid circular imports
    from deriva_ml import DerivaML
    from deriva_ml.execution import ExecutionConfiguration
    from deriva_ml.execution.base_config import _format_description_with_overrides

    # ---------------------------------------------------------------------------
    # Clear hydra's logging configuration
    # ---------------------------------------------------------------------------
    # Hydra sets up its own logging handlers which can interfere with DerivaML's
    # logging. Remove them to ensure consistent log output.
    root = logging.getLogger()
    for handler in root.handlers[:]:
        root.removeHandler(handler)

    # ---------------------------------------------------------------------------
    # Connect to the Deriva catalog
    # ---------------------------------------------------------------------------
    # Use the provided ml_class or default to DerivaML
    if ml_class is None:
        ml_class = DerivaML

    ml_instance = ml_class.instantiate(deriva_ml)

    # ---------------------------------------------------------------------------
    # Validate that all config RIDs exist in the catalog
    # ---------------------------------------------------------------------------
    # Check dataset RIDs, versions, and asset RIDs before creating an execution
    # or downloading any data. This catches typos, wrong catalogs, and stale
    # versions early with clear error messages.
    from deriva_ml.core.validation import validate_execution_config

    validation_result = validate_execution_config(ml_instance, datasets, assets)
    if not validation_result.is_valid:
        from deriva_ml.core.exceptions import DerivaMLException

        raise DerivaMLException(f"Execution config validation failed:\n{validation_result}")
    if validation_result.warnings:
        for warning in validation_result.warnings:
            logging.warning(warning)

    # ---------------------------------------------------------------------------
    # Correct workflow URL from model function source
    # ---------------------------------------------------------------------------
    # When run via `deriva-ml-run`, the Workflow object is created during Hydra
    # config resolution — before the model function is on the call stack. This
    # causes find_caller.py to pick up the CLI entry point (e.g.,
    # .venv/bin/deriva-ml-run) instead of the actual model file. Here we extract
    # the model function's source file and recompute the workflow URL.
    model_source = _resolve_model_source(model_config)
    if model_source is not None:
        try:
            from deriva_ml.execution.workflow import Workflow as _Wf

            new_url, new_checksum = _Wf.get_url_and_checksum(model_source, allow_dirty=workflow.allow_dirty)
            new_git_root = _Wf._get_git_root(model_source)
            workflow.url = new_url
            workflow.checksum = new_checksum
            workflow.git_root = new_git_root
        except Exception as e:
            logger.debug(f"Could not recompute workflow URL/checksum: {e}")

    # ---------------------------------------------------------------------------
    # Handle multirun mode - create parent execution on first job
    # ---------------------------------------------------------------------------
    is_multirun = _is_multirun()
    if is_multirun and _multirun_state.parent_execution is None:
        _create_parent_execution(ml_instance, workflow, description, dry_run)

    # ---------------------------------------------------------------------------
    # Capture Hydra runtime choices and overrides for provenance
    # ---------------------------------------------------------------------------
    # The choices dict maps config group names to the selected config names
    # e.g., {"model_config": "cifar10_quick", "datasets": "cifar10_training"}
    # Filter out None values (some Hydra internal groups have None choices).
    #
    # The overrides list is the resolved Hydra task-override list (the same
    # list Hydra echoes at the top of every run). It feeds into the Execution
    # description so the catalog row reflects what actually ran -- mirroring
    # the run_notebook pattern. Without this, a sweep that differs only in a
    # group/parameter override is indistinguishable from a default run when
    # browsing executions.
    config_choices: dict[str, str] = {}
    task_overrides: list[str] = []
    try:
        hydra_cfg = HydraConfig.get()
        config_choices = {k: v for k, v in hydra_cfg.runtime.choices.items() if v is not None}
        task_overrides = list(hydra_cfg.overrides.task)
    except Exception as e:
        logger.debug(f"HydraConfig not available (not in Hydra context): {e}")

    # The CLI synthesises a ``description='...'`` override in multirun mode
    # (see DerivaMLRunCLI.main). Including it inside the formatted
    # ``[overrides: ...]`` clause would recursively quote the base description
    # back into itself, so drop self-references on the description parameter
    # before composing. All other overrides (groups, parameters, package
    # specs) pass through verbatim, matching run_notebook's behaviour.
    description_overrides = [o for o in task_overrides if not o.startswith("description=")]

    # ---------------------------------------------------------------------------
    # Create the execution context
    # ---------------------------------------------------------------------------
    # The ExecutionConfiguration bundles together all the inputs for this run:
    # which datasets to use, which assets (model weights, etc.), and metadata.

    # Compose the description from the resolved Hydra overrides so the
    # catalog Execution row reflects what actually ran, not just the
    # registration-time default. This is symmetric with run_notebook
    # (see base_config.run_notebook), and the two entry points share
    # the same ``_format_description_with_overrides`` helper.
    composed_description = _format_description_with_overrides(description, description_overrides)

    # In multirun mode, enhance the description with job info
    job_description = composed_description
    if is_multirun:
        job_num = _get_job_num()
        job_description = f"[Job {job_num}] {composed_description}"

    execution_config = ExecutionConfiguration(
        datasets=datasets,
        assets=assets,
        description=job_description,
        config_choices=config_choices,
    )

    # Create the execution record in the catalog. This generates a unique
    # execution ID and sets up the working directories for this run.
    execution = ml_instance.create_execution(execution_config, workflow=workflow, dry_run=dry_run)

    # ---------------------------------------------------------------------------
    # Link to parent execution in multirun mode
    # ---------------------------------------------------------------------------
    if is_multirun and _multirun_state.parent_execution is not None:
        if not dry_run:
            try:
                # Get the current job sequence from the global state
                job_sequence = _multirun_state.job_sequence
                _multirun_state.parent_execution.add_nested_execution(execution, sequence=job_sequence)
                logging.info(
                    f"Linked execution {execution.execution_rid} to parent "
                    f"{_multirun_state.parent_execution_rid} (sequence={job_sequence})"
                )
                # Increment the sequence for the next job
                _multirun_state.job_sequence += 1
            except Exception as e:
                logging.warning(f"Failed to link execution to parent: {e}")

    # ---------------------------------------------------------------------------
    # Run the model within the execution context
    # ---------------------------------------------------------------------------
    # The context manager handles setup (downloading datasets, creating output
    # directories) and teardown (recording completion status, timing).
    with execution.execute() as exec_context:
        # Determine which callable to invoke. script_config takes precedence
        # over model_config when both are provided — this allows skill-generated
        # scripts to use a separate config group while sharing the same runner.
        callable_config = script_config if script_config is not None else model_config
        if dry_run:
            if script_config is not None:
                # Script configs handle dry run internally by checking
                # execution=None and printing a preview instead of writing.
                logging.info("Dry run mode: running script preview")
                callable_config(ml_instance=ml_instance, execution=None)
            else:
                # Model configs may not handle execution=None, so skip entirely.
                logging.info("Dry run mode: skipping model execution")
        else:
            callable_config(ml_instance=ml_instance, execution=exec_context)

    # ---------------------------------------------------------------------------
    # Upload results to the catalog
    # ---------------------------------------------------------------------------
    # After the model completes, upload any output files (metrics, predictions,
    # model checkpoints) to the Deriva catalog for permanent storage.
    #
    # NOTE(2026-05-19): previously this call passed timeout=... and
    # chunk_size=... kwargs. Both were unsupported by
    # Execution.commit_output_assets's signature (which only accepts
    # clean_folder and progress_callback) and the @validate_call decorator
    # made the mismatch fatal at runtime. The kwargs have been removed from
    # this call AND from run_model's signature because:
    #
    #   * chunk_size: had a defined home at DerivaUpload._hatracUpload's
    #     chunk_size parameter (deriva-py), but the call site at
    #     deriva.bag.catalog_loader._hatracUpload doesn't pass it through.
    #     Filed as a follow-up on deriva-py.
    #
    #   * timeout: has no home anywhere in the deriva-py upload chain.
    #     HatracStore.put_loc, _hatracUpload, and the underlying requests
    #     calls do not accept a per-call timeout. Adding it requires a
    #     deriva-py feature, not a deriva-ml plumbing change.
    #
    # Once deriva-py grows the matching support, re-introduce both
    # parameters here AND in run_model's signature.
    if not dry_run:
        report = execution.commit_output_assets()

        # Print summary of committed assets
        if report.total_uploaded > 0:
            print(f"\nCommitted {report.total_uploaded} asset(s) to catalog:")
            for fqn, counts in report.per_table.items():
                print(f"  - {fqn}: {counts['uploaded']}")

run_notebook

run_notebook(
    config_name: str | None = None,
    overrides: list[str] | None = None,
    workflow_name: str | None = None,
    workflow_type: str = "Analysis Notebook",
    ml_class: type[DerivaML]
    | None = None,
    config_package: str = "configs",
) -> tuple[
    DerivaML, Execution, BaseConfig
]

Initialize a notebook with DerivaML execution context.

This is the main entry point for notebooks. It handles all the setup: 1. Loads all config modules from the config package 2. Resolves the hydra-zen configuration 3. Creates the DerivaML connection 4. Creates a workflow and execution context 5. Downloads any specified datasets and assets

Parameters:

Name Type Description Default
config_name str | None

Name of the notebook configuration (registered via notebook_config() or store()). When omitted, the config name is derived from the calling notebook's filename stem -- the DerivaML convention is that X.ipynb uses config X (registered with notebook_config("X", ...)). Pass this explicitly only when the notebook's filename does not match its config name, which is rare.

None
overrides list[str] | None

Optional list of Hydra override strings (e.g., ["assets=different_assets"]).

None
workflow_name str | None

Name for the workflow. Defaults to config_name.

None
workflow_type str

Type of workflow (default: "Analysis Notebook").

'Analysis Notebook'
ml_class type[DerivaML] | None

Optional DerivaML subclass to use. If None, uses DerivaML.

None
config_package str

Package containing config modules (default: "configs").

'configs'

Returns:

Type Description
DerivaML

Tuple of (ml_instance, execution, config):

Execution
  • ml_instance: Connected DerivaML (or subclass) instance
BaseConfig
  • execution: Execution context with downloaded inputs
tuple[DerivaML, Execution, BaseConfig]
  • config: Resolved configuration object

Raises:

Type Description
ValueError

If config_name is omitted and cannot be derived from the calling context (e.g. when called from a plain .py script with no PAPERMILL_INPUT_PATH set).

Example

Simple usage -- config name derived from the notebook's

filename. Inside notebooks/roc_analysis.ipynb, this resolves

to config "roc_analysis":

from deriva_ml.execution import run_notebook

ml, execution, config = run_notebook()

Access config values

print(config.assets) print(config.deriva_ml.hostname)

Use ml and execution

for asset_table, paths in execution.asset_paths.items(): for path in paths: print(f"Downloaded: {path.file_name}")

At the end of notebook

execution.commit_output_assets()

Example with explicit config_name (rare -- only when the notebook's filename doesn't match its config name): ml, execution, config = run_notebook("custom_config_name")

Example with overrides

ml, execution, config = run_notebook( overrides=["assets=roc_quick_probabilities"], )

Example with custom ML class

from eye_ai import EyeAI

ml, execution, config = run_notebook(ml_class=EyeAI)

Source code in src/deriva_ml/execution/base_config.py
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
def run_notebook(
    config_name: str | None = None,
    overrides: list[str] | None = None,
    workflow_name: str | None = None,
    workflow_type: str = "Analysis Notebook",
    ml_class: type["DerivaML"] | None = None,
    config_package: str = "configs",
) -> tuple["DerivaML", "Execution", BaseConfig]:
    """Initialize a notebook with DerivaML execution context.

    This is the main entry point for notebooks. It handles all the setup:
    1. Loads all config modules from the config package
    2. Resolves the hydra-zen configuration
    3. Creates the DerivaML connection
    4. Creates a workflow and execution context
    5. Downloads any specified datasets and assets

    Args:
        config_name: Name of the notebook configuration (registered via
            notebook_config() or store()). When omitted, the config name is
            derived from the calling notebook's filename stem -- the
            DerivaML convention is that ``X.ipynb`` uses config ``X``
            (registered with ``notebook_config("X", ...)``). Pass this
            explicitly only when the notebook's filename does not match
            its config name, which is rare.
        overrides: Optional list of Hydra override strings
            (e.g., ["assets=different_assets"]).
        workflow_name: Name for the workflow. Defaults to config_name.
        workflow_type: Type of workflow (default: "Analysis Notebook").
        ml_class: Optional DerivaML subclass to use. If None, uses DerivaML.
        config_package: Package containing config modules (default: "configs").

    Returns:
        Tuple of (ml_instance, execution, config):
        - ml_instance: Connected DerivaML (or subclass) instance
        - execution: Execution context with downloaded inputs
        - config: Resolved configuration object

    Raises:
        ValueError: If ``config_name`` is omitted and cannot be derived
            from the calling context (e.g. when called from a plain
            ``.py`` script with no ``PAPERMILL_INPUT_PATH`` set).

    Example:
        # Simple usage -- config name derived from the notebook's
        # filename. Inside notebooks/roc_analysis.ipynb, this resolves
        # to config "roc_analysis":
        from deriva_ml.execution import run_notebook

        ml, execution, config = run_notebook()

        # Access config values
        print(config.assets)
        print(config.deriva_ml.hostname)

        # Use ml and execution
        for asset_table, paths in execution.asset_paths.items():
            for path in paths:
                print(f"Downloaded: {path.file_name}")

        # At the end of notebook
        execution.commit_output_assets()

    Example with explicit config_name (rare -- only when the notebook's
    filename doesn't match its config name):
        ml, execution, config = run_notebook("custom_config_name")

    Example with overrides:
        ml, execution, config = run_notebook(
            overrides=["assets=roc_quick_probabilities"],
        )

    Example with custom ML class:
        from eye_ai import EyeAI

        ml, execution, config = run_notebook(ml_class=EyeAI)
    """
    # Derive config_name from the calling notebook if not provided. The
    # convention "notebook X.ipynb uses config X" is universal across this
    # codebase, so the explicit string is redundant in every existing
    # case. Auto-derivation also removes the wrong example users
    # mis-imitate at the deriva-ml-run-notebook CLI ("just pass
    # roc_analysis as the first positional arg").
    if config_name is None:
        config_name = _derive_config_name_from_notebook()

    # Import here to avoid circular imports
    from deriva_ml import DerivaML
    from deriva_ml.execution import Execution, ExecutionConfiguration

    # Load all config modules
    load_configs(config_package)

    # Get the config builds class from our registry or try the store
    if config_name in _notebook_configs:
        config_builds, _ = _notebook_configs[config_name]
    else:
        # Fall back to looking up in hydra store by building a simple config
        # This handles configs registered the old way
        config_builds = DerivaBaseConfig

    # Resolve the configuration
    config = get_notebook_configuration(
        config_builds,
        config_name=config_name,
        overrides=overrides,
    )

    # Reconstruct the full override list the same way get_notebook_configuration
    # did, so the Execution description reflects what actually ran (not just the
    # registration-time default). DERIVA_ML_HYDRA_OVERRIDES is set by the
    # `deriva-ml-run-notebook` CLI when overrides are passed on the command line;
    # `overrides` is the in-process list passed by the notebook author.
    env_overrides_json = os.environ.get("DERIVA_ML_HYDRA_OVERRIDES")
    env_overrides = json.loads(env_overrides_json) if env_overrides_json else []
    all_overrides = env_overrides + (overrides or [])

    # Create DerivaML instance, passing the hydra output dir captured during
    # config resolution so that hydra YAML configs get uploaded with the execution.
    actual_ml_class = ml_class or DerivaML
    hydra_output_dir = Path(_captured_hydra_output_dir) if _captured_hydra_output_dir else None
    ml = actual_ml_class(
        hostname=config.deriva_ml.hostname,
        catalog_id=config.deriva_ml.catalog_id,
        hydra_runtime_output_dir=hydra_output_dir,
    )

    # Validate that all config RIDs exist in the catalog before proceeding.
    from deriva_ml.core.validation import validate_execution_config

    _datasets = config.datasets if config.datasets else []
    _assets = config.assets if config.assets else []
    validation_result = validate_execution_config(ml, _datasets, _assets)
    if not validation_result.is_valid:
        from deriva_ml.core.exceptions import DerivaMLException

        raise DerivaMLException(f"Notebook config validation failed:\n{validation_result}")
    if validation_result.warnings:
        import logging as _logging

        for warning in validation_result.warnings:
            _logging.warning(warning)

    # Create workflow. The workflow description is registration-shape (it
    # identifies the *kind* of work, not this specific run), so it stays at
    # the base description without override decoration.
    actual_workflow_name = workflow_name or config_name.replace("_", " ").title()
    workflow = ml.create_workflow(
        name=actual_workflow_name,
        workflow_type=workflow_type,
        description=config.description or f"Running {config_name}",
    )

    # Create execution configuration. The execution description is run-shape
    # (it identifies *this* specific run), so we append the resolved Hydra
    # overrides so the catalog row matches the work that actually ran. Without
    # this, an analyst sweeping `find_executions(workflow_type=...)` cannot
    # tell apart runs that differ only in their asset/datasets group.
    base_description = config.description or f"Execution of {config_name}"
    exec_config = ExecutionConfiguration(
        workflow=workflow,
        datasets=config.datasets if config.datasets else [],
        assets=config.assets if config.assets else [],
        description=_format_description_with_overrides(base_description, all_overrides),
    )

    # Create execution context (downloads inputs)
    execution = Execution(configuration=exec_config, ml_object=ml, dry_run=config.dry_run)

    # Transition Created → Running. Notebook code paths can't use a
    # ``with`` context manager around the cells (the kernel runs cells
    # one at a time and ``run_notebook`` returns to the user), so we
    # take the imperative ``execution_start()`` path here. Pairs with
    # ``commit_output_assets()`` at the end of the notebook, which
    # auto-stops the execution if it is still Running.
    execution.execution_start()

    return ml, execution, config

with_description

with_description(
    items: list, description: str
) -> Any

Create a hydra-zen config for a list with an attached description.

Use this to add descriptions to configuration values like asset RIDs or dataset specifications. The result is a hydra-zen config that, when instantiated, produces a DescribedList.

Parameters:

Name Type Description Default
items list

List items (e.g., asset RIDs, dataset specs).

required
description str

Human-readable description of this configuration.

required

Returns:

Type Description
Any

A hydra-zen config that instantiates to a DescribedList.

Example

from hydra_zen import store # doctest: +SKIP from deriva_ml.execution import with_description # doctest: +SKIP

Assets with description

asset_store = store(group="assets") # doctest: +SKIP asset_store( # doctest: +SKIP ... with_description( ... ["3WMG", "3XPA"], ... "Model weights from quick and extended training runs", ... ), ... name="comparison_weights", ... )

Datasets with description

from deriva_ml.dataset import DatasetSpecConfig # doctest: +SKIP datasets_store = store(group="datasets") # doctest: +SKIP datasets_store( # doctest: +SKIP ... with_description( ... [DatasetSpecConfig(rid="28CT", version="0.21.0")], ... "Complete CIFAR-10 dataset with 10,000 images", ... ), ... name="cifar10_complete", ... )

After instantiation:

config.assets is a DescribedList

config.assets[0] # "3WMG"

config.assets.description # "Model weights from..."

Note

For model configs created with builds(), use the zen_meta parameter instead:

model_store( # doctest: +SKIP ... Cifar10CNNConfig, ... name="cifar10_quick", ... epochs=3, ... zen_meta={"description": "Quick training - 3 epochs"}, ... )

Source code in src/deriva_ml/execution/base_config.py
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
def with_description(items: list, description: str) -> Any:
    """Create a hydra-zen config for a list with an attached description.

    Use this to add descriptions to configuration values like asset RIDs
    or dataset specifications. The result is a hydra-zen config that, when
    instantiated, produces a DescribedList.

    Args:
        items: List items (e.g., asset RIDs, dataset specs).
        description: Human-readable description of this configuration.

    Returns:
        A hydra-zen config that instantiates to a DescribedList.

    Example:
        >>> from hydra_zen import store  # doctest: +SKIP
        >>> from deriva_ml.execution import with_description  # doctest: +SKIP
        >>>
        >>> # Assets with description
        >>> asset_store = store(group="assets")  # doctest: +SKIP
        >>> asset_store(  # doctest: +SKIP
        ...     with_description(
        ...         ["3WMG", "3XPA"],
        ...         "Model weights from quick and extended training runs",
        ...     ),
        ...     name="comparison_weights",
        ... )
        >>>
        >>> # Datasets with description
        >>> from deriva_ml.dataset import DatasetSpecConfig  # doctest: +SKIP
        >>> datasets_store = store(group="datasets")  # doctest: +SKIP
        >>> datasets_store(  # doctest: +SKIP
        ...     with_description(
        ...         [DatasetSpecConfig(rid="28CT", version="0.21.0")],
        ...         "Complete CIFAR-10 dataset with 10,000 images",
        ...     ),
        ...     name="cifar10_complete",
        ... )
        >>>
        >>> # After instantiation:
        >>> # config.assets is a DescribedList
        >>> # config.assets[0]  # "3WMG"
        >>> # config.assets.description  # "Model weights from..."

    Note:
        For model configs created with `builds()`, use the `zen_meta` parameter
        instead:

        >>> model_store(  # doctest: +SKIP
        ...     Cifar10CNNConfig,
        ...     name="cifar10_quick",
        ...     epochs=3,
        ...     zen_meta={"description": "Quick training - 3 epochs"},
        ... )
    """
    return _DescribedListConfig(items=items, description=description)