Skip to content

Zen Stores

zenml.zen_stores

ZenStores define ways to store ZenML relevant data locally or remotely.

Modules

base_zen_store

Base Zen Store implementation.

Classes
BaseZenStore(skip_default_registrations: bool = False, **kwargs: Any)

Bases: BaseModel, ZenStoreInterface, ABC

Base class for accessing and persisting ZenML core objects.

Attributes:

Name Type Description
config StoreConfiguration

The configuration of the store.

Create and initialize a store.

Parameters:

Name Type Description Default
skip_default_registrations bool

If True, the creation of the default stack and user in the store will be skipped.

False
**kwargs Any

Additional keyword arguments to pass to the Pydantic constructor.

{}
Source code in src/zenml/zen_stores/base_zen_store.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def __init__(
    self,
    skip_default_registrations: bool = False,
    **kwargs: Any,
) -> None:
    """Create and initialize a store.

    Args:
        skip_default_registrations: If `True`, the creation of the default
            stack and user in the store will be skipped.
        **kwargs: Additional keyword arguments to pass to the Pydantic
            constructor.
    """
    super().__init__(**kwargs)

    self._initialize()

    if not skip_default_registrations:
        logger.debug("Initializing database")
        self._initialize_database()
    else:
        logger.debug("Skipping database initialization")
Attributes
type: StoreType property

The type of the store.

Returns:

Type Description
StoreType

The type of the store.

url: str property

The URL of the store.

Returns:

Type Description
str

The URL of the store.

Functions
convert_config(data: Dict[str, Any]) -> Dict[str, Any] classmethod

Method to infer the correct type of the config and convert.

Parameters:

Name Type Description Default
data Dict[str, Any]

The provided configuration object, can potentially be a generic object

required

Raises:

Type Description
ValueError

If the provided config object's type does not match any of the current implementations.

Returns:

Type Description
Dict[str, Any]

The converted configuration object.

Source code in src/zenml/zen_stores/base_zen_store.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
@model_validator(mode="before")
@classmethod
@before_validator_handler
def convert_config(cls, data: Dict[str, Any]) -> Dict[str, Any]:
    """Method to infer the correct type of the config and convert.

    Args:
        data: The provided configuration object, can potentially be a
            generic object

    Raises:
        ValueError: If the provided config object's type does not match
            any of the current implementations.

    Returns:
        The converted configuration object.
    """
    if data["config"].type == StoreType.SQL:
        from zenml.zen_stores.sql_zen_store import SqlZenStoreConfiguration

        data["config"] = SqlZenStoreConfiguration(
            **data["config"].model_dump()
        )

    elif data["config"].type == StoreType.REST:
        from zenml.zen_stores.rest_zen_store import (
            RestZenStoreConfiguration,
        )

        data["config"] = RestZenStoreConfiguration(
            **data["config"].model_dump()
        )
    else:
        raise ValueError(
            f"Unknown type '{data['config'].type}' for the configuration."
        )

    return data
create_store(config: StoreConfiguration, skip_default_registrations: bool = False, **kwargs: Any) -> BaseZenStore staticmethod

Create and initialize a store from a store configuration.

Parameters:

Name Type Description Default
config StoreConfiguration

The store configuration to use.

required
skip_default_registrations bool

If True, the creation of the default stack and user in the store will be skipped.

False
**kwargs Any

Additional keyword arguments to pass to the store class

{}

Returns:

Type Description
BaseZenStore

The initialized store.

Source code in src/zenml/zen_stores/base_zen_store.py
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
@staticmethod
def create_store(
    config: StoreConfiguration,
    skip_default_registrations: bool = False,
    **kwargs: Any,
) -> "BaseZenStore":
    """Create and initialize a store from a store configuration.

    Args:
        config: The store configuration to use.
        skip_default_registrations: If `True`, the creation of the default
            stack and user in the store will be skipped.
        **kwargs: Additional keyword arguments to pass to the store class

    Returns:
        The initialized store.
    """
    store_class = BaseZenStore.get_store_class(config.type)
    store = store_class(
        config=config,
        skip_default_registrations=skip_default_registrations,
        **kwargs,
    )

    return store
get_default_store_config(path: str) -> StoreConfiguration staticmethod

Get the default store configuration.

The default store is a SQLite store that saves the DB contents on the local filesystem.

Parameters:

Name Type Description Default
path str

The local path where the store DB will be stored.

required

Returns:

Type Description
StoreConfiguration

The default store configuration.

Source code in src/zenml/zen_stores/base_zen_store.py
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
@staticmethod
def get_default_store_config(path: str) -> StoreConfiguration:
    """Get the default store configuration.

    The default store is a SQLite store that saves the DB contents on the
    local filesystem.

    Args:
        path: The local path where the store DB will be stored.

    Returns:
        The default store configuration.
    """
    from zenml.zen_stores.secrets_stores.sql_secrets_store import (
        SqlSecretsStoreConfiguration,
    )
    from zenml.zen_stores.sql_zen_store import SqlZenStoreConfiguration

    config = SqlZenStoreConfiguration(
        type=StoreType.SQL,
        url=SqlZenStoreConfiguration.get_local_url(path),
        secrets_store=SqlSecretsStoreConfiguration(
            type=SecretsStoreType.SQL,
        ),
    )
    return config
get_external_user(user_id: UUID) -> UserResponse

Get a user by external ID.

Parameters:

Name Type Description Default
user_id UUID

The external ID of the user.

required

Returns:

Type Description
UserResponse

The user with the supplied external ID.

Raises:

Type Description
KeyError

If the user doesn't exist.

Source code in src/zenml/zen_stores/base_zen_store.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
def get_external_user(self, user_id: UUID) -> UserResponse:
    """Get a user by external ID.

    Args:
        user_id: The external ID of the user.

    Returns:
        The user with the supplied external ID.

    Raises:
        KeyError: If the user doesn't exist.
    """
    users = self.list_users(UserFilter(external_user_id=user_id))
    if users.total == 0:
        raise KeyError(f"User with external ID '{user_id}' not found.")
    return users.items[0]
get_store_class(store_type: StoreType) -> Type[BaseZenStore] staticmethod

Returns the class of the given store type.

Parameters:

Name Type Description Default
store_type StoreType

The type of the store to get the class for.

required

Returns:

Type Description
Type[BaseZenStore]

The class of the given store type or None if the type is unknown.

Raises:

Type Description
TypeError

If the store type is unsupported.

Source code in src/zenml/zen_stores/base_zen_store.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
@staticmethod
def get_store_class(store_type: StoreType) -> Type["BaseZenStore"]:
    """Returns the class of the given store type.

    Args:
        store_type: The type of the store to get the class for.

    Returns:
        The class of the given store type or None if the type is unknown.

    Raises:
        TypeError: If the store type is unsupported.
    """
    if store_type == StoreType.SQL:
        if os.environ.get(ENV_ZENML_SERVER):
            from zenml.zen_server.rbac.rbac_sql_zen_store import (
                RBACSqlZenStore,
            )

            return RBACSqlZenStore
        else:
            from zenml.zen_stores.sql_zen_store import SqlZenStore

            return SqlZenStore
    elif store_type == StoreType.REST:
        from zenml.zen_stores.rest_zen_store import RestZenStore

        return RestZenStore
    else:
        raise TypeError(
            f"No store implementation found for store type "
            f"`{store_type.value}`."
        )
get_store_config_class(store_type: StoreType) -> Type[StoreConfiguration] staticmethod

Returns the store config class of the given store type.

Parameters:

Name Type Description Default
store_type StoreType

The type of the store to get the class for.

required

Returns:

Type Description
Type[StoreConfiguration]

The config class of the given store type.

Source code in src/zenml/zen_stores/base_zen_store.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
@staticmethod
def get_store_config_class(
    store_type: StoreType,
) -> Type["StoreConfiguration"]:
    """Returns the store config class of the given store type.

    Args:
        store_type: The type of the store to get the class for.

    Returns:
        The config class of the given store type.
    """
    store_class = BaseZenStore.get_store_class(store_type)
    return store_class.CONFIG_TYPE
get_store_info() -> ServerModel

Get information about the store.

Returns:

Type Description
ServerModel

Information about the store.

Source code in src/zenml/zen_stores/base_zen_store.py
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
def get_store_info(self) -> ServerModel:
    """Get information about the store.

    Returns:
        Information about the store.
    """
    from zenml.zen_stores.sql_zen_store import SqlZenStore

    server_config = ServerConfiguration.get_server_config()
    deployment_type = server_config.deployment_type
    auth_scheme = server_config.auth_scheme
    metadata = server_config.metadata
    secrets_store_type = SecretsStoreType.NONE
    if isinstance(self, SqlZenStore) and self.config.secrets_store:
        secrets_store_type = self.config.secrets_store.type
    store_info = ServerModel(
        id=GlobalConfiguration().user_id,
        active=True,
        version=zenml.__version__,
        deployment_type=deployment_type,
        database_type=ServerDatabaseType.OTHER,
        debug=IS_DEBUG_ENV,
        secrets_store_type=secrets_store_type,
        auth_scheme=auth_scheme,
        server_url=server_config.server_url or "",
        dashboard_url=server_config.dashboard_url or "",
        analytics_enabled=GlobalConfiguration().analytics_opt_in,
        metadata=metadata,
    )

    # Add ZenML Pro specific store information to the server model, if available.
    if store_info.deployment_type == ServerDeploymentType.CLOUD:
        from zenml.config.server_config import ServerProConfiguration

        pro_config = ServerProConfiguration.get_server_config()

        store_info.pro_api_url = pro_config.api_url
        store_info.pro_dashboard_url = pro_config.dashboard_url
        store_info.pro_organization_id = pro_config.organization_id
        store_info.pro_workspace_id = pro_config.workspace_id
        if pro_config.workspace_name:
            store_info.pro_workspace_name = pro_config.workspace_name
        if pro_config.organization_name:
            store_info.pro_organization_name = pro_config.organization_name

    return store_info
get_store_type(url: str) -> StoreType staticmethod

Returns the store type associated with a URL schema.

Parameters:

Name Type Description Default
url str

The store URL.

required

Returns:

Type Description
StoreType

The store type associated with the supplied URL schema.

Raises:

Type Description
TypeError

If no store type was found to support the supplied URL.

Source code in src/zenml/zen_stores/base_zen_store.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
@staticmethod
def get_store_type(url: str) -> StoreType:
    """Returns the store type associated with a URL schema.

    Args:
        url: The store URL.

    Returns:
        The store type associated with the supplied URL schema.

    Raises:
        TypeError: If no store type was found to support the supplied URL.
    """
    from zenml.zen_stores.rest_zen_store import RestZenStoreConfiguration
    from zenml.zen_stores.sql_zen_store import SqlZenStoreConfiguration

    if SqlZenStoreConfiguration.supports_url_scheme(url):
        return StoreType.SQL
    elif RestZenStoreConfiguration.supports_url_scheme(url):
        return StoreType.REST
    else:
        raise TypeError(f"No store implementation found for URL: {url}.")
is_local_store() -> bool

Check if the store is local or connected to a local ZenML server.

Returns:

Type Description
bool

True if the store is local, False otherwise.

Source code in src/zenml/zen_stores/base_zen_store.py
447
448
449
450
451
452
453
def is_local_store(self) -> bool:
    """Check if the store is local or connected to a local ZenML server.

    Returns:
        True if the store is local, False otherwise.
    """
    return self.get_store_info().is_local()
validate_active_config(active_project_id: Optional[UUID] = None, active_stack_id: Optional[UUID] = None, config_name: str = '') -> Tuple[Optional[ProjectResponse], StackResponse]

Validate the active configuration.

Call this method to validate the supplied active project and active stack values.

This method returns a valid project and stack values. If the supplied project and stack are not set or are not valid (e.g. they do not exist or are not accessible), the default project and default stack will be returned in their stead.

Parameters:

Name Type Description Default
active_project_id Optional[UUID]

The ID of the active project.

None
active_stack_id Optional[UUID]

The ID of the active stack.

None
config_name str

The name of the configuration to validate (used in the displayed logs/messages).

''

Returns:

Type Description
Tuple[Optional[ProjectResponse], StackResponse]

A tuple containing the active project and active stack.

Source code in src/zenml/zen_stores/base_zen_store.py
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
def validate_active_config(
    self,
    active_project_id: Optional[UUID] = None,
    active_stack_id: Optional[UUID] = None,
    config_name: str = "",
) -> Tuple[Optional[ProjectResponse], StackResponse]:
    """Validate the active configuration.

    Call this method to validate the supplied active project and active
    stack values.

    This method returns a valid project and stack values. If the
    supplied project and stack are not set or are not valid (e.g. they
    do not exist or are not accessible), the default project and default
    stack will be returned in their stead.

    Args:
        active_project_id: The ID of the active project.
        active_stack_id: The ID of the active stack.
        config_name: The name of the configuration to validate (used in the
            displayed logs/messages).

    Returns:
        A tuple containing the active project and active stack.
    """
    active_project: Optional[ProjectResponse] = None

    if active_project_id:
        try:
            active_project = self.get_project(active_project_id)
        except (KeyError, IllegalOperationError):
            active_project_id = None
            logger.warning(
                f"The current {config_name} active project is no longer "
                f"available."
            )

    if active_project is None:
        user = self.get_user()
        if user.default_project_id:
            try:
                active_project = self.get_project(user.default_project_id)
            except (KeyError, IllegalOperationError):
                logger.warning(
                    "The default project %s for the active user is no longer "
                    "available.",
                    user.default_project_id,
                )
            else:
                logger.info(
                    f"Setting the {config_name} active project "
                    f"to '{active_project.name}'."
                )

    if active_project is None:
        try:
            projects = self.list_projects(
                project_filter_model=ProjectFilter()
            )
        except Exception:
            # There was some failure, we force the user to set the active
            # project manually
            logger.warning(
                "An active project is not set. Please set the active "
                "project by running `zenml project set <NAME>`."
            )
        else:
            if len(projects) == 0:
                logger.warning(
                    "No available projects. Please create a project by "
                    "running `zenml project register <NAME> --set`."
                )
            elif len(projects) == 1:
                active_project = projects.items[0]
                logger.info(
                    f"Setting the {config_name} active project "
                    f"to '{active_project.name}'."
                )
            else:
                logger.warning(
                    "Multiple projects are available. Please set the "
                    "active project by running `zenml project set <NAME>`."
                )

    active_stack: StackResponse

    # Sanitize the active stack
    if active_stack_id:
        # Ensure that the active stack is still valid
        try:
            active_stack = self.get_stack(stack_id=active_stack_id)
        except (KeyError, IllegalOperationError):
            logger.warning(
                "The current %s active stack is no longer available. "
                "Resetting the active stack to default.",
                config_name,
            )
            active_stack = self._get_default_stack()

    else:
        logger.warning(
            "Setting the %s active stack to default.",
            config_name,
        )
        active_stack = self._get_default_stack()

    return active_project, active_stack
Functions

migrations

Alembic database migration utilities.

Modules
alembic

Alembic utilities wrapper.

The Alembic class defined here acts as a wrapper around the Alembic library that automatically configures Alembic to use the ZenML SQL store database connection.

Classes
Alembic(engine: Engine, metadata: MetaData = SQLModel.metadata, context: Optional[EnvironmentContext] = None, **kwargs: Any)

Alembic environment and migration API.

This class provides a wrapper around the Alembic library that automatically configures Alembic to use the ZenML SQL store database connection.

Initialize the Alembic wrapper.

Parameters:

Name Type Description Default
engine Engine

The SQLAlchemy engine to use.

required
metadata MetaData

The SQLAlchemy metadata to use.

metadata
context Optional[EnvironmentContext]

The Alembic environment context to use. If not set, a new context is created pointing to the ZenML migrations directory.

None
**kwargs Any

Additional keyword arguments to pass to the Alembic environment context.

{}
Source code in src/zenml/zen_stores/migrations/alembic.py
 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
def __init__(
    self,
    engine: Engine,
    metadata: MetaData = SQLModel.metadata,
    context: Optional[EnvironmentContext] = None,
    **kwargs: Any,
) -> None:
    """Initialize the Alembic wrapper.

    Args:
        engine: The SQLAlchemy engine to use.
        metadata: The SQLAlchemy metadata to use.
        context: The Alembic environment context to use. If not set, a new
            context is created pointing to the ZenML migrations directory.
        **kwargs: Additional keyword arguments to pass to the Alembic
            environment context.
    """
    self.engine = engine
    self.metadata = metadata
    self.context_kwargs = kwargs

    self.config = Config()
    self.config.set_main_option(
        "script_location", str(Path(__file__).parent)
    )

    self.script_directory = ScriptDirectory.from_config(self.config)
    if context is None:
        self.environment_context = EnvironmentContext(
            self.config, self.script_directory
        )
    else:
        self.environment_context = context
Functions
current_revisions() -> List[str]

Get the current database revisions.

Returns:

Type Description
List[str]

List of head revisions.

Source code in src/zenml/zen_stores/migrations/alembic.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def current_revisions(self) -> List[str]:
    """Get the current database revisions.

    Returns:
        List of head revisions.
    """
    current_revisions: List[str] = []

    def do_get_current_rev(rev: _RevIdType, context: Any) -> List[Any]:
        nonlocal current_revisions

        for r in self.script_directory.get_all_current(
            rev  # type:ignore [arg-type]
        ):
            if r is None:
                continue
            current_revisions.append(r.revision)
        return []

    self.run_migrations(do_get_current_rev)

    return current_revisions
db_is_empty() -> bool

Check if the database is empty.

Returns:

Type Description
bool

True if the database is empty, False otherwise.

Source code in src/zenml/zen_stores/migrations/alembic.py
112
113
114
115
116
117
118
119
120
121
def db_is_empty(self) -> bool:
    """Check if the database is empty.

    Returns:
        True if the database is empty, False otherwise.
    """
    # Check the existence of any of the SQLModel tables
    return not self.engine.dialect.has_table(
        self.engine.connect(), schemas.StackSchema.__tablename__
    )
downgrade(revision: str) -> None

Revert the database to a previous version.

Parameters:

Name Type Description Default
revision str

String revision target.

required
Source code in src/zenml/zen_stores/migrations/alembic.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def downgrade(self, revision: str) -> None:
    """Revert the database to a previous version.

    Args:
        revision: String revision target.
    """

    def do_downgrade(rev: _RevIdType, context: Any) -> List[Any]:
        return self.script_directory._downgrade_revs(
            revision,
            rev,  # type:ignore [arg-type]
        )

    self.run_migrations(do_downgrade)
head_revisions() -> List[str]

Get the head database revisions.

Returns:

Type Description
List[str]

List of head revisions.

Source code in src/zenml/zen_stores/migrations/alembic.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def head_revisions(self) -> List[str]:
    """Get the head database revisions.

    Returns:
        List of head revisions.
    """
    head_revisions: List[str] = []

    def do_get_head_rev(rev: _RevIdType, context: Any) -> List[Any]:
        nonlocal head_revisions

        for r in self.script_directory.get_heads():
            if r is None:
                continue
            head_revisions.append(r)
        return []

    self.run_migrations(do_get_head_rev)

    return head_revisions
run_migrations(fn: Optional[Callable[[_RevIdType, MigrationContext], List[Any]]]) -> None

Run an online migration function in the current migration context.

Parameters:

Name Type Description Default
fn Optional[Callable[[_RevIdType, MigrationContext], List[Any]]]

Migration function to run. If not set, the function configured externally by the Alembic CLI command is used.

required
Source code in src/zenml/zen_stores/migrations/alembic.py
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
def run_migrations(
    self,
    fn: Optional[Callable[[_RevIdType, MigrationContext], List[Any]]],
) -> None:
    """Run an online migration function in the current migration context.

    Args:
        fn: Migration function to run. If not set, the function configured
            externally by the Alembic CLI command is used.
    """
    fn_context_args: Dict[Any, Any] = {}
    if fn is not None:
        fn_context_args["fn"] = fn

    with self.engine.connect() as connection:
        self.environment_context.configure(
            connection=connection,
            target_metadata=self.metadata,
            include_object=include_object,
            compare_type=True,
            render_as_batch=True,
            **fn_context_args,
            **self.context_kwargs,
        )

        with self.environment_context.begin_transaction():
            self.environment_context.run_migrations()
stamp(revision: str) -> None

Stamp the revision table with the given revision without running any migrations.

Parameters:

Name Type Description Default
revision str

String revision target.

required
Source code in src/zenml/zen_stores/migrations/alembic.py
195
196
197
198
199
200
201
202
203
204
205
def stamp(self, revision: str) -> None:
    """Stamp the revision table with the given revision without running any migrations.

    Args:
        revision: String revision target.
    """

    def do_stamp(rev: _RevIdType, context: Any) -> List[Any]:
        return self.script_directory._stamp_revs(revision, rev)

    self.run_migrations(do_stamp)
upgrade(revision: str = 'heads') -> None

Upgrade the database to a later version.

Parameters:

Name Type Description Default
revision str

String revision target.

'heads'
Source code in src/zenml/zen_stores/migrations/alembic.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def upgrade(self, revision: str = "heads") -> None:
    """Upgrade the database to a later version.

    Args:
        revision: String revision target.
    """

    def do_upgrade(rev: _RevIdType, context: Any) -> List[Any]:
        return self.script_directory._upgrade_revs(
            revision,
            rev,  # type:ignore [arg-type]
        )

    self.run_migrations(do_upgrade)
AlembicVersion

Bases: Base

Alembic version table.

Functions
include_object(object: Any, name: str, type_: str, *args: Any, **kwargs: Any) -> bool

Function used to exclude tables from the migration scripts.

Parameters:

Name Type Description Default
object Any

The schema item object to check.

required
name str

The name of the object to check.

required
type_ str

The type of the object to check.

required
*args Any

Additional arguments.

()
**kwargs Any

Additional keyword arguments.

{}

Returns:

Type Description
bool

True if the object should be included, False otherwise.

Source code in src/zenml/zen_stores/migrations/alembic.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def include_object(
    object: Any, name: str, type_: str, *args: Any, **kwargs: Any
) -> bool:
    """Function used to exclude tables from the migration scripts.

    Args:
        object: The schema item object to check.
        name: The name of the object to check.
        type_: The type of the object to check.
        *args: Additional arguments.
        **kwargs: Additional keyword arguments.

    Returns:
        True if the object should be included, False otherwise.
    """
    return not (type_ == "table" and name in exclude_tables)
Modules
utils

ZenML database migration, backup and recovery utilities.

Classes
MigrationUtils

Bases: BaseModel

Utilities for database migration, backup and recovery.

Attributes
engine: Engine property

The SQLAlchemy engine.

Returns:

Type Description
Engine

The SQLAlchemy engine.

master_engine: Engine property

The SQLAlchemy engine for the master database.

Returns:

Type Description
Engine

The SQLAlchemy engine for the master database.

Functions
backup_database_to_db(backup_db_name: str) -> None

Backup the database to a backup database.

Parameters:

Name Type Description Default
backup_db_name str

Backup database name to backup to.

required
Source code in src/zenml/zen_stores/migrations/utils.py
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
def backup_database_to_db(self, backup_db_name: str) -> None:
    """Backup the database to a backup database.

    Args:
        backup_db_name: Backup database name to backup to.
    """
    # Re-create the backup database
    self.create_database(
        database=backup_db_name,
        drop=True,
    )

    backup_engine = self.create_engine(database=backup_db_name)

    self._copy_database(self.engine, backup_engine)

    logger.debug(
        f"Database backed up to the `{backup_db_name}` backup database."
    )
backup_database_to_file(dump_file: str) -> None

Backup the database to a file.

This method dumps the entire database into a JSON file. Instead of using a SQL dump, we use a proprietary JSON dump because:

* it is (mostly) not dependent on the SQL dialect or database version
* it is safer with respect to SQL injection attacks
* it is easier to read and debug

The JSON file contains a list of JSON objects instead of a single JSON object, because it allows for buffered reading and writing of the file and thus reduces the memory footprint. Each JSON object can contain either schema or data information about a single table. For tables with a large amount of data, the data is split into multiple JSON objects with the first object always containing the schema.

The format of the dump is as depicted in the following example:

{
    "table": "table1",
    "create_stmt": "CREATE TABLE table1 (id INTEGER NOT NULL, "
        "name VARCHAR(255), PRIMARY KEY (id))"
}
{
    "table": "table1",
    "data": [
    {
        "id": 1,
        "name": "foo"
    },
    {
        "id": 1,
        "name": "bar"
    },
    ...
    ]
}
{
    "table": "table1",
    "data": [
    {
        "id": 101,
        "name": "fee"
    },
    {
        "id": 102,
        "name": "bee"
    },
    ...
    ]
}

Parameters:

Name Type Description Default
dump_file str

The path to the dump file.

required
Source code in src/zenml/zen_stores/migrations/utils.py
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
def backup_database_to_file(self, dump_file: str) -> None:
    """Backup the database to a file.

    This method dumps the entire database into a JSON file. Instead of
    using a SQL dump, we use a proprietary JSON dump because:

        * it is (mostly) not dependent on the SQL dialect or database version
        * it is safer with respect to SQL injection attacks
        * it is easier to read and debug

    The JSON file contains a list of JSON objects instead of a single JSON
    object, because it allows for buffered reading and writing of the file
    and thus reduces the memory footprint. Each JSON object can contain
    either schema or data information about a single table. For tables with
    a large amount of data, the data is split into multiple JSON objects
    with the first object always containing the schema.

    The format of the dump is as depicted in the following example:

    ```json
    {
        "table": "table1",
        "create_stmt": "CREATE TABLE table1 (id INTEGER NOT NULL, "
            "name VARCHAR(255), PRIMARY KEY (id))"
    }
    {
        "table": "table1",
        "data": [
        {
            "id": 1,
            "name": "foo"
        },
        {
            "id": 1,
            "name": "bar"
        },
        ...
        ]
    }
    {
        "table": "table1",
        "data": [
        {
            "id": 101,
            "name": "fee"
        },
        {
            "id": 102,
            "name": "bee"
        },
        ...
        ]
    }
    ```

    Args:
        dump_file: The path to the dump file.
    """
    # create the directory if it does not exist
    dump_path = os.path.dirname(os.path.abspath(dump_file))
    if not os.path.exists(dump_path):
        os.makedirs(dump_path)

    if self.url.drivername == "sqlite":
        # For a sqlite database, we can just make a copy of the database
        # file
        assert self.url.database is not None
        shutil.copyfile(
            self.url.database,
            dump_file,
        )
        return

    with open(dump_file, "w") as f:

        def json_dump(obj: Dict[str, Any]) -> None:
            """Dump a JSON object to the dump file.

            Args:
                obj: The JSON object to dump.
            """
            # Write the data to the JSON file. Use an encoder that
            # can handle datetime, Decimal and other types.
            json.dump(
                obj,
                f,
                indent=4,
                default=pydantic_encoder,
            )
            f.write("\n")

        # Call the generic backup method with a function that dumps the
        # JSON objects to the dump file
        self.backup_database_to_storage(json_dump)

    logger.debug(f"Database backed up to {dump_file}")
backup_database_to_memory() -> List[Dict[str, Any]]

Backup the database in memory.

Returns:

Type Description
List[Dict[str, Any]]

The in-memory representation of the database backup.

Raises:

Type Description
RuntimeError

If the database cannot be backed up successfully.

Source code in src/zenml/zen_stores/migrations/utils.py
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
def backup_database_to_memory(self) -> List[Dict[str, Any]]:
    """Backup the database in memory.

    Returns:
        The in-memory representation of the database backup.

    Raises:
        RuntimeError: If the database cannot be backed up successfully.
    """
    if self.url.drivername == "sqlite":
        # For a sqlite database, this is not supported.
        raise RuntimeError(
            "In-memory backup is not supported for sqlite databases."
        )

    db_dump: List[Dict[str, Any]] = []

    def store_in_mem(obj: Dict[str, Any]) -> None:
        """Store a JSON object in the in-memory database backup.

        Args:
            obj: The JSON object to store.
        """
        db_dump.append(obj)

    # Call the generic backup method with a function that stores the
    # JSON objects in the in-memory database backup
    self.backup_database_to_storage(store_in_mem)

    logger.debug("Database backed up in memory")

    return db_dump
backup_database_to_storage(store_db_info: Callable[[Dict[str, Any]], None]) -> None

Backup the database to a storage location.

Backup the database to an abstract storage location. The storage location is specified by a function that is called repeatedly to store the database information. The function is called with a single argument, which is a dictionary containing either the table schema or table data. The dictionary contains the following keys:

* `table`: The name of the table.
* `create_stmt`: The table creation statement.
* `data`: A list of rows in the table.

Parameters:

Name Type Description Default
store_db_info Callable[[Dict[str, Any]], None]

The function to call to store the database information.

required
Source code in src/zenml/zen_stores/migrations/utils.py
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
def backup_database_to_storage(
    self, store_db_info: Callable[[Dict[str, Any]], None]
) -> None:
    """Backup the database to a storage location.

    Backup the database to an abstract storage location. The storage
    location is specified by a function that is called repeatedly to
    store the database information. The function is called with a single
    argument, which is a dictionary containing either the table schema or
    table data. The dictionary contains the following keys:

        * `table`: The name of the table.
        * `create_stmt`: The table creation statement.
        * `data`: A list of rows in the table.

    Args:
        store_db_info: The function to call to store the database
            information.
    """
    metadata = MetaData()
    metadata.reflect(bind=self.engine)
    with self.engine.connect() as conn:
        for table in metadata.sorted_tables:
            # 1. extract the table creation statements

            create_table_construct = CreateTable(table)
            create_table_stmt = str(create_table_construct).strip()
            for column in create_table_construct.columns:
                # enclosing all column names in backticks. This is because
                # some column names are reserved keywords in MySQL. For
                # example, keys and values. So, instead of tracking all
                # keywords, we just enclose all column names in backticks.
                # enclose the first word in the column definition in
                # backticks
                words = str(column).split()
                words[0] = f"`{words[0]}`"
                create_table_stmt = create_table_stmt.replace(
                    f"\n\t{str(column)}", " ".join(words)
                )
            # if any double quotes are used for column names, replace them
            # with backticks
            create_table_stmt = create_table_stmt.replace('"', "") + ";"

            # enclose all table names in backticks. This is because some
            # table names are reserved keywords in MySQL (e.g key
            # and trigger).
            create_table_stmt = create_table_stmt.replace(
                f"CREATE TABLE {table.name}",
                f"CREATE TABLE `{table.name}`",
            )
            # do the same for references to other tables
            # (i.e. foreign key constraints) by replacing REFERENCES <word>
            # with REFERENCES `<word>`
            # use a regular expression for this
            create_table_stmt = re.sub(
                r"REFERENCES\s+(\w+)",
                r"REFERENCES `\1`",
                create_table_stmt,
            )

            # In SQLAlchemy, the CreateTable statement may not always
            # include unique constraints explicitly if they are implemented
            # as unique indexes instead. To make sure we get all unique
            # constraints, including those implemented as indexes, we
            # extract the unique constraints from the table schema and add
            # them to the create table statement.

            # Extract the unique constraints from the table schema
            index_create_statements = []
            unique_constraints = []
            for index in table.indexes:
                if index.unique:
                    unique_columns = [
                        f"`{column.name}`" for column in index.columns
                    ]
                    unique_constraints.append(
                        f"UNIQUE KEY `{index.name}` ({', '.join(unique_columns)})"
                    )
                else:
                    if index.name in {
                        fk.name for fk in table.foreign_key_constraints
                    }:
                        # Foreign key indices are already handled by the
                        # table creation statement.
                        continue

                    index_create = str(CreateIndex(index)).strip()  # type: ignore[no-untyped-call]
                    index_create = index_create.replace(
                        f"CREATE INDEX {index.name}",
                        f"CREATE INDEX `{index.name}`",
                    )
                    index_create = index_create.replace(
                        f"ON {table.name}", f"ON `{table.name}`"
                    )

                    for column_name in index.columns.keys():
                        # We need this logic here to avoid the column names
                        # inside the index name
                        index_create = index_create.replace(
                            f"({column_name}", f"(`{column_name}`"
                        )
                        index_create = index_create.replace(
                            f"{column_name},", f"`{column_name}`,"
                        )
                        index_create = index_create.replace(
                            f"{column_name})", f"`{column_name}`)"
                        )

                    index_create = index_create.replace('"', "") + ";"
                    index_create_statements.append(index_create)

            # Add the unique constraints to the create table statement
            if unique_constraints:
                # Remove the closing parenthesis, semicolon and any
                # whitespaces at the end of the create table statement
                create_table_stmt = re.sub(
                    r"\s*\)\s*;\s*$", "", create_table_stmt
                )
                create_table_stmt = (
                    create_table_stmt
                    + ", \n\t"
                    + ", \n\t".join(unique_constraints)
                    + "\n);"
                )

            # Detect self-referential foreign keys from the table schema
            has_self_referential_foreign_keys = False
            for fk in table.foreign_keys:
                # Check if the foreign key points to the same table
                if fk.column.table == table:
                    has_self_referential_foreign_keys = True
                    break

            # Store the table schema
            store_db_info(
                dict(
                    table=table.name,
                    create_stmt=create_table_stmt,
                    self_references=has_self_referential_foreign_keys,
                )
            )

            for stmt in index_create_statements:
                store_db_info(
                    dict(
                        table=table.name,
                        index_create_stmt=stmt,
                    )
                )

            # 2. extract the table data in batches
            order_by = [col for col in table.primary_key]

            # Fetch the number of rows in the table
            row_count = conn.scalar(
                select(func.count()).select_from(table)
            )

            # Fetch the data from the table in batches
            if row_count is not None:
                batch_size = 100
                for i in range(0, row_count, batch_size):
                    rows = conn.execute(
                        table.select()
                        .order_by(*order_by)
                        .limit(batch_size)
                        .offset(i)
                    ).fetchall()

                    store_db_info(
                        dict(
                            table=table.name,
                            data=[row._asdict() for row in rows],
                        ),
                    )
create_database(database: Optional[str] = None, drop: bool = False) -> None

Creates a mysql database.

Parameters:

Name Type Description Default
database Optional[str]

The name of the database to create. If not set, the database name from the configuration will be used.

None
drop bool

Whether to drop the database if it already exists.

False
Source code in src/zenml/zen_stores/migrations/utils.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def create_database(
    self,
    database: Optional[str] = None,
    drop: bool = False,
) -> None:
    """Creates a mysql database.

    Args:
        database: The name of the database to create. If not set, the
            database name from the configuration will be used.
        drop: Whether to drop the database if it already exists.
    """
    database = database or self.url.database
    if drop:
        self.drop_database(database=database)

    with self.master_engine.connect() as conn:
        logger.info(f"Creating database '{database}'")
        conn.execute(text(f"CREATE DATABASE IF NOT EXISTS `{database}`"))
create_engine(database: Optional[str] = None) -> Engine

Get the SQLAlchemy engine for a database.

Parameters:

Name Type Description Default
database Optional[str]

The name of the database. If not set, a master engine will be returned.

None

Returns:

Type Description
Engine

The SQLAlchemy engine.

Source code in src/zenml/zen_stores/migrations/utils.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def create_engine(self, database: Optional[str] = None) -> Engine:
    """Get the SQLAlchemy engine for a database.

    Args:
        database: The name of the database. If not set, a master engine
            will be returned.

    Returns:
        The SQLAlchemy engine.
    """
    url = self.url._replace(database=database)
    return create_engine(
        url=url,
        connect_args=self.connect_args,
        **self.engine_args,
    )
database_exists(database: Optional[str] = None) -> bool

Check if a database exists.

Parameters:

Name Type Description Default
database Optional[str]

The name of the database to check. If not set, the database name from the configuration will be used.

None

Returns:

Type Description
bool

Whether the database exists.

Raises:

Type Description
OperationalError

If connecting to the database failed.

Source code in src/zenml/zen_stores/migrations/utils.py
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
def database_exists(
    self,
    database: Optional[str] = None,
) -> bool:
    """Check if a database exists.

    Args:
        database: The name of the database to check. If not set, the
            database name from the configuration will be used.

    Returns:
        Whether the database exists.

    Raises:
        OperationalError: If connecting to the database failed.
    """
    database = database or self.url.database

    engine = self.create_engine(database=database)
    try:
        engine.connect()
    except OperationalError as e:
        if self.is_mysql_missing_database_error(e):
            return False
        else:
            logger.exception(
                f"Failed to connect to mysql database `{database}`.",
            )
            raise
    else:
        return True
drop_database(database: Optional[str] = None) -> None

Drops a mysql database.

Parameters:

Name Type Description Default
database Optional[str]

The name of the database to drop. If not set, the database name from the configuration will be used.

None
Source code in src/zenml/zen_stores/migrations/utils.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def drop_database(
    self,
    database: Optional[str] = None,
) -> None:
    """Drops a mysql database.

    Args:
        database: The name of the database to drop. If not set, the
            database name from the configuration will be used.
    """
    database = database or self.url.database
    with self.master_engine.connect() as conn:
        # drop the database if it exists
        logger.info(f"Dropping database '{database}'")
        conn.execute(text(f"DROP DATABASE IF EXISTS `{database}`"))
is_mysql_missing_database_error(error: OperationalError) -> bool classmethod

Checks if the given error is due to a missing database.

Parameters:

Name Type Description Default
error OperationalError

The error to check.

required

Returns:

Type Description
bool

If the error because the MySQL database doesn't exist.

Source code in src/zenml/zen_stores/migrations/utils.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
@classmethod
def is_mysql_missing_database_error(cls, error: OperationalError) -> bool:
    """Checks if the given error is due to a missing database.

    Args:
        error: The error to check.

    Returns:
        If the error because the MySQL database doesn't exist.
    """
    from pymysql.constants.ER import BAD_DB_ERROR

    if not isinstance(error.orig, pymysql.err.OperationalError):
        return False

    error_code = cast(int, error.orig.args[0])
    return error_code == BAD_DB_ERROR
restore_database_from_db(backup_db_name: str) -> None

Restore the database from the backup database.

Parameters:

Name Type Description Default
backup_db_name str

Backup database name to restore from.

required

Raises:

Type Description
RuntimeError

If the backup database does not exist.

Source code in src/zenml/zen_stores/migrations/utils.py
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
def restore_database_from_db(self, backup_db_name: str) -> None:
    """Restore the database from the backup database.

    Args:
        backup_db_name: Backup database name to restore from.

    Raises:
        RuntimeError: If the backup database does not exist.
    """
    if not self.database_exists(database=backup_db_name):
        raise RuntimeError(
            f"Backup database `{backup_db_name}` does not exist."
        )

    backup_engine = self.create_engine(database=backup_db_name)

    # Drop and re-create the primary database
    self.create_database(
        drop=True,
    )

    self._copy_database(backup_engine, self.engine)

    logger.debug(
        f"Database restored from the `{backup_db_name}` backup database."
    )
restore_database_from_file(dump_file: str) -> None

Restore the database from a backup dump file.

See the documentation of the backup_database_to_file method for details on the format of the dump file.

Parameters:

Name Type Description Default
dump_file str

The path to the dump file.

required

Raises:

Type Description
RuntimeError

If the database cannot be restored successfully.

Source code in src/zenml/zen_stores/migrations/utils.py
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
def restore_database_from_file(self, dump_file: str) -> None:
    """Restore the database from a backup dump file.

    See the documentation of the `backup_database_to_file` method for
    details on the format of the dump file.

    Args:
        dump_file: The path to the dump file.

    Raises:
        RuntimeError: If the database cannot be restored successfully.
    """
    if not os.path.exists(dump_file):
        raise RuntimeError(
            f"Database backup file '{dump_file}' does not "
            f"exist or is not accessible."
        )

    if self.url.drivername == "sqlite":
        # For a sqlite database, we just overwrite the database file
        # with the backup file
        assert self.url.database is not None
        shutil.copyfile(
            dump_file,
            self.url.database,
        )
        return

    # read the DB dump file one JSON object at a time
    with open(dump_file, "r") as f:

        def json_load() -> Generator[Dict[str, Any], None, None]:
            """Generator that loads the JSON objects in the dump file.

            Yields:
                The loaded JSON objects.
            """
            buffer = ""
            while True:
                chunk = f.readline()
                if not chunk:
                    break
                buffer += chunk
                if chunk.rstrip() == "}":
                    yield json.loads(buffer)
                    buffer = ""

        # Call the generic restore method with a function that loads the
        # JSON objects from the dump file
        self.restore_database_from_storage(json_load)

    logger.info(f"Database successfully restored from '{dump_file}'")
restore_database_from_memory(db_dump: List[Dict[str, Any]]) -> None

Restore the database from an in-memory backup.

Parameters:

Name Type Description Default
db_dump List[Dict[str, Any]]

The in-memory database backup to restore from generated by the backup_database_to_memory method.

required

Raises:

Type Description
RuntimeError

If the database cannot be restored successfully.

Source code in src/zenml/zen_stores/migrations/utils.py
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
def restore_database_from_memory(
    self, db_dump: List[Dict[str, Any]]
) -> None:
    """Restore the database from an in-memory backup.

    Args:
        db_dump: The in-memory database backup to restore from generated
            by the `backup_database_to_memory` method.

    Raises:
        RuntimeError: If the database cannot be restored successfully.
    """
    if self.url.drivername == "sqlite":
        # For a sqlite database, this is not supported.
        raise RuntimeError(
            "In-memory backup is not supported for sqlite databases."
        )

    def load_from_mem() -> Generator[Dict[str, Any], None, None]:
        """Generator that loads the JSON objects from the in-memory backup.

        Yields:
            The loaded JSON objects.
        """
        for obj in db_dump:
            yield obj

    # Call the generic restore method with a function that loads the
    # JSON objects from the in-memory database backup
    self.restore_database_from_storage(load_from_mem)

    logger.info("Database successfully restored from memory")
restore_database_from_storage(load_db_info: Callable[[], Generator[Dict[str, Any], None, None]]) -> None

Restore the database from a backup storage location.

Restores the database from an abstract storage location. The storage location is specified by a function that is called repeatedly to load the database information from the external storage chunk by chunk. The function must yield a dictionary containing either the table schema or table data. The dictionary contains the following keys:

* `table`: The name of the table.
* `create_stmt`: The table creation statement.
* `data`: A list of rows in the table.

The function must return None when there is no more data to load.

Parameters:

Name Type Description Default
load_db_info Callable[[], Generator[Dict[str, Any], None, None]]

The function to call to load the database information.

required
Source code in src/zenml/zen_stores/migrations/utils.py
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
def restore_database_from_storage(
    self, load_db_info: Callable[[], Generator[Dict[str, Any], None, None]]
) -> None:
    """Restore the database from a backup storage location.

    Restores the database from an abstract storage location. The storage
    location is specified by a function that is called repeatedly to
    load the database information from the external storage chunk by chunk.
    The function must yield a dictionary containing either the table schema
    or table data. The dictionary contains the following keys:

        * `table`: The name of the table.
        * `create_stmt`: The table creation statement.
        * `data`: A list of rows in the table.

    The function must return `None` when there is no more data to load.

    Args:
        load_db_info: The function to call to load the database
            information.
    """
    # Drop and re-create the primary database
    self.create_database(drop=True)

    metadata = MetaData()

    with self.engine.begin() as connection:
        # read the DB information one JSON object at a time
        self_references: Dict[str, bool] = {}
        for table_dump in load_db_info():
            table_name = table_dump["table"]
            if "create_stmt" in table_dump:
                # execute the table creation statement
                connection.execute(text(table_dump["create_stmt"]))
                # Reload the database metadata after creating the table
                metadata.reflect(bind=self.engine)
                self_references[table_name] = table_dump.get(
                    "self_references", False
                )

            if "index_create_stmt" in table_dump:
                # execute the index creation statement
                connection.execute(text(table_dump["index_create_stmt"]))
                # Reload the database metadata after creating the index
                metadata.reflect(bind=self.engine)

            if "data" in table_dump:
                # insert the data into the database
                table = metadata.tables[table_name]
                if self_references.get(table_name, False):
                    # If the table has self-referential foreign keys, we
                    # need to disable the foreign key checks before inserting
                    # the rows and re-enable them afterwards. This is because
                    # the rows need to be inserted in the correct order to
                    # satisfy the foreign key constraints and we don't sort
                    # the rows by creation time in the backup.
                    connection.execute(text("SET FOREIGN_KEY_CHECKS = 0"))

                for row in table_dump["data"]:
                    # Convert column values to the correct type
                    for column in table.columns:
                        # Blob columns are stored as binary strings
                        if column.type.python_type is bytes and isinstance(
                            row[column.name], str
                        ):
                            # Convert the string to bytes
                            row[column.name] = bytes(
                                row[column.name], "utf-8"
                            )

                # Insert the rows into the table in batches
                batch_size = 100
                for i in range(0, len(table_dump["data"]), batch_size):
                    connection.execute(
                        table.insert().values(
                            table_dump["data"][i : i + batch_size]
                        )
                    )

                if table_dump.get("self_references", False):
                    # Re-enable the foreign key checks after inserting the rows
                    connection.execute(text("SET FOREIGN_KEY_CHECKS = 1"))
Functions

rest_zen_store

REST Zen Store implementation.

Classes
RestZenStore(skip_default_registrations: bool = False, **kwargs: Any)

Bases: BaseZenStore

Store implementation for accessing data from a REST API.

Source code in src/zenml/zen_stores/base_zen_store.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def __init__(
    self,
    skip_default_registrations: bool = False,
    **kwargs: Any,
) -> None:
    """Create and initialize a store.

    Args:
        skip_default_registrations: If `True`, the creation of the default
            stack and user in the store will be skipped.
        **kwargs: Additional keyword arguments to pass to the Pydantic
            constructor.
    """
    super().__init__(**kwargs)

    self._initialize()

    if not skip_default_registrations:
        logger.debug("Initializing database")
        self._initialize_database()
    else:
        logger.debug("Skipping database initialization")
Attributes
server_info: ServerModel property

Get cached information about the server.

Returns:

Type Description
ServerModel

Cached information about the server.

session: requests.Session property

Initialize and return a requests session.

Returns:

Type Description
Session

A requests session.

Functions
authenticate(force: bool = False) -> None

Authenticate or re-authenticate to the ZenML server.

Parameters:

Name Type Description Default
force bool

If True, force a re-authentication even if a valid API token is currently cached. This is useful when the current API token is known to be invalid or expired.

False
Source code in src/zenml/zen_stores/rest_zen_store.py
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
def authenticate(self, force: bool = False) -> None:
    """Authenticate or re-authenticate to the ZenML server.

    Args:
        force: If True, force a re-authentication even if a valid API token
            is currently cached. This is useful when the current API token
            is known to be invalid or expired.
    """
    # This is called to trigger an authentication flow, either because
    # the current API token is expired or no longer valid, or because
    # a configuration change has happened or merely because an
    # authentication was never attempted before.
    #
    # 1. Drop the API token currently being used, if any.
    # 2. If force=True, clear the current API token from the credentials
    # store, if any, otherwise it will just be re-used on the next call.
    # 3. Get a new API token

    # The authentication token could have expired or invalidated through
    # other means; refresh it and try again. This will clear any cached
    # token and trigger a new authentication flow.
    if self._api_token and not force:
        if self._api_token.expired:
            logger.info(
                "Authentication session expired; attempting to "
                "re-authenticate."
            )
        else:
            logger.info(
                "Authentication session was invalidated by the server; "
                "This can happen for example if the user's permissions "
                "have been revoked or if the server has been restarted "
                "and lost its session state. Attempting to "
                "re-authenticate."
            )
    else:
        if force:
            # Clear the current API token from the credentials store, if
            # any, to force a new authentication flow.
            get_credentials_store().clear_token(self.url)
        # Never authenticated since the client was created or the API token
        # was explicitly cleared.
        logger.debug(f"Authenticating to {self.url}...")

    self._api_token = None

    new_api_token = self.get_or_generate_api_token()

    # Set or refresh the authentication token
    self.session.headers.update(
        {"Authorization": "Bearer " + new_api_token}
    )
    logger.debug(f"Authenticated to {self.url}")
backup_secrets(ignore_errors: bool = True, delete_secrets: bool = False) -> None

Backs up all secrets to the configured backup secrets store.

Parameters:

Name Type Description Default
ignore_errors bool

Whether to ignore individual errors during the backup process and attempt to backup all secrets.

True
delete_secrets bool

Whether to delete the secrets that have been successfully backed up from the primary secrets store. Setting this flag effectively moves all secrets from the primary secrets store to the backup secrets store.

False
Source code in src/zenml/zen_stores/rest_zen_store.py
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
def backup_secrets(
    self, ignore_errors: bool = True, delete_secrets: bool = False
) -> None:
    """Backs up all secrets to the configured backup secrets store.

    Args:
        ignore_errors: Whether to ignore individual errors during the backup
            process and attempt to backup all secrets.
        delete_secrets: Whether to delete the secrets that have been
            successfully backed up from the primary secrets store. Setting
            this flag effectively moves all secrets from the primary secrets
            store to the backup secrets store.
    """
    params: Dict[str, Any] = {
        "ignore_errors": ignore_errors,
        "delete_secrets": delete_secrets,
    }
    self.put(
        f"{SECRETS_OPERATIONS}{SECRETS_BACKUP}",
        params=params,
    )
batch_create_artifact_versions(artifact_versions: List[ArtifactVersionRequest]) -> List[ArtifactVersionResponse]

Creates a batch of artifact versions.

Parameters:

Name Type Description Default
artifact_versions List[ArtifactVersionRequest]

The artifact versions to create.

required

Returns:

Type Description
List[ArtifactVersionResponse]

The created artifact versions.

Source code in src/zenml/zen_stores/rest_zen_store.py
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
def batch_create_artifact_versions(
    self, artifact_versions: List[ArtifactVersionRequest]
) -> List[ArtifactVersionResponse]:
    """Creates a batch of artifact versions.

    Args:
        artifact_versions: The artifact versions to create.

    Returns:
        The created artifact versions.
    """
    return self._batch_create_resources(
        resources=artifact_versions,
        response_model=ArtifactVersionResponse,
        route=ARTIFACT_VERSIONS,
    )
batch_create_tag_resource(tag_resources: List[TagResourceRequest]) -> List[TagResourceResponse]

Create a batch of tag resource relationships.

Parameters:

Name Type Description Default
tag_resources List[TagResourceRequest]

The tag resource relationships to be created.

required

Returns:

Type Description
List[TagResourceResponse]

The newly created tag resource relationships.

Source code in src/zenml/zen_stores/rest_zen_store.py
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
def batch_create_tag_resource(
    self, tag_resources: List[TagResourceRequest]
) -> List[TagResourceResponse]:
    """Create a batch of tag resource relationships.

    Args:
        tag_resources: The tag resource relationships to be created.

    Returns:
        The newly created tag resource relationships.
    """
    return self._batch_create_resources(
        resources=tag_resources,
        response_model=TagResourceResponse,
        route=TAG_RESOURCES,
    )
batch_delete_tag_resource(tag_resources: List[TagResourceRequest]) -> None

Delete a batch of tag resources.

Parameters:

Name Type Description Default
tag_resources List[TagResourceRequest]

The tag resource relationships to be deleted.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
def batch_delete_tag_resource(
    self, tag_resources: List[TagResourceRequest]
) -> None:
    """Delete a batch of tag resources.

    Args:
        tag_resources: The tag resource relationships to be deleted.
    """
    self._batch_delete_resources(
        resources=tag_resources,
        route=TAG_RESOURCES,
    )
create_action(action: ActionRequest) -> ActionResponse

Create an action.

Parameters:

Name Type Description Default
action ActionRequest

The action to create.

required

Returns:

Type Description
ActionResponse

The created action.

Source code in src/zenml/zen_stores/rest_zen_store.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
def create_action(self, action: ActionRequest) -> ActionResponse:
    """Create an action.

    Args:
        action: The action to create.

    Returns:
        The created action.
    """
    return self._create_resource(
        resource=action,
        route=ACTIONS,
        response_model=ActionResponse,
    )
create_api_key(service_account_id: UUID, api_key: APIKeyRequest) -> APIKeyResponse

Create a new API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to create the API key.

required
api_key APIKeyRequest

The API key to create.

required

Returns:

Type Description
APIKeyResponse

The created API key.

Source code in src/zenml/zen_stores/rest_zen_store.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
def create_api_key(
    self, service_account_id: UUID, api_key: APIKeyRequest
) -> APIKeyResponse:
    """Create a new API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to
            create the API key.
        api_key: The API key to create.

    Returns:
        The created API key.
    """
    return self._create_resource(
        resource=api_key,
        route=f"{SERVICE_ACCOUNTS}/{str(service_account_id)}{API_KEYS}",
        response_model=APIKeyResponse,
    )
create_artifact(artifact: ArtifactRequest) -> ArtifactResponse

Creates a new artifact.

Parameters:

Name Type Description Default
artifact ArtifactRequest

The artifact to create.

required

Returns:

Type Description
ArtifactResponse

The newly created artifact.

Source code in src/zenml/zen_stores/rest_zen_store.py
893
894
895
896
897
898
899
900
901
902
903
904
905
906
def create_artifact(self, artifact: ArtifactRequest) -> ArtifactResponse:
    """Creates a new artifact.

    Args:
        artifact: The artifact to create.

    Returns:
        The newly created artifact.
    """
    return self._create_resource(
        resource=artifact,
        response_model=ArtifactResponse,
        route=ARTIFACTS,
    )
create_artifact_version(artifact_version: ArtifactVersionRequest) -> ArtifactVersionResponse

Creates an artifact version.

Parameters:

Name Type Description Default
artifact_version ArtifactVersionRequest

The artifact version to create.

required

Returns:

Type Description
ArtifactVersionResponse

The created artifact version.

Source code in src/zenml/zen_stores/rest_zen_store.py
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def create_artifact_version(
    self, artifact_version: ArtifactVersionRequest
) -> ArtifactVersionResponse:
    """Creates an artifact version.

    Args:
        artifact_version: The artifact version to create.

    Returns:
        The created artifact version.
    """
    return self._create_resource(
        resource=artifact_version,
        response_model=ArtifactVersionResponse,
        route=ARTIFACT_VERSIONS,
    )
create_build(build: PipelineBuildRequest) -> PipelineBuildResponse

Creates a new build.

Parameters:

Name Type Description Default
build PipelineBuildRequest

The build to create.

required

Returns:

Type Description
PipelineBuildResponse

The newly created build.

Source code in src/zenml/zen_stores/rest_zen_store.py
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
def create_build(
    self,
    build: PipelineBuildRequest,
) -> PipelineBuildResponse:
    """Creates a new build.

    Args:
        build: The build to create.

    Returns:
        The newly created build.
    """
    return self._create_resource(
        resource=build,
        route=PIPELINE_BUILDS,
        response_model=PipelineBuildResponse,
    )
create_code_repository(code_repository: CodeRepositoryRequest) -> CodeRepositoryResponse

Creates a new code repository.

Parameters:

Name Type Description Default
code_repository CodeRepositoryRequest

Code repository to be created.

required

Returns:

Type Description
CodeRepositoryResponse

The newly created code repository.

Source code in src/zenml/zen_stores/rest_zen_store.py
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
def create_code_repository(
    self, code_repository: CodeRepositoryRequest
) -> CodeRepositoryResponse:
    """Creates a new code repository.

    Args:
        code_repository: Code repository to be created.

    Returns:
        The newly created code repository.
    """
    return self._create_resource(
        resource=code_repository,
        response_model=CodeRepositoryResponse,
        route=CODE_REPOSITORIES,
    )
create_deployment(deployment: PipelineDeploymentRequest) -> PipelineDeploymentResponse

Creates a new deployment.

Parameters:

Name Type Description Default
deployment PipelineDeploymentRequest

The deployment to create.

required

Returns:

Type Description
PipelineDeploymentResponse

The newly created deployment.

Source code in src/zenml/zen_stores/rest_zen_store.py
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
def create_deployment(
    self,
    deployment: PipelineDeploymentRequest,
) -> PipelineDeploymentResponse:
    """Creates a new deployment.

    Args:
        deployment: The deployment to create.

    Returns:
        The newly created deployment.
    """
    return self._create_resource(
        resource=deployment,
        route=PIPELINE_DEPLOYMENTS,
        response_model=PipelineDeploymentResponse,
    )
create_event_source(event_source: EventSourceRequest) -> EventSourceResponse

Create an event_source.

Parameters:

Name Type Description Default
event_source EventSourceRequest

The event_source to create.

required

Returns:

Type Description
EventSourceResponse

The created event_source.

Source code in src/zenml/zen_stores/rest_zen_store.py
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
def create_event_source(
    self, event_source: EventSourceRequest
) -> EventSourceResponse:
    """Create an event_source.

    Args:
        event_source: The event_source to create.

    Returns:
        The created event_source.
    """
    return self._create_resource(
        resource=event_source,
        route=EVENT_SOURCES,
        response_model=EventSourceResponse,
    )
create_flavor(flavor: FlavorRequest) -> FlavorResponse

Creates a new stack component flavor.

Parameters:

Name Type Description Default
flavor FlavorRequest

The stack component flavor to create.

required

Returns:

Type Description
FlavorResponse

The newly created flavor.

Source code in src/zenml/zen_stores/rest_zen_store.py
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
def create_flavor(self, flavor: FlavorRequest) -> FlavorResponse:
    """Creates a new stack component flavor.

    Args:
        flavor: The stack component flavor to create.

    Returns:
        The newly created flavor.
    """
    return self._create_resource(
        resource=flavor,
        route=FLAVORS,
        response_model=FlavorResponse,
    )
create_model(model: ModelRequest) -> ModelResponse

Creates a new model.

Parameters:

Name Type Description Default
model ModelRequest

the Model to be created.

required

Returns:

Type Description
ModelResponse

The newly created model.

Source code in src/zenml/zen_stores/rest_zen_store.py
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
def create_model(self, model: ModelRequest) -> ModelResponse:
    """Creates a new model.

    Args:
        model: the Model to be created.

    Returns:
        The newly created model.
    """
    return self._create_resource(
        resource=model,
        response_model=ModelResponse,
        route=MODELS,
    )
create_model_version(model_version: ModelVersionRequest) -> ModelVersionResponse

Creates a new model version.

Parameters:

Name Type Description Default
model_version ModelVersionRequest

the Model Version to be created.

required

Returns:

Type Description
ModelVersionResponse

The newly created model version.

Source code in src/zenml/zen_stores/rest_zen_store.py
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
def create_model_version(
    self, model_version: ModelVersionRequest
) -> ModelVersionResponse:
    """Creates a new model version.

    Args:
        model_version: the Model Version to be created.

    Returns:
        The newly created model version.
    """
    return self._create_resource(
        resource=model_version,
        response_model=ModelVersionResponse,
        route=MODEL_VERSIONS,
    )
create_model_version_artifact_link(model_version_artifact_link: ModelVersionArtifactRequest) -> ModelVersionArtifactResponse

Creates a new model version link.

Parameters:

Name Type Description Default
model_version_artifact_link ModelVersionArtifactRequest

the Model Version to Artifact Link to be created.

required

Returns:

Type Description
ModelVersionArtifactResponse

The newly created model version to artifact link.

Source code in src/zenml/zen_stores/rest_zen_store.py
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
def create_model_version_artifact_link(
    self, model_version_artifact_link: ModelVersionArtifactRequest
) -> ModelVersionArtifactResponse:
    """Creates a new model version link.

    Args:
        model_version_artifact_link: the Model Version to Artifact Link
            to be created.

    Returns:
        The newly created model version to artifact link.
    """
    return self._create_resource(
        resource=model_version_artifact_link,
        response_model=ModelVersionArtifactResponse,
        route=MODEL_VERSION_ARTIFACTS,
    )
create_model_version_pipeline_run_link(model_version_pipeline_run_link: ModelVersionPipelineRunRequest) -> ModelVersionPipelineRunResponse

Creates a new model version to pipeline run link.

Parameters:

Name Type Description Default
model_version_pipeline_run_link ModelVersionPipelineRunRequest

the Model Version to Pipeline Run Link to be created.

required

Returns:

Type Description
ModelVersionPipelineRunResponse
  • If Model Version to Pipeline Run Link already exists - returns the existing link.
ModelVersionPipelineRunResponse
  • Otherwise, returns the newly created model version to pipeline run link.
Source code in src/zenml/zen_stores/rest_zen_store.py
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
def create_model_version_pipeline_run_link(
    self,
    model_version_pipeline_run_link: ModelVersionPipelineRunRequest,
) -> ModelVersionPipelineRunResponse:
    """Creates a new model version to pipeline run link.

    Args:
        model_version_pipeline_run_link: the Model Version to Pipeline Run
            Link to be created.

    Returns:
        - If Model Version to Pipeline Run Link already exists - returns
            the existing link.
        - Otherwise, returns the newly created model version to pipeline
            run link.
    """
    return self._create_resource(
        resource=model_version_pipeline_run_link,
        response_model=ModelVersionPipelineRunResponse,
        route=MODEL_VERSION_PIPELINE_RUNS,
    )
create_pipeline(pipeline: PipelineRequest) -> PipelineResponse

Creates a new pipeline.

Parameters:

Name Type Description Default
pipeline PipelineRequest

The pipeline to create.

required

Returns:

Type Description
PipelineResponse

The newly created pipeline.

Source code in src/zenml/zen_stores/rest_zen_store.py
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
def create_pipeline(self, pipeline: PipelineRequest) -> PipelineResponse:
    """Creates a new pipeline.

    Args:
        pipeline: The pipeline to create.

    Returns:
        The newly created pipeline.
    """
    return self._create_resource(
        resource=pipeline,
        route=PIPELINES,
        response_model=PipelineResponse,
    )
create_project(project: ProjectRequest) -> ProjectResponse

Creates a new project.

Parameters:

Name Type Description Default
project ProjectRequest

The project to create.

required

Returns:

Type Description
ProjectResponse

The newly created project.

Source code in src/zenml/zen_stores/rest_zen_store.py
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
def create_project(self, project: ProjectRequest) -> ProjectResponse:
    """Creates a new project.

    Args:
        project: The project to create.

    Returns:
        The newly created project.
    """
    return self._create_resource(
        resource=project,
        route=PROJECTS,
        response_model=ProjectResponse,
    )
create_run_metadata(run_metadata: RunMetadataRequest) -> None

Creates run metadata.

Parameters:

Name Type Description Default
run_metadata RunMetadataRequest

The run metadata to create.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
2007
2008
2009
2010
2011
2012
2013
def create_run_metadata(self, run_metadata: RunMetadataRequest) -> None:
    """Creates run metadata.

    Args:
        run_metadata: The run metadata to create.
    """
    self.post(RUN_METADATA, body=run_metadata)
create_run_step(step_run: StepRunRequest) -> StepRunResponse

Creates a step run.

Parameters:

Name Type Description Default
step_run StepRunRequest

The step run to create.

required

Returns:

Type Description
StepRunResponse

The created step run.

Source code in src/zenml/zen_stores/rest_zen_store.py
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
def create_run_step(self, step_run: StepRunRequest) -> StepRunResponse:
    """Creates a step run.

    Args:
        step_run: The step run to create.

    Returns:
        The created step run.
    """
    return self._create_resource(
        resource=step_run,
        response_model=StepRunResponse,
        route=STEPS,
    )
create_run_template(template: RunTemplateRequest) -> RunTemplateResponse

Create a new run template.

Parameters:

Name Type Description Default
template RunTemplateRequest

The template to create.

required

Returns:

Type Description
RunTemplateResponse

The newly created template.

Source code in src/zenml/zen_stores/rest_zen_store.py
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
def create_run_template(
    self,
    template: RunTemplateRequest,
) -> RunTemplateResponse:
    """Create a new run template.

    Args:
        template: The template to create.

    Returns:
        The newly created template.
    """
    return self._create_resource(
        resource=template,
        route=RUN_TEMPLATES,
        response_model=RunTemplateResponse,
    )
create_schedule(schedule: ScheduleRequest) -> ScheduleResponse

Creates a new schedule.

Parameters:

Name Type Description Default
schedule ScheduleRequest

The schedule to create.

required

Returns:

Type Description
ScheduleResponse

The newly created schedule.

Source code in src/zenml/zen_stores/rest_zen_store.py
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
def create_schedule(self, schedule: ScheduleRequest) -> ScheduleResponse:
    """Creates a new schedule.

    Args:
        schedule: The schedule to create.

    Returns:
        The newly created schedule.
    """
    return self._create_resource(
        resource=schedule,
        route=SCHEDULES,
        response_model=ScheduleResponse,
    )
create_secret(secret: SecretRequest) -> SecretResponse

Creates a new secret.

The new secret is also validated against the scoping rules enforced in the secrets store:

  • only one private secret with the given name can exist.
  • only one public secret with the given name can exist.

Parameters:

Name Type Description Default
secret SecretRequest

The secret to create.

required

Returns:

Type Description
SecretResponse

The newly created secret.

Source code in src/zenml/zen_stores/rest_zen_store.py
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
def create_secret(self, secret: SecretRequest) -> SecretResponse:
    """Creates a new secret.

    The new secret is also validated against the scoping rules enforced in
    the secrets store:

      - only one private secret with the given name can exist.
      - only one public secret with the given name can exist.

    Args:
        secret: The secret to create.

    Returns:
        The newly created secret.
    """
    return self._create_resource(
        resource=secret,
        route=SECRETS,
        response_model=SecretResponse,
    )
create_service(service_request: ServiceRequest) -> ServiceResponse

Create a new service.

Parameters:

Name Type Description Default
service_request ServiceRequest

The service to create.

required

Returns:

Type Description
ServiceResponse

The created service.

Source code in src/zenml/zen_stores/rest_zen_store.py
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
def create_service(
    self, service_request: ServiceRequest
) -> ServiceResponse:
    """Create a new service.

    Args:
        service_request: The service to create.

    Returns:
        The created service.
    """
    return self._create_resource(
        resource=service_request,
        response_model=ServiceResponse,
        route=SERVICES,
    )
create_service_account(service_account: ServiceAccountRequest) -> ServiceAccountResponse

Creates a new service account.

Parameters:

Name Type Description Default
service_account ServiceAccountRequest

Service account to be created.

required

Returns:

Type Description
ServiceAccountResponse

The newly created service account.

Source code in src/zenml/zen_stores/rest_zen_store.py
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
def create_service_account(
    self, service_account: ServiceAccountRequest
) -> ServiceAccountResponse:
    """Creates a new service account.

    Args:
        service_account: Service account to be created.

    Returns:
        The newly created service account.
    """
    return self._create_resource(
        resource=service_account,
        route=SERVICE_ACCOUNTS,
        response_model=ServiceAccountResponse,
    )
create_service_connector(service_connector: ServiceConnectorRequest) -> ServiceConnectorResponse

Creates a new service connector.

Parameters:

Name Type Description Default
service_connector ServiceConnectorRequest

Service connector to be created.

required

Returns:

Type Description
ServiceConnectorResponse

The newly created service connector.

Source code in src/zenml/zen_stores/rest_zen_store.py
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
def create_service_connector(
    self, service_connector: ServiceConnectorRequest
) -> ServiceConnectorResponse:
    """Creates a new service connector.

    Args:
        service_connector: Service connector to be created.

    Returns:
        The newly created service connector.
    """
    connector_model = self._create_resource(
        resource=service_connector,
        route=SERVICE_CONNECTORS,
        response_model=ServiceConnectorResponse,
    )
    self._populate_connector_type(connector_model)
    return connector_model
create_stack(stack: StackRequest) -> StackResponse

Register a new stack.

Parameters:

Name Type Description Default
stack StackRequest

The stack to register.

required

Returns:

Type Description
StackResponse

The registered stack.

Source code in src/zenml/zen_stores/rest_zen_store.py
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
def create_stack(self, stack: StackRequest) -> StackResponse:
    """Register a new stack.

    Args:
        stack: The stack to register.

    Returns:
        The registered stack.
    """
    return self._create_resource(
        resource=stack,
        response_model=StackResponse,
        route=STACKS,
    )
create_stack_component(component: ComponentRequest) -> ComponentResponse

Create a stack component.

Parameters:

Name Type Description Default
component ComponentRequest

The stack component to create.

required

Returns:

Type Description
ComponentResponse

The created stack component.

Source code in src/zenml/zen_stores/rest_zen_store.py
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
def create_stack_component(
    self,
    component: ComponentRequest,
) -> ComponentResponse:
    """Create a stack component.

    Args:
        component: The stack component to create.

    Returns:
        The created stack component.
    """
    return self._create_resource(
        resource=component,
        route=STACK_COMPONENTS,
        response_model=ComponentResponse,
    )
create_tag(tag: TagRequest) -> TagResponse

Creates a new tag.

Parameters:

Name Type Description Default
tag TagRequest

the tag to be created.

required

Returns:

Type Description
TagResponse

The newly created tag.

Source code in src/zenml/zen_stores/rest_zen_store.py
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
def create_tag(self, tag: TagRequest) -> TagResponse:
    """Creates a new tag.

    Args:
        tag: the tag to be created.

    Returns:
        The newly created tag.
    """
    return self._create_resource(
        resource=tag,
        response_model=TagResponse,
        route=TAGS,
    )
create_tag_resource(tag_resource: TagResourceRequest) -> TagResourceResponse

Create a new tag resource.

Parameters:

Name Type Description Default
tag_resource TagResourceRequest

The tag resource to be created.

required

Returns:

Type Description
TagResourceResponse

The newly created tag resource.

Source code in src/zenml/zen_stores/rest_zen_store.py
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
def create_tag_resource(
    self,
    tag_resource: TagResourceRequest,
) -> TagResourceResponse:
    """Create a new tag resource.

    Args:
        tag_resource: The tag resource to be created.

    Returns:
        The newly created tag resource.
    """
    return self._create_resource(
        resource=tag_resource,
        response_model=TagResourceResponse,
        route=TAG_RESOURCES,
    )
create_trigger(trigger: TriggerRequest) -> TriggerResponse

Create an trigger.

Parameters:

Name Type Description Default
trigger TriggerRequest

The trigger to create.

required

Returns:

Type Description
TriggerResponse

The created trigger.

Source code in src/zenml/zen_stores/rest_zen_store.py
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
def create_trigger(self, trigger: TriggerRequest) -> TriggerResponse:
    """Create an trigger.

    Args:
        trigger: The trigger to create.

    Returns:
        The created trigger.
    """
    return self._create_resource(
        resource=trigger,
        route=TRIGGERS,
        response_model=TriggerResponse,
    )
create_user(user: UserRequest) -> UserResponse

Creates a new user.

Parameters:

Name Type Description Default
user UserRequest

User to be created.

required

Returns:

Type Description
UserResponse

The newly created user.

Source code in src/zenml/zen_stores/rest_zen_store.py
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
def create_user(self, user: UserRequest) -> UserResponse:
    """Creates a new user.

    Args:
        user: User to be created.

    Returns:
        The newly created user.
    """
    return self._create_resource(
        resource=user,
        route=USERS,
        response_model=UserResponse,
    )
deactivate_user(user_name_or_id: Union[str, UUID]) -> UserResponse

Deactivates a user.

Parameters:

Name Type Description Default
user_name_or_id Union[str, UUID]

The name or ID of the user to delete.

required

Returns:

Type Description
UserResponse

The deactivated user containing the activation token.

Source code in src/zenml/zen_stores/rest_zen_store.py
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
def deactivate_user(
    self, user_name_or_id: Union[str, UUID]
) -> UserResponse:
    """Deactivates a user.

    Args:
        user_name_or_id: The name or ID of the user to delete.

    Returns:
        The deactivated user containing the activation token.
    """
    response_body = self.put(
        f"{USERS}/{str(user_name_or_id)}{DEACTIVATE}",
    )

    return UserResponse.model_validate(response_body)
delete(path: str, body: Optional[BaseModel] = None, params: Optional[Dict[str, Any]] = None, timeout: Optional[int] = None, **kwargs: Any) -> Json

Make a DELETE request to the given endpoint path.

Parameters:

Name Type Description Default
path str

The path to the endpoint.

required
body Optional[BaseModel]

The body to send.

None
params Optional[Dict[str, Any]]

The query parameters to pass to the endpoint.

None
timeout Optional[int]

The request timeout in seconds.

None
kwargs Any

Additional keyword arguments to pass to the request.

{}

Returns:

Type Description
Json

The response body.

Source code in src/zenml/zen_stores/rest_zen_store.py
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
def delete(
    self,
    path: str,
    body: Optional[BaseModel] = None,
    params: Optional[Dict[str, Any]] = None,
    timeout: Optional[int] = None,
    **kwargs: Any,
) -> Json:
    """Make a DELETE request to the given endpoint path.

    Args:
        path: The path to the endpoint.
        body: The body to send.
        params: The query parameters to pass to the endpoint.
        timeout: The request timeout in seconds.
        kwargs: Additional keyword arguments to pass to the request.

    Returns:
        The response body.
    """
    logger.debug(f"Sending DELETE request to {path}...")
    return self._request(
        "DELETE",
        self.url + API + VERSION_1 + path,
        json=body.model_dump(mode="json") if body else None,
        params=params,
        timeout=timeout,
        **kwargs,
    )
delete_action(action_id: UUID) -> None

Delete an action.

Parameters:

Name Type Description Default
action_id UUID

The ID of the action to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
657
658
659
660
661
662
663
664
665
666
def delete_action(self, action_id: UUID) -> None:
    """Delete an action.

    Args:
        action_id: The ID of the action to delete.
    """
    self._delete_resource(
        resource_id=action_id,
        route=ACTIONS,
    )
delete_all_model_version_artifact_links(model_version_id: UUID, only_links: bool = True) -> None

Deletes all links between model version and an artifact.

Parameters:

Name Type Description Default
model_version_id UUID

ID of the model version containing the link.

required
only_links bool

Flag deciding whether to delete only links or all.

True
Source code in src/zenml/zen_stores/rest_zen_store.py
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
def delete_all_model_version_artifact_links(
    self,
    model_version_id: UUID,
    only_links: bool = True,
) -> None:
    """Deletes all links between model version and an artifact.

    Args:
        model_version_id: ID of the model version containing the link.
        only_links: Flag deciding whether to delete only links or all.
    """
    self.delete(
        f"{MODEL_VERSIONS}/{model_version_id}{ARTIFACTS}",
        params={"only_links": only_links},
    )
delete_api_key(service_account_id: UUID, api_key_name_or_id: Union[str, UUID]) -> None

Delete an API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to delete the API key.

required
api_key_name_or_id Union[str, UUID]

The name or ID of the API key to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
def delete_api_key(
    self,
    service_account_id: UUID,
    api_key_name_or_id: Union[str, UUID],
) -> None:
    """Delete an API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to
            delete the API key.
        api_key_name_or_id: The name or ID of the API key to delete.
    """
    self._delete_resource(
        resource_id=api_key_name_or_id,
        route=f"{SERVICE_ACCOUNTS}/{str(service_account_id)}{API_KEYS}",
    )
delete_artifact(artifact_id: UUID) -> None

Deletes an artifact.

Parameters:

Name Type Description Default
artifact_id UUID

The ID of the artifact to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
968
969
970
971
972
973
974
def delete_artifact(self, artifact_id: UUID) -> None:
    """Deletes an artifact.

    Args:
        artifact_id: The ID of the artifact to delete.
    """
    self._delete_resource(resource_id=artifact_id, route=ARTIFACTS)
delete_artifact_version(artifact_version_id: UUID) -> None

Deletes an artifact version.

Parameters:

Name Type Description Default
artifact_version_id UUID

The ID of the artifact version to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
1077
1078
1079
1080
1081
1082
1083
1084
1085
def delete_artifact_version(self, artifact_version_id: UUID) -> None:
    """Deletes an artifact version.

    Args:
        artifact_version_id: The ID of the artifact version to delete.
    """
    self._delete_resource(
        resource_id=artifact_version_id, route=ARTIFACT_VERSIONS
    )
delete_authorized_device(device_id: UUID) -> None

Deletes an OAuth 2.0 authorized device.

Parameters:

Name Type Description Default
device_id UUID

The ID of the device to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
3815
3816
3817
3818
3819
3820
3821
def delete_authorized_device(self, device_id: UUID) -> None:
    """Deletes an OAuth 2.0 authorized device.

    Args:
        device_id: The ID of the device to delete.
    """
    self._delete_resource(resource_id=device_id, route=DEVICES)
delete_build(build_id: UUID) -> None

Deletes a build.

Parameters:

Name Type Description Default
build_id UUID

The ID of the build to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
def delete_build(self, build_id: UUID) -> None:
    """Deletes a build.

    Args:
        build_id: The ID of the build to delete.
    """
    self._delete_resource(
        resource_id=build_id,
        route=PIPELINE_BUILDS,
    )
delete_code_repository(code_repository_id: UUID) -> None

Deletes a code repository.

Parameters:

Name Type Description Default
code_repository_id UUID

The ID of the code repository to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
1233
1234
1235
1236
1237
1238
1239
1240
1241
def delete_code_repository(self, code_repository_id: UUID) -> None:
    """Deletes a code repository.

    Args:
        code_repository_id: The ID of the code repository to delete.
    """
    self._delete_resource(
        resource_id=code_repository_id, route=CODE_REPOSITORIES
    )
delete_deployment(deployment_id: UUID) -> None

Deletes a deployment.

Parameters:

Name Type Description Default
deployment_id UUID

The ID of the deployment to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
def delete_deployment(self, deployment_id: UUID) -> None:
    """Deletes a deployment.

    Args:
        deployment_id: The ID of the deployment to delete.
    """
    self._delete_resource(
        resource_id=deployment_id,
        route=PIPELINE_DEPLOYMENTS,
    )
delete_event_source(event_source_id: UUID) -> None

Delete an event_source.

Parameters:

Name Type Description Default
event_source_id UUID

The ID of the event_source to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
def delete_event_source(self, event_source_id: UUID) -> None:
    """Delete an event_source.

    Args:
        event_source_id: The ID of the event_source to delete.
    """
    self._delete_resource(
        resource_id=event_source_id,
        route=EVENT_SOURCES,
    )
delete_flavor(flavor_id: UUID) -> None

Delete a stack component flavor.

Parameters:

Name Type Description Default
flavor_id UUID

The ID of the stack component flavor to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
def delete_flavor(self, flavor_id: UUID) -> None:
    """Delete a stack component flavor.

    Args:
        flavor_id: The ID of the stack component flavor to delete.
    """
    self._delete_resource(
        resource_id=flavor_id,
        route=FLAVORS,
    )
delete_model(model_id: UUID) -> None

Deletes a model.

Parameters:

Name Type Description Default
model_id UUID

id of the model to be deleted.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
3445
3446
3447
3448
3449
3450
3451
def delete_model(self, model_id: UUID) -> None:
    """Deletes a model.

    Args:
        model_id: id of the model to be deleted.
    """
    self._delete_resource(resource_id=model_id, route=MODELS)
delete_model_version(model_version_id: UUID) -> None

Deletes a model version.

Parameters:

Name Type Description Default
model_version_id UUID

name or id of the model version to be deleted.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
def delete_model_version(
    self,
    model_version_id: UUID,
) -> None:
    """Deletes a model version.

    Args:
        model_version_id: name or id of the model version to be deleted.
    """
    self._delete_resource(
        resource_id=model_version_id,
        route=MODEL_VERSIONS,
    )
delete_model_version_artifact_link(model_version_id: UUID, model_version_artifact_link_name_or_id: Union[str, UUID]) -> None

Deletes a model version to artifact link.

Parameters:

Name Type Description Default
model_version_id UUID

ID of the model version containing the link.

required
model_version_artifact_link_name_or_id Union[str, UUID]

name or ID of the model version to artifact link to be deleted.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
def delete_model_version_artifact_link(
    self,
    model_version_id: UUID,
    model_version_artifact_link_name_or_id: Union[str, UUID],
) -> None:
    """Deletes a model version to artifact link.

    Args:
        model_version_id: ID of the model version containing the link.
        model_version_artifact_link_name_or_id: name or ID of the model
            version to artifact link to be deleted.
    """
    self._delete_resource(
        resource_id=model_version_artifact_link_name_or_id,
        route=f"{MODEL_VERSIONS}/{model_version_id}{ARTIFACTS}",
    )
delete_model_version_pipeline_run_link(model_version_id: UUID, model_version_pipeline_run_link_name_or_id: Union[str, UUID]) -> None

Deletes a model version to pipeline run link.

Parameters:

Name Type Description Default
model_version_id UUID

ID of the model version containing the link.

required
model_version_pipeline_run_link_name_or_id Union[str, UUID]

name or ID of the model version to pipeline run link to be deleted.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
def delete_model_version_pipeline_run_link(
    self,
    model_version_id: UUID,
    model_version_pipeline_run_link_name_or_id: Union[str, UUID],
) -> None:
    """Deletes a model version to pipeline run link.

    Args:
        model_version_id: ID of the model version containing the link.
        model_version_pipeline_run_link_name_or_id: name or ID of the model version to pipeline run link to be deleted.
    """
    self._delete_resource(
        resource_id=model_version_pipeline_run_link_name_or_id,
        route=f"{MODEL_VERSIONS}/{model_version_id}{RUNS}",
    )
delete_pipeline(pipeline_id: UUID) -> None

Deletes a pipeline.

Parameters:

Name Type Description Default
pipeline_id UUID

The ID of the pipeline to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
def delete_pipeline(self, pipeline_id: UUID) -> None:
    """Deletes a pipeline.

    Args:
        pipeline_id: The ID of the pipeline to delete.
    """
    self._delete_resource(
        resource_id=pipeline_id,
        route=PIPELINES,
    )
delete_project(project_name_or_id: Union[str, UUID]) -> None

Deletes a project.

Parameters:

Name Type Description Default
project_name_or_id Union[str, UUID]

Name or ID of the project to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
def delete_project(self, project_name_or_id: Union[str, UUID]) -> None:
    """Deletes a project.

    Args:
        project_name_or_id: Name or ID of the project to delete.
    """
    self._delete_resource(
        resource_id=project_name_or_id,
        route=PROJECTS,
    )
delete_run(run_id: UUID) -> None

Deletes a pipeline run.

Parameters:

Name Type Description Default
run_id UUID

The ID of the pipeline run to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
def delete_run(self, run_id: UUID) -> None:
    """Deletes a pipeline run.

    Args:
        run_id: The ID of the pipeline run to delete.
    """
    self._delete_resource(
        resource_id=run_id,
        route=RUNS,
    )
delete_run_template(template_id: UUID) -> None

Delete a run template.

Parameters:

Name Type Description Default
template_id UUID

The ID of the template to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
def delete_run_template(self, template_id: UUID) -> None:
    """Delete a run template.

    Args:
        template_id: The ID of the template to delete.
    """
    self._delete_resource(
        resource_id=template_id,
        route=RUN_TEMPLATES,
    )
delete_schedule(schedule_id: UUID) -> None

Deletes a schedule.

Parameters:

Name Type Description Default
schedule_id UUID

The ID of the schedule to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
def delete_schedule(self, schedule_id: UUID) -> None:
    """Deletes a schedule.

    Args:
        schedule_id: The ID of the schedule to delete.
    """
    self._delete_resource(
        resource_id=schedule_id,
        route=SCHEDULES,
    )
delete_secret(secret_id: UUID) -> None

Delete a secret.

Parameters:

Name Type Description Default
secret_id UUID

The id of the secret to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
def delete_secret(self, secret_id: UUID) -> None:
    """Delete a secret.

    Args:
        secret_id: The id of the secret to delete.
    """
    self._delete_resource(
        resource_id=secret_id,
        route=SECRETS,
    )
delete_service(service_id: UUID) -> None

Delete a service.

Parameters:

Name Type Description Default
service_id UUID

The ID of the service to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
883
884
885
886
887
888
889
def delete_service(self, service_id: UUID) -> None:
    """Delete a service.

    Args:
        service_id: The ID of the service to delete.
    """
    self._delete_resource(resource_id=service_id, route=SERVICES)
delete_service_account(service_account_name_or_id: Union[str, UUID]) -> None

Delete a service account.

Parameters:

Name Type Description Default
service_account_name_or_id Union[str, UUID]

The name or the ID of the service account to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
def delete_service_account(
    self,
    service_account_name_or_id: Union[str, UUID],
) -> None:
    """Delete a service account.

    Args:
        service_account_name_or_id: The name or the ID of the service
            account to delete.
    """
    self._delete_resource(
        resource_id=service_account_name_or_id,
        route=SERVICE_ACCOUNTS,
    )
delete_service_connector(service_connector_id: UUID) -> None

Deletes a service connector.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the service connector to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
2475
2476
2477
2478
2479
2480
2481
2482
2483
def delete_service_connector(self, service_connector_id: UUID) -> None:
    """Deletes a service connector.

    Args:
        service_connector_id: The ID of the service connector to delete.
    """
    self._delete_resource(
        resource_id=service_connector_id, route=SERVICE_CONNECTORS
    )
delete_stack(stack_id: UUID) -> None

Delete a stack.

Parameters:

Name Type Description Default
stack_id UUID

The ID of the stack to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
def delete_stack(self, stack_id: UUID) -> None:
    """Delete a stack.

    Args:
        stack_id: The ID of the stack to delete.
    """
    self._delete_resource(
        resource_id=stack_id,
        route=STACKS,
    )
delete_stack_component(component_id: UUID) -> None

Delete a stack component.

Parameters:

Name Type Description Default
component_id UUID

The ID of the stack component to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
def delete_stack_component(self, component_id: UUID) -> None:
    """Delete a stack component.

    Args:
        component_id: The ID of the stack component to delete.
    """
    self._delete_resource(
        resource_id=component_id,
        route=STACK_COMPONENTS,
    )
delete_tag(tag_name_or_id: Union[str, UUID]) -> None

Deletes a tag.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

name or id of the tag to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
def delete_tag(
    self,
    tag_name_or_id: Union[str, UUID],
) -> None:
    """Deletes a tag.

    Args:
        tag_name_or_id: name or id of the tag to delete.
    """
    self._delete_resource(
        resource_id=tag_name_or_id,
        route=TAGS,
    )
delete_tag_resource(tag_resource: TagResourceRequest) -> None

Delete a tag resource.

Parameters:

Name Type Description Default
tag_resource TagResourceRequest

The tag resource relationship to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
def delete_tag_resource(
    self,
    tag_resource: TagResourceRequest,
) -> None:
    """Delete a tag resource.

    Args:
        tag_resource: The tag resource relationship to delete.
    """
    self.delete(path=TAG_RESOURCES, body=tag_resource)
delete_trigger(trigger_id: UUID) -> None

Delete an trigger.

Parameters:

Name Type Description Default
trigger_id UUID

The ID of the trigger to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
def delete_trigger(self, trigger_id: UUID) -> None:
    """Delete an trigger.

    Args:
        trigger_id: The ID of the trigger to delete.
    """
    self._delete_resource(
        resource_id=trigger_id,
        route=TRIGGERS,
    )
delete_trigger_execution(trigger_execution_id: UUID) -> None

Delete a trigger execution.

Parameters:

Name Type Description Default
trigger_execution_id UUID

The ID of the trigger execution to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
def delete_trigger_execution(self, trigger_execution_id: UUID) -> None:
    """Delete a trigger execution.

    Args:
        trigger_execution_id: The ID of the trigger execution to delete.
    """
    self._delete_resource(
        resource_id=trigger_execution_id,
        route=TRIGGER_EXECUTIONS,
    )
delete_user(user_name_or_id: Union[str, UUID]) -> None

Deletes a user.

Parameters:

Name Type Description Default
user_name_or_id Union[str, UUID]

The name or ID of the user to delete.

required
Source code in src/zenml/zen_stores/rest_zen_store.py
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
def delete_user(self, user_name_or_id: Union[str, UUID]) -> None:
    """Deletes a user.

    Args:
        user_name_or_id: The name or ID of the user to delete.
    """
    self._delete_resource(
        resource_id=user_name_or_id,
        route=USERS,
    )
get(path: str, params: Optional[Dict[str, Any]] = None, timeout: Optional[int] = None, **kwargs: Any) -> Json

Make a GET request to the given endpoint path.

Parameters:

Name Type Description Default
path str

The path to the endpoint.

required
params Optional[Dict[str, Any]]

The query parameters to pass to the endpoint.

None
timeout Optional[int]

The request timeout in seconds.

None
kwargs Any

Additional keyword arguments to pass to the request.

{}

Returns:

Type Description
Json

The response body.

Source code in src/zenml/zen_stores/rest_zen_store.py
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
def get(
    self,
    path: str,
    params: Optional[Dict[str, Any]] = None,
    timeout: Optional[int] = None,
    **kwargs: Any,
) -> Json:
    """Make a GET request to the given endpoint path.

    Args:
        path: The path to the endpoint.
        params: The query parameters to pass to the endpoint.
        timeout: The request timeout in seconds.
        kwargs: Additional keyword arguments to pass to the request.

    Returns:
        The response body.
    """
    logger.debug(f"Sending GET request to {path}...")
    return self._request(
        "GET",
        self.url + API + VERSION_1 + path,
        params=params,
        timeout=timeout,
        **kwargs,
    )
get_action(action_id: UUID, hydrate: bool = True) -> ActionResponse

Get an action by ID.

Parameters:

Name Type Description Default
action_id UUID

The ID of the action to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ActionResponse

The action.

Source code in src/zenml/zen_stores/rest_zen_store.py
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def get_action(
    self,
    action_id: UUID,
    hydrate: bool = True,
) -> ActionResponse:
    """Get an action by ID.

    Args:
        action_id: The ID of the action to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The action.
    """
    return self._get_resource(
        resource_id=action_id,
        route=ACTIONS,
        response_model=ActionResponse,
        params={"hydrate": hydrate},
    )
get_api_key(service_account_id: UUID, api_key_name_or_id: Union[str, UUID], hydrate: bool = True) -> APIKeyResponse

Get an API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to fetch the API key.

required
api_key_name_or_id Union[str, UUID]

The name or ID of the API key to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
APIKeyResponse

The API key with the given ID.

Source code in src/zenml/zen_stores/rest_zen_store.py
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
def get_api_key(
    self,
    service_account_id: UUID,
    api_key_name_or_id: Union[str, UUID],
    hydrate: bool = True,
) -> APIKeyResponse:
    """Get an API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to fetch
            the API key.
        api_key_name_or_id: The name or ID of the API key to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The API key with the given ID.
    """
    return self._get_resource(
        resource_id=api_key_name_or_id,
        route=f"{SERVICE_ACCOUNTS}/{str(service_account_id)}{API_KEYS}",
        response_model=APIKeyResponse,
        params={"hydrate": hydrate},
    )
get_api_token(token_type: APITokenType = APITokenType.WORKLOAD, expires_in: Optional[int] = None, schedule_id: Optional[UUID] = None, pipeline_run_id: Optional[UUID] = None, step_run_id: Optional[UUID] = None) -> str

Get an API token.

Parameters:

Name Type Description Default
token_type APITokenType

The type of the token to get.

WORKLOAD
expires_in Optional[int]

The time in seconds until the token expires.

None
schedule_id Optional[UUID]

The ID of the schedule to get a token for.

None
pipeline_run_id Optional[UUID]

The ID of the pipeline run to get a token for.

None
step_run_id Optional[UUID]

The ID of the step run to get a token for.

None

Returns:

Type Description
str

The API token.

Raises:

Type Description
ValueError

if the server response is not valid.

Source code in src/zenml/zen_stores/rest_zen_store.py
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
def get_api_token(
    self,
    token_type: APITokenType = APITokenType.WORKLOAD,
    expires_in: Optional[int] = None,
    schedule_id: Optional[UUID] = None,
    pipeline_run_id: Optional[UUID] = None,
    step_run_id: Optional[UUID] = None,
) -> str:
    """Get an API token.

    Args:
        token_type: The type of the token to get.
        expires_in: The time in seconds until the token expires.
        schedule_id: The ID of the schedule to get a token for.
        pipeline_run_id: The ID of the pipeline run to get a token for.
        step_run_id: The ID of the step run to get a token for.

    Returns:
        The API token.

    Raises:
        ValueError: if the server response is not valid.
    """
    params: Dict[str, Any] = {
        "token_type": token_type.value,
    }
    if expires_in:
        params["expires_in"] = expires_in
    if schedule_id:
        params["schedule_id"] = schedule_id
    if pipeline_run_id:
        params["pipeline_run_id"] = pipeline_run_id
    if step_run_id:
        params["step_run_id"] = step_run_id
    response_body = self.get(API_TOKEN, params=params)
    if not isinstance(response_body, str):
        raise ValueError(
            f"Bad API Response. Expected API token, got "
            f"{type(response_body)}"
        )
    return response_body
get_artifact(artifact_id: UUID, hydrate: bool = True) -> ArtifactResponse

Gets an artifact.

Parameters:

Name Type Description Default
artifact_id UUID

The ID of the artifact to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ArtifactResponse

The artifact.

Source code in src/zenml/zen_stores/rest_zen_store.py
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
def get_artifact(
    self, artifact_id: UUID, hydrate: bool = True
) -> ArtifactResponse:
    """Gets an artifact.

    Args:
        artifact_id: The ID of the artifact to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The artifact.
    """
    return self._get_resource(
        resource_id=artifact_id,
        route=ARTIFACTS,
        response_model=ArtifactResponse,
        params={"hydrate": hydrate},
    )
get_artifact_version(artifact_version_id: UUID, hydrate: bool = True) -> ArtifactVersionResponse

Gets an artifact.

Parameters:

Name Type Description Default
artifact_version_id UUID

The ID of the artifact version to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ArtifactVersionResponse

The artifact version.

Source code in src/zenml/zen_stores/rest_zen_store.py
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
def get_artifact_version(
    self, artifact_version_id: UUID, hydrate: bool = True
) -> ArtifactVersionResponse:
    """Gets an artifact.

    Args:
        artifact_version_id: The ID of the artifact version to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The artifact version.
    """
    return self._get_resource(
        resource_id=artifact_version_id,
        route=ARTIFACT_VERSIONS,
        response_model=ArtifactVersionResponse,
        params={"hydrate": hydrate},
    )
get_artifact_visualization(artifact_visualization_id: UUID, hydrate: bool = True) -> ArtifactVisualizationResponse

Gets an artifact visualization.

Parameters:

Name Type Description Default
artifact_visualization_id UUID

The ID of the artifact visualization to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ArtifactVisualizationResponse

The artifact visualization.

Source code in src/zenml/zen_stores/rest_zen_store.py
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
def get_artifact_visualization(
    self, artifact_visualization_id: UUID, hydrate: bool = True
) -> ArtifactVisualizationResponse:
    """Gets an artifact visualization.

    Args:
        artifact_visualization_id: The ID of the artifact visualization to
            get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The artifact visualization.
    """
    return self._get_resource(
        resource_id=artifact_visualization_id,
        route=ARTIFACT_VISUALIZATIONS,
        response_model=ArtifactVisualizationResponse,
        params={"hydrate": hydrate},
    )
get_authorized_device(device_id: UUID, hydrate: bool = True) -> OAuthDeviceResponse

Gets a specific OAuth 2.0 authorized device.

Parameters:

Name Type Description Default
device_id UUID

The ID of the device to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
OAuthDeviceResponse

The requested device, if it was found.

Source code in src/zenml/zen_stores/rest_zen_store.py
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
def get_authorized_device(
    self, device_id: UUID, hydrate: bool = True
) -> OAuthDeviceResponse:
    """Gets a specific OAuth 2.0 authorized device.

    Args:
        device_id: The ID of the device to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested device, if it was found.
    """
    return self._get_resource(
        resource_id=device_id,
        route=DEVICES,
        response_model=OAuthDeviceResponse,
        params={"hydrate": hydrate},
    )
get_build(build_id: UUID, hydrate: bool = True) -> PipelineBuildResponse

Get a build with a given ID.

Parameters:

Name Type Description Default
build_id UUID

ID of the build.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineBuildResponse

The build.

Source code in src/zenml/zen_stores/rest_zen_store.py
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
def get_build(
    self, build_id: UUID, hydrate: bool = True
) -> PipelineBuildResponse:
    """Get a build with a given ID.

    Args:
        build_id: ID of the build.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The build.
    """
    return self._get_resource(
        resource_id=build_id,
        route=PIPELINE_BUILDS,
        response_model=PipelineBuildResponse,
        params={"hydrate": hydrate},
    )
get_code_reference(code_reference_id: UUID, hydrate: bool = True) -> CodeReferenceResponse

Gets a code reference.

Parameters:

Name Type Description Default
code_reference_id UUID

The ID of the code reference to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
CodeReferenceResponse

The code reference.

Source code in src/zenml/zen_stores/rest_zen_store.py
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
def get_code_reference(
    self, code_reference_id: UUID, hydrate: bool = True
) -> CodeReferenceResponse:
    """Gets a code reference.

    Args:
        code_reference_id: The ID of the code reference to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The code reference.
    """
    return self._get_resource(
        resource_id=code_reference_id,
        route=CODE_REFERENCES,
        response_model=CodeReferenceResponse,
        params={"hydrate": hydrate},
    )
get_code_repository(code_repository_id: UUID, hydrate: bool = True) -> CodeRepositoryResponse

Gets a specific code repository.

Parameters:

Name Type Description Default
code_repository_id UUID

The ID of the code repository to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
CodeRepositoryResponse

The requested code repository, if it was found.

Source code in src/zenml/zen_stores/rest_zen_store.py
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
def get_code_repository(
    self, code_repository_id: UUID, hydrate: bool = True
) -> CodeRepositoryResponse:
    """Gets a specific code repository.

    Args:
        code_repository_id: The ID of the code repository to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested code repository, if it was found.
    """
    return self._get_resource(
        resource_id=code_repository_id,
        route=CODE_REPOSITORIES,
        response_model=CodeRepositoryResponse,
        params={"hydrate": hydrate},
    )
get_deployment(deployment_id: UUID, hydrate: bool = True) -> PipelineDeploymentResponse

Get a deployment with a given ID.

Parameters:

Name Type Description Default
deployment_id UUID

ID of the deployment.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineDeploymentResponse

The deployment.

Source code in src/zenml/zen_stores/rest_zen_store.py
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
def get_deployment(
    self, deployment_id: UUID, hydrate: bool = True
) -> PipelineDeploymentResponse:
    """Get a deployment with a given ID.

    Args:
        deployment_id: ID of the deployment.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The deployment.
    """
    return self._get_resource(
        resource_id=deployment_id,
        route=PIPELINE_DEPLOYMENTS,
        response_model=PipelineDeploymentResponse,
        params={"hydrate": hydrate},
    )
get_deployment_id() -> UUID

Get the ID of the deployment.

Returns:

Type Description
UUID

The ID of the deployment.

Source code in src/zenml/zen_stores/rest_zen_store.py
535
536
537
538
539
540
541
def get_deployment_id(self) -> UUID:
    """Get the ID of the deployment.

    Returns:
        The ID of the deployment.
    """
    return self.server_info.id
get_event_source(event_source_id: UUID, hydrate: bool = True) -> EventSourceResponse

Get an event_source by ID.

Parameters:

Name Type Description Default
event_source_id UUID

The ID of the event_source to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
EventSourceResponse

The event_source.

Source code in src/zenml/zen_stores/rest_zen_store.py
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
def get_event_source(
    self,
    event_source_id: UUID,
    hydrate: bool = True,
) -> EventSourceResponse:
    """Get an event_source by ID.

    Args:
        event_source_id: The ID of the event_source to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The event_source.
    """
    return self._get_resource(
        resource_id=event_source_id,
        route=EVENT_SOURCES,
        response_model=EventSourceResponse,
        params={"hydrate": hydrate},
    )
get_flavor(flavor_id: UUID, hydrate: bool = True) -> FlavorResponse

Get a stack component flavor by ID.

Parameters:

Name Type Description Default
flavor_id UUID

The ID of the stack component flavor to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
FlavorResponse

The stack component flavor.

Source code in src/zenml/zen_stores/rest_zen_store.py
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
def get_flavor(
    self, flavor_id: UUID, hydrate: bool = True
) -> FlavorResponse:
    """Get a stack component flavor by ID.

    Args:
        flavor_id: The ID of the stack component flavor to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The stack component flavor.
    """
    return self._get_resource(
        resource_id=flavor_id,
        route=FLAVORS,
        response_model=FlavorResponse,
        params={"hydrate": hydrate},
    )
get_logs(logs_id: UUID, hydrate: bool = True) -> LogsResponse

Gets logs with the given ID.

Parameters:

Name Type Description Default
logs_id UUID

The ID of the logs to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
LogsResponse

The logs.

Source code in src/zenml/zen_stores/rest_zen_store.py
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
def get_logs(self, logs_id: UUID, hydrate: bool = True) -> LogsResponse:
    """Gets logs with the given ID.

    Args:
        logs_id: The ID of the logs to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The logs.
    """
    return self._get_resource(
        resource_id=logs_id,
        route=LOGS,
        response_model=LogsResponse,
        params={"hydrate": hydrate},
    )
get_model(model_id: UUID, hydrate: bool = True) -> ModelResponse

Get an existing model.

Parameters:

Name Type Description Default
model_id UUID

id of the model to be retrieved.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ModelResponse

The model of interest.

Source code in src/zenml/zen_stores/rest_zen_store.py
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
def get_model(self, model_id: UUID, hydrate: bool = True) -> ModelResponse:
    """Get an existing model.

    Args:
        model_id: id of the model to be retrieved.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The model of interest.
    """
    return self._get_resource(
        resource_id=model_id,
        route=MODELS,
        response_model=ModelResponse,
        params={"hydrate": hydrate},
    )
get_model_version(model_version_id: UUID, hydrate: bool = True) -> ModelVersionResponse

Get an existing model version.

Parameters:

Name Type Description Default
model_version_id UUID

name, id, stage or number of the model version to be retrieved. If skipped - latest is retrieved.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ModelVersionResponse

The model version of interest.

Source code in src/zenml/zen_stores/rest_zen_store.py
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
def get_model_version(
    self, model_version_id: UUID, hydrate: bool = True
) -> ModelVersionResponse:
    """Get an existing model version.

    Args:
        model_version_id: name, id, stage or number of the model version to
            be retrieved. If skipped - latest is retrieved.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The model version of interest.
    """
    return self._get_resource(
        resource_id=model_version_id,
        route=MODEL_VERSIONS,
        response_model=ModelVersionResponse,
        params={"hydrate": hydrate},
    )
get_or_create_run(pipeline_run: PipelineRunRequest) -> Tuple[PipelineRunResponse, bool]

Gets or creates a pipeline run.

If a run with the same ID or name already exists, it is returned. Otherwise, a new run is created.

Parameters:

Name Type Description Default
pipeline_run PipelineRunRequest

The pipeline run to get or create.

required

Returns:

Type Description
PipelineRunResponse

The pipeline run, and a boolean indicating whether the run was

bool

created or not.

Source code in src/zenml/zen_stores/rest_zen_store.py
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
def get_or_create_run(
    self, pipeline_run: PipelineRunRequest
) -> Tuple[PipelineRunResponse, bool]:
    """Gets or creates a pipeline run.

    If a run with the same ID or name already exists, it is returned.
    Otherwise, a new run is created.

    Args:
        pipeline_run: The pipeline run to get or create.

    Returns:
        The pipeline run, and a boolean indicating whether the run was
        created or not.
    """
    return self._get_or_create_resource(
        resource=pipeline_run,
        route=RUNS,
        response_model=PipelineRunResponse,
    )
get_or_generate_api_token() -> str

Get or generate an API token.

Returns:

Type Description
str

The API token.

Raises:

Type Description
CredentialsNotValid

if an API token cannot be fetched or generated because the client credentials are not valid.

Source code in src/zenml/zen_stores/rest_zen_store.py
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
def get_or_generate_api_token(self) -> str:
    """Get or generate an API token.

    Returns:
        The API token.

    Raises:
        CredentialsNotValid: if an API token cannot be fetched or
            generated because the client credentials are not valid.
    """
    if self._api_token is None or self._api_token.expired:
        # Check if a valid API token is already in the cache
        credentials_store = get_credentials_store()
        credentials = credentials_store.get_credentials(self.url)
        token = credentials.api_token if credentials else None
        if credentials and token and not token.expired:
            self._api_token = token
            return self._api_token.access_token

        # Token is expired or not found in the cache. Time to get a new one.

        if not token:
            logger.debug(f"Authenticating to {self.url}")
        else:
            logger.debug(
                f"Authentication token for {self.url} expired; refreshing..."
            )

        data: Optional[Dict[str, str]] = None

        # Use a custom user agent to identify the ZenML client in the server
        # logs.
        headers: Dict[str, str] = {
            "User-Agent": "zenml/" + zenml.__version__,
        }

        # Check if an API key is configured
        api_key = credentials_store.get_api_key(self.url)

        # Check if username and password are configured
        username, password = credentials_store.get_password(self.url)

        api_key_hint = (
            "\nHint: If you're getting this error in an automated, "
            "non-interactive workload like a pipeline run or a CI/CD job, "
            "you should use a service account API key to authenticate to "
            "the server instead of temporary CLI login credentials. For "
            "more information, see "
            "https://docs.zenml.io/how-to/project-setup-and-management/connecting-to-zenml/connect-with-a-service-account"
        )

        if api_key is not None:
            # An API key is configured. Use it as a password to
            # authenticate.
            data = {
                "grant_type": OAuthGrantTypes.ZENML_API_KEY.value,
                "password": api_key,
            }
        elif username is not None and password is not None:
            # Username and password are configured. Use them to authenticate.
            data = {
                "grant_type": OAuthGrantTypes.OAUTH_PASSWORD.value,
                "username": username,
                "password": password,
            }
        elif self.server_info.is_pro_server():
            # ZenML Pro workspaces use a proprietary authorization grant
            # where the ZenML Pro API session token is exchanged for a
            # regular ZenML server access token.

            # Get the ZenML Pro API session token, if cached and valid

            # We need to determine the right ZenML Pro API URL to use
            pro_api_url = self.server_info.pro_api_url
            if not pro_api_url and credentials and credentials.pro_api_url:
                pro_api_url = credentials.pro_api_url
            if not pro_api_url:
                pro_api_url = ZENML_PRO_API_URL

            pro_token = credentials_store.get_pro_token(
                pro_api_url, allow_expired=True
            )
            if not pro_token:
                raise CredentialsNotValid(
                    "You need to be logged in to ZenML Pro in order to "
                    f"access the ZenML Pro server '{self.url}'. Please run "
                    "'zenml login' to log in or choose a different server."
                    + api_key_hint
                )

            elif pro_token.expired:
                raise CredentialsNotValid(
                    "Your ZenML Pro login session has expired. "
                    "Please log in again using 'zenml login'."
                    + api_key_hint
                )

            data = {
                "grant_type": OAuthGrantTypes.ZENML_EXTERNAL.value,
            }
            headers.update(
                {"Authorization": "Bearer " + pro_token.access_token}
            )
        else:
            if not token:
                raise CredentialsNotValid(
                    "No valid credentials found. Please run 'zenml login "
                    f"--url {self.url}' to connect to the current server."
                    + api_key_hint
                )
            elif token.expired:
                raise CredentialsNotValid(
                    "Your authentication to the current server has expired. "
                    "Please log in again using 'zenml login --url "
                    f"{self.url}'." + api_key_hint
                )

        response = self._handle_response(
            requests.post(
                self.url + API + VERSION_1 + LOGIN,
                data=data,
                verify=self.config.verify_ssl,
                timeout=self.config.http_timeout,
                headers=headers,
            )
        )
        try:
            token_response = OAuthTokenResponse.model_validate(response)
        except ValidationError as e:
            raise CredentialsNotValid(
                "Unexpected response received while authenticating to "
                f"the server {e}"
            ) from e

        # Cache the token
        self._api_token = credentials_store.set_token(
            self.url, token_response
        )

        # Update the server info in the credentials store with the latest
        # information from the server.
        # NOTE: this is the best place to do this because we know that
        # the token is valid and the server is reachable.
        try:
            server_info = self.get_store_info()
        except Exception as e:
            logger.warning(f"Failed to get server info: {e}.")
        else:
            credentials_store.update_server_info(self.url, server_info)

    return self._api_token.access_token
get_pipeline(pipeline_id: UUID, hydrate: bool = True) -> PipelineResponse

Get a pipeline with a given ID.

Parameters:

Name Type Description Default
pipeline_id UUID

ID of the pipeline.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineResponse

The pipeline.

Source code in src/zenml/zen_stores/rest_zen_store.py
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
def get_pipeline(
    self, pipeline_id: UUID, hydrate: bool = True
) -> PipelineResponse:
    """Get a pipeline with a given ID.

    Args:
        pipeline_id: ID of the pipeline.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The pipeline.
    """
    return self._get_resource(
        resource_id=pipeline_id,
        route=PIPELINES,
        response_model=PipelineResponse,
        params={"hydrate": hydrate},
    )
get_project(project_name_or_id: Union[UUID, str], hydrate: bool = True) -> ProjectResponse

Get an existing project by name or ID.

Parameters:

Name Type Description Default
project_name_or_id Union[UUID, str]

Name or ID of the project to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ProjectResponse

The requested project.

Source code in src/zenml/zen_stores/rest_zen_store.py
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
def get_project(
    self, project_name_or_id: Union[UUID, str], hydrate: bool = True
) -> ProjectResponse:
    """Get an existing project by name or ID.

    Args:
        project_name_or_id: Name or ID of the project to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested project.
    """
    return self._get_resource(
        resource_id=project_name_or_id,
        route=PROJECTS,
        response_model=ProjectResponse,
        params={"hydrate": hydrate},
    )
get_run(run_id: UUID, hydrate: bool = True) -> PipelineRunResponse

Gets a pipeline run.

Parameters:

Name Type Description Default
run_id UUID

The ID of the pipeline run to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineRunResponse

The pipeline run.

Source code in src/zenml/zen_stores/rest_zen_store.py
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
def get_run(
    self, run_id: UUID, hydrate: bool = True
) -> PipelineRunResponse:
    """Gets a pipeline run.

    Args:
        run_id: The ID of the pipeline run to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The pipeline run.
    """
    return self._get_resource(
        resource_id=run_id,
        route=RUNS,
        response_model=PipelineRunResponse,
        params={"hydrate": hydrate},
    )
get_run_step(step_run_id: UUID, hydrate: bool = True) -> StepRunResponse

Get a step run by ID.

Parameters:

Name Type Description Default
step_run_id UUID

The ID of the step run to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
StepRunResponse

The step run.

Source code in src/zenml/zen_stores/rest_zen_store.py
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
def get_run_step(
    self, step_run_id: UUID, hydrate: bool = True
) -> StepRunResponse:
    """Get a step run by ID.

    Args:
        step_run_id: The ID of the step run to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The step run.
    """
    return self._get_resource(
        resource_id=step_run_id,
        route=STEPS,
        response_model=StepRunResponse,
        params={"hydrate": hydrate},
    )
get_run_template(template_id: UUID, hydrate: bool = True) -> RunTemplateResponse

Get a run template with a given ID.

Parameters:

Name Type Description Default
template_id UUID

ID of the template.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
RunTemplateResponse

The template.

Source code in src/zenml/zen_stores/rest_zen_store.py
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
def get_run_template(
    self, template_id: UUID, hydrate: bool = True
) -> RunTemplateResponse:
    """Get a run template with a given ID.

    Args:
        template_id: ID of the template.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The template.
    """
    return self._get_resource(
        resource_id=template_id,
        route=RUN_TEMPLATES,
        response_model=RunTemplateResponse,
        params={"hydrate": hydrate},
    )
get_schedule(schedule_id: UUID, hydrate: bool = True) -> ScheduleResponse

Get a schedule with a given ID.

Parameters:

Name Type Description Default
schedule_id UUID

ID of the schedule.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ScheduleResponse

The schedule.

Source code in src/zenml/zen_stores/rest_zen_store.py
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
def get_schedule(
    self, schedule_id: UUID, hydrate: bool = True
) -> ScheduleResponse:
    """Get a schedule with a given ID.

    Args:
        schedule_id: ID of the schedule.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The schedule.
    """
    return self._get_resource(
        resource_id=schedule_id,
        route=SCHEDULES,
        response_model=ScheduleResponse,
        params={"hydrate": hydrate},
    )
get_secret(secret_id: UUID, hydrate: bool = True) -> SecretResponse

Get a secret by ID.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret to fetch.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
SecretResponse

The secret.

Source code in src/zenml/zen_stores/rest_zen_store.py
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
def get_secret(
    self, secret_id: UUID, hydrate: bool = True
) -> SecretResponse:
    """Get a secret by ID.

    Args:
        secret_id: The ID of the secret to fetch.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The secret.
    """
    return self._get_resource(
        resource_id=secret_id,
        route=SECRETS,
        response_model=SecretResponse,
        params={"hydrate": hydrate},
    )
get_server_settings(hydrate: bool = True) -> ServerSettingsResponse

Get the server settings.

Parameters:

Name Type Description Default
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServerSettingsResponse

The server settings.

Source code in src/zenml/zen_stores/rest_zen_store.py
545
546
547
548
549
550
551
552
553
554
555
556
557
558
def get_server_settings(
    self, hydrate: bool = True
) -> ServerSettingsResponse:
    """Get the server settings.

    Args:
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The server settings.
    """
    response_body = self.get(SERVER_SETTINGS, params={"hydrate": hydrate})
    return ServerSettingsResponse.model_validate(response_body)
get_service(service_id: UUID, hydrate: bool = True) -> ServiceResponse

Get a service.

Parameters:

Name Type Description Default
service_id UUID

The ID of the service to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServiceResponse

The service.

Source code in src/zenml/zen_stores/rest_zen_store.py
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
def get_service(
    self, service_id: UUID, hydrate: bool = True
) -> ServiceResponse:
    """Get a service.

    Args:
        service_id: The ID of the service to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The service.
    """
    return self._get_resource(
        resource_id=service_id,
        route=SERVICES,
        response_model=ServiceResponse,
        params={"hydrate": hydrate},
    )
get_service_account(service_account_name_or_id: Union[str, UUID], hydrate: bool = True) -> ServiceAccountResponse

Gets a specific service account.

Parameters:

Name Type Description Default
service_account_name_or_id Union[str, UUID]

The name or ID of the service account to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServiceAccountResponse

The requested service account, if it was found.

Source code in src/zenml/zen_stores/rest_zen_store.py
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
def get_service_account(
    self,
    service_account_name_or_id: Union[str, UUID],
    hydrate: bool = True,
) -> ServiceAccountResponse:
    """Gets a specific service account.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested service account, if it was found.
    """
    return self._get_resource(
        resource_id=service_account_name_or_id,
        route=SERVICE_ACCOUNTS,
        response_model=ServiceAccountResponse,
        params={"hydrate": hydrate},
    )
get_service_connector(service_connector_id: UUID, hydrate: bool = True) -> ServiceConnectorResponse

Gets a specific service connector.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the service connector to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServiceConnectorResponse

The requested service connector, if it was found.

Source code in src/zenml/zen_stores/rest_zen_store.py
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
def get_service_connector(
    self, service_connector_id: UUID, hydrate: bool = True
) -> ServiceConnectorResponse:
    """Gets a specific service connector.

    Args:
        service_connector_id: The ID of the service connector to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested service connector, if it was found.
    """
    connector_model = self._get_resource(
        resource_id=service_connector_id,
        route=SERVICE_CONNECTORS,
        response_model=ServiceConnectorResponse,
        params={"expand_secrets": False, "hydrate": hydrate},
    )
    self._populate_connector_type(connector_model)
    return connector_model
get_service_connector_client(service_connector_id: UUID, resource_type: Optional[str] = None, resource_id: Optional[str] = None) -> ServiceConnectorResponse

Get a service connector client for a service connector and given resource.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the base service connector to use.

required
resource_type Optional[str]

The type of resource to get a client for.

None
resource_id Optional[str]

The ID of the resource to get a client for.

None

Returns:

Type Description
ServiceConnectorResponse

A service connector client that can be used to access the given

ServiceConnectorResponse

resource.

Source code in src/zenml/zen_stores/rest_zen_store.py
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
def get_service_connector_client(
    self,
    service_connector_id: UUID,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
) -> ServiceConnectorResponse:
    """Get a service connector client for a service connector and given resource.

    Args:
        service_connector_id: The ID of the base service connector to use.
        resource_type: The type of resource to get a client for.
        resource_id: The ID of the resource to get a client for.

    Returns:
        A service connector client that can be used to access the given
        resource.
    """
    params = {}
    if resource_type:
        params["resource_type"] = resource_type
    if resource_id:
        params["resource_id"] = resource_id
    response_body = self.get(
        f"{SERVICE_CONNECTORS}/{str(service_connector_id)}{SERVICE_CONNECTOR_CLIENT}",
        params=params,
    )

    connector = ServiceConnectorResponse.model_validate(response_body)
    self._populate_connector_type(connector)
    return connector
get_service_connector_type(connector_type: str) -> ServiceConnectorTypeModel

Returns the requested service connector type.

Parameters:

Name Type Description Default
connector_type str

the service connector type identifier.

required

Returns:

Type Description
ServiceConnectorTypeModel

The requested service connector type.

Source code in src/zenml/zen_stores/rest_zen_store.py
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
def get_service_connector_type(
    self,
    connector_type: str,
) -> ServiceConnectorTypeModel:
    """Returns the requested service connector type.

    Args:
        connector_type: the service connector type identifier.

    Returns:
        The requested service connector type.
    """
    # Use the local registry to get the service connector type, if it
    # exists.
    local_connector_type: Optional[ServiceConnectorTypeModel] = None
    if service_connector_registry.is_registered(connector_type):
        local_connector_type = (
            service_connector_registry.get_service_connector_type(
                connector_type
            )
        )
    try:
        response_body = self.get(
            f"{SERVICE_CONNECTOR_TYPES}/{connector_type}",
        )
        remote_connector_type = ServiceConnectorTypeModel.model_validate(
            response_body
        )
        if local_connector_type:
            # If locally available, return the local connector type but
            # mark it as being remotely available.
            local_connector_type.remote = True
            return local_connector_type

        # Mark the remote connector type as being only remotely available
        remote_connector_type.local = False
        remote_connector_type.remote = True

        return remote_connector_type
    except KeyError:
        # If the service connector type is not found, check the local
        # registry.
        return service_connector_registry.get_service_connector_type(
            connector_type
        )
get_stack(stack_id: UUID, hydrate: bool = True) -> StackResponse

Get a stack by its unique ID.

Parameters:

Name Type Description Default
stack_id UUID

The ID of the stack to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
StackResponse

The stack with the given ID.

Source code in src/zenml/zen_stores/rest_zen_store.py
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
def get_stack(self, stack_id: UUID, hydrate: bool = True) -> StackResponse:
    """Get a stack by its unique ID.

    Args:
        stack_id: The ID of the stack to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The stack with the given ID.
    """
    return self._get_resource(
        resource_id=stack_id,
        route=STACKS,
        response_model=StackResponse,
        params={"hydrate": hydrate},
    )
get_stack_component(component_id: UUID, hydrate: bool = True) -> ComponentResponse

Get a stack component by ID.

Parameters:

Name Type Description Default
component_id UUID

The ID of the stack component to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ComponentResponse

The stack component.

Source code in src/zenml/zen_stores/rest_zen_store.py
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
def get_stack_component(
    self, component_id: UUID, hydrate: bool = True
) -> ComponentResponse:
    """Get a stack component by ID.

    Args:
        component_id: The ID of the stack component to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The stack component.
    """
    return self._get_resource(
        resource_id=component_id,
        route=STACK_COMPONENTS,
        response_model=ComponentResponse,
        params={"hydrate": hydrate},
    )
get_stack_deployment_config(provider: StackDeploymentProvider, stack_name: str, location: Optional[str] = None) -> StackDeploymentConfig

Return the cloud provider console URL and configuration needed to deploy the ZenML stack.

Parameters:

Name Type Description Default
provider StackDeploymentProvider

The stack deployment provider.

required
stack_name str

The name of the stack.

required
location Optional[str]

The location where the stack should be deployed.

None

Returns:

Type Description
StackDeploymentConfig

The cloud provider console URL and configuration needed to deploy

StackDeploymentConfig

the ZenML stack to the specified cloud provider.

Source code in src/zenml/zen_stores/rest_zen_store.py
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
def get_stack_deployment_config(
    self,
    provider: StackDeploymentProvider,
    stack_name: str,
    location: Optional[str] = None,
) -> StackDeploymentConfig:
    """Return the cloud provider console URL and configuration needed to deploy the ZenML stack.

    Args:
        provider: The stack deployment provider.
        stack_name: The name of the stack.
        location: The location where the stack should be deployed.

    Returns:
        The cloud provider console URL and configuration needed to deploy
        the ZenML stack to the specified cloud provider.
    """
    params = {
        "provider": provider.value,
        "stack_name": stack_name,
    }
    if location:
        params["location"] = location
    body = self.get(f"{STACK_DEPLOYMENT}{CONFIG}", params=params)
    return StackDeploymentConfig.model_validate(body)
get_stack_deployment_info(provider: StackDeploymentProvider) -> StackDeploymentInfo

Get information about a stack deployment provider.

Parameters:

Name Type Description Default
provider StackDeploymentProvider

The stack deployment provider.

required

Returns:

Type Description
StackDeploymentInfo

Information about the stack deployment provider.

Source code in src/zenml/zen_stores/rest_zen_store.py
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
def get_stack_deployment_info(
    self,
    provider: StackDeploymentProvider,
) -> StackDeploymentInfo:
    """Get information about a stack deployment provider.

    Args:
        provider: The stack deployment provider.

    Returns:
        Information about the stack deployment provider.
    """
    body = self.get(
        f"{STACK_DEPLOYMENT}{INFO}",
        params={"provider": provider.value},
    )
    return StackDeploymentInfo.model_validate(body)
get_stack_deployment_stack(provider: StackDeploymentProvider, stack_name: str, location: Optional[str] = None, date_start: Optional[datetime] = None) -> Optional[DeployedStack]

Return a matching ZenML stack that was deployed and registered.

Parameters:

Name Type Description Default
provider StackDeploymentProvider

The stack deployment provider.

required
stack_name str

The name of the stack.

required
location Optional[str]

The location where the stack should be deployed.

None
date_start Optional[datetime]

The date when the deployment started.

None

Returns:

Type Description
Optional[DeployedStack]

The ZenML stack that was deployed and registered or None if the

Optional[DeployedStack]

stack was not found.

Source code in src/zenml/zen_stores/rest_zen_store.py
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
def get_stack_deployment_stack(
    self,
    provider: StackDeploymentProvider,
    stack_name: str,
    location: Optional[str] = None,
    date_start: Optional[datetime] = None,
) -> Optional[DeployedStack]:
    """Return a matching ZenML stack that was deployed and registered.

    Args:
        provider: The stack deployment provider.
        stack_name: The name of the stack.
        location: The location where the stack should be deployed.
        date_start: The date when the deployment started.

    Returns:
        The ZenML stack that was deployed and registered or None if the
        stack was not found.
    """
    params = {
        "provider": provider.value,
        "stack_name": stack_name,
    }
    if location:
        params["location"] = location
    if date_start:
        params["date_start"] = str(date_start)
    body = self.get(
        f"{STACK_DEPLOYMENT}{STACK}",
        params=params,
    )
    if body:
        return DeployedStack.model_validate(body)

    return None
get_store_info() -> ServerModel

Get information about the server.

Returns:

Type Description
ServerModel

Information about the server.

Source code in src/zenml/zen_stores/rest_zen_store.py
525
526
527
528
529
530
531
532
533
def get_store_info(self) -> ServerModel:
    """Get information about the server.

    Returns:
        Information about the server.
    """
    body = self.get(INFO)
    self._server_info = ServerModel.model_validate(body)
    return self._server_info
get_tag(tag_name_or_id: Union[str, UUID], hydrate: bool = True) -> TagResponse

Get an existing tag.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

name or id of the tag to be retrieved.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
TagResponse

The tag of interest.

Source code in src/zenml/zen_stores/rest_zen_store.py
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
def get_tag(
    self,
    tag_name_or_id: Union[str, UUID],
    hydrate: bool = True,
) -> TagResponse:
    """Get an existing tag.

    Args:
        tag_name_or_id: name or id of the tag to be retrieved.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The tag of interest.
    """
    params: Dict[str, Any] = {"hydrate": hydrate}

    return self._get_resource(
        resource_id=tag_name_or_id,
        route=TAGS,
        response_model=TagResponse,
        params=params,
    )
get_trigger(trigger_id: UUID, hydrate: bool = True) -> TriggerResponse

Get a trigger by ID.

Parameters:

Name Type Description Default
trigger_id UUID

The ID of the trigger to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
TriggerResponse

The trigger.

Source code in src/zenml/zen_stores/rest_zen_store.py
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
def get_trigger(
    self,
    trigger_id: UUID,
    hydrate: bool = True,
) -> TriggerResponse:
    """Get a trigger by ID.

    Args:
        trigger_id: The ID of the trigger to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The trigger.
    """
    return self._get_resource(
        resource_id=trigger_id,
        route=TRIGGERS,
        response_model=TriggerResponse,
        params={"hydrate": hydrate},
    )
get_trigger_execution(trigger_execution_id: UUID, hydrate: bool = True) -> TriggerExecutionResponse

Get an trigger execution by ID.

Parameters:

Name Type Description Default
trigger_execution_id UUID

The ID of the trigger execution to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
TriggerExecutionResponse

The trigger execution.

Source code in src/zenml/zen_stores/rest_zen_store.py
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
def get_trigger_execution(
    self,
    trigger_execution_id: UUID,
    hydrate: bool = True,
) -> TriggerExecutionResponse:
    """Get an trigger execution by ID.

    Args:
        trigger_execution_id: The ID of the trigger execution to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The trigger execution.
    """
    return self._get_resource(
        resource_id=trigger_execution_id,
        route=TRIGGER_EXECUTIONS,
        response_model=TriggerExecutionResponse,
        params={"hydrate": hydrate},
    )
get_user(user_name_or_id: Optional[Union[str, UUID]] = None, include_private: bool = False, hydrate: bool = True) -> UserResponse

Gets a specific user, when no id is specified get the active user.

The include_private parameter is ignored here as it is handled implicitly by the /current-user endpoint that is queried when no user_name_or_id is set. Raises a KeyError in case a user with that id does not exist.

Parameters:

Name Type Description Default
user_name_or_id Optional[Union[str, UUID]]

The name or ID of the user to get.

None
include_private bool

Whether to include private user information.

False
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
UserResponse

The requested user, if it was found.

Source code in src/zenml/zen_stores/rest_zen_store.py
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
def get_user(
    self,
    user_name_or_id: Optional[Union[str, UUID]] = None,
    include_private: bool = False,
    hydrate: bool = True,
) -> UserResponse:
    """Gets a specific user, when no id is specified get the active user.

    The `include_private` parameter is ignored here as it is handled
    implicitly by the /current-user endpoint that is queried when no
    user_name_or_id is set. Raises a KeyError in case a user with that id
    does not exist.

    Args:
        user_name_or_id: The name or ID of the user to get.
        include_private: Whether to include private user information.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested user, if it was found.
    """
    if user_name_or_id:
        return self._get_resource(
            resource_id=user_name_or_id,
            route=USERS,
            response_model=UserResponse,
            params={"hydrate": hydrate},
        )
    else:
        body = self.get(CURRENT_USER, params={"hydrate": hydrate})
        return UserResponse.model_validate(body)
list_actions(action_filter_model: ActionFilter, hydrate: bool = False) -> Page[ActionResponse]

List all actions matching the given filter criteria.

Parameters:

Name Type Description Default
action_filter_model ActionFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ActionResponse]

A list of all actions matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
def list_actions(
    self,
    action_filter_model: ActionFilter,
    hydrate: bool = False,
) -> Page[ActionResponse]:
    """List all actions matching the given filter criteria.

    Args:
        action_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all actions matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=ACTIONS,
        response_model=ActionResponse,
        filter_model=action_filter_model,
        params={"hydrate": hydrate},
    )
list_api_keys(service_account_id: UUID, filter_model: APIKeyFilter, hydrate: bool = False) -> Page[APIKeyResponse]

List all API keys for a service account matching the given filter criteria.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to list the API keys.

required
filter_model APIKeyFilter

All filter parameters including pagination params

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[APIKeyResponse]

A list of all API keys matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
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
def list_api_keys(
    self,
    service_account_id: UUID,
    filter_model: APIKeyFilter,
    hydrate: bool = False,
) -> Page[APIKeyResponse]:
    """List all API keys for a service account matching the given filter criteria.

    Args:
        service_account_id: The ID of the service account for which to list
            the API keys.
        filter_model: All filter parameters including pagination
            params
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all API keys matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=f"{SERVICE_ACCOUNTS}/{str(service_account_id)}{API_KEYS}",
        response_model=APIKeyResponse,
        filter_model=filter_model,
        params={"hydrate": hydrate},
    )
list_artifact_versions(artifact_version_filter_model: ArtifactVersionFilter, hydrate: bool = False) -> Page[ArtifactVersionResponse]

List all artifact versions matching the given filter criteria.

Parameters:

Name Type Description Default
artifact_version_filter_model ArtifactVersionFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ArtifactVersionResponse]

A list of all artifact versions matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
def list_artifact_versions(
    self,
    artifact_version_filter_model: ArtifactVersionFilter,
    hydrate: bool = False,
) -> Page[ArtifactVersionResponse]:
    """List all artifact versions matching the given filter criteria.

    Args:
        artifact_version_filter_model: All filter parameters including
            pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all artifact versions matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=ARTIFACT_VERSIONS,
        response_model=ArtifactVersionResponse,
        filter_model=artifact_version_filter_model,
        params={"hydrate": hydrate},
    )
list_artifacts(filter_model: ArtifactFilter, hydrate: bool = False) -> Page[ArtifactResponse]

List all artifacts matching the given filter criteria.

Parameters:

Name Type Description Default
filter_model ArtifactFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ArtifactResponse]

A list of all artifacts matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
def list_artifacts(
    self, filter_model: ArtifactFilter, hydrate: bool = False
) -> Page[ArtifactResponse]:
    """List all artifacts matching the given filter criteria.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all artifacts matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=ARTIFACTS,
        response_model=ArtifactResponse,
        filter_model=filter_model,
        params={"hydrate": hydrate},
    )
list_authorized_devices(filter_model: OAuthDeviceFilter, hydrate: bool = False) -> Page[OAuthDeviceResponse]

List all OAuth 2.0 authorized devices for a user.

Parameters:

Name Type Description Default
filter_model OAuthDeviceFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[OAuthDeviceResponse]

A page of all matching OAuth 2.0 authorized devices.

Source code in src/zenml/zen_stores/rest_zen_store.py
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
def list_authorized_devices(
    self, filter_model: OAuthDeviceFilter, hydrate: bool = False
) -> Page[OAuthDeviceResponse]:
    """List all OAuth 2.0 authorized devices for a user.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all matching OAuth 2.0 authorized devices.
    """
    return self._list_paginated_resources(
        route=DEVICES,
        response_model=OAuthDeviceResponse,
        filter_model=filter_model,
        params={"hydrate": hydrate},
    )
list_builds(build_filter_model: PipelineBuildFilter, hydrate: bool = False) -> Page[PipelineBuildResponse]

List all builds matching the given filter criteria.

Parameters:

Name Type Description Default
build_filter_model PipelineBuildFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineBuildResponse]

A page of all builds matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
def list_builds(
    self,
    build_filter_model: PipelineBuildFilter,
    hydrate: bool = False,
) -> Page[PipelineBuildResponse]:
    """List all builds matching the given filter criteria.

    Args:
        build_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all builds matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=PIPELINE_BUILDS,
        response_model=PipelineBuildResponse,
        filter_model=build_filter_model,
        params={"hydrate": hydrate},
    )
list_code_repositories(filter_model: CodeRepositoryFilter, hydrate: bool = False) -> Page[CodeRepositoryResponse]

List all code repositories.

Parameters:

Name Type Description Default
filter_model CodeRepositoryFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[CodeRepositoryResponse]

A page of all code repositories.

Source code in src/zenml/zen_stores/rest_zen_store.py
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
def list_code_repositories(
    self,
    filter_model: CodeRepositoryFilter,
    hydrate: bool = False,
) -> Page[CodeRepositoryResponse]:
    """List all code repositories.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all code repositories.
    """
    return self._list_paginated_resources(
        route=CODE_REPOSITORIES,
        response_model=CodeRepositoryResponse,
        filter_model=filter_model,
        params={"hydrate": hydrate},
    )
list_deployments(deployment_filter_model: PipelineDeploymentFilter, hydrate: bool = False) -> Page[PipelineDeploymentResponse]

List all deployments matching the given filter criteria.

Parameters:

Name Type Description Default
deployment_filter_model PipelineDeploymentFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineDeploymentResponse]

A page of all deployments matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
def list_deployments(
    self,
    deployment_filter_model: PipelineDeploymentFilter,
    hydrate: bool = False,
) -> Page[PipelineDeploymentResponse]:
    """List all deployments matching the given filter criteria.

    Args:
        deployment_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all deployments matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=PIPELINE_DEPLOYMENTS,
        response_model=PipelineDeploymentResponse,
        filter_model=deployment_filter_model,
        params={"hydrate": hydrate},
    )
list_event_sources(event_source_filter_model: EventSourceFilter, hydrate: bool = False) -> Page[EventSourceResponse]

List all event_sources matching the given filter criteria.

Parameters:

Name Type Description Default
event_source_filter_model EventSourceFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[EventSourceResponse]

A list of all event_sources matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
def list_event_sources(
    self,
    event_source_filter_model: EventSourceFilter,
    hydrate: bool = False,
) -> Page[EventSourceResponse]:
    """List all event_sources matching the given filter criteria.

    Args:
        event_source_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all event_sources matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=EVENT_SOURCES,
        response_model=EventSourceResponse,
        filter_model=event_source_filter_model,
        params={"hydrate": hydrate},
    )
list_flavors(flavor_filter_model: FlavorFilter, hydrate: bool = False) -> Page[FlavorResponse]

List all stack component flavors matching the given filter criteria.

Parameters:

Name Type Description Default
flavor_filter_model FlavorFilter

All filter parameters including pagination params

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[FlavorResponse]

List of all the stack component flavors matching the given criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
def list_flavors(
    self,
    flavor_filter_model: FlavorFilter,
    hydrate: bool = False,
) -> Page[FlavorResponse]:
    """List all stack component flavors matching the given filter criteria.

    Args:
        flavor_filter_model: All filter parameters including pagination
            params
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        List of all the stack component flavors matching the given criteria.
    """
    return self._list_paginated_resources(
        route=FLAVORS,
        response_model=FlavorResponse,
        filter_model=flavor_filter_model,
        params={"hydrate": hydrate},
    )
list_model_version_artifact_links(model_version_artifact_link_filter_model: ModelVersionArtifactFilter, hydrate: bool = False) -> Page[ModelVersionArtifactResponse]

Get all model version to artifact links by filter.

Parameters:

Name Type Description Default
model_version_artifact_link_filter_model ModelVersionArtifactFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ModelVersionArtifactResponse]

A page of all model version to artifact links.

Source code in src/zenml/zen_stores/rest_zen_store.py
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
def list_model_version_artifact_links(
    self,
    model_version_artifact_link_filter_model: ModelVersionArtifactFilter,
    hydrate: bool = False,
) -> Page[ModelVersionArtifactResponse]:
    """Get all model version to artifact links by filter.

    Args:
        model_version_artifact_link_filter_model: All filter parameters
            including pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all model version to artifact links.
    """
    return self._list_paginated_resources(
        route=MODEL_VERSION_ARTIFACTS,
        response_model=ModelVersionArtifactResponse,
        filter_model=model_version_artifact_link_filter_model,
        params={"hydrate": hydrate},
    )
list_model_version_pipeline_run_links(model_version_pipeline_run_link_filter_model: ModelVersionPipelineRunFilter, hydrate: bool = False) -> Page[ModelVersionPipelineRunResponse]

Get all model version to pipeline run links by filter.

Parameters:

Name Type Description Default
model_version_pipeline_run_link_filter_model ModelVersionPipelineRunFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ModelVersionPipelineRunResponse]

A page of all model version to pipeline run links.

Source code in src/zenml/zen_stores/rest_zen_store.py
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
def list_model_version_pipeline_run_links(
    self,
    model_version_pipeline_run_link_filter_model: ModelVersionPipelineRunFilter,
    hydrate: bool = False,
) -> Page[ModelVersionPipelineRunResponse]:
    """Get all model version to pipeline run links by filter.

    Args:
        model_version_pipeline_run_link_filter_model: All filter parameters
            including pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all model version to pipeline run links.
    """
    return self._list_paginated_resources(
        route=MODEL_VERSION_PIPELINE_RUNS,
        response_model=ModelVersionPipelineRunResponse,
        filter_model=model_version_pipeline_run_link_filter_model,
        params={"hydrate": hydrate},
    )
list_model_versions(model_version_filter_model: ModelVersionFilter, hydrate: bool = False) -> Page[ModelVersionResponse]

Get all model versions by filter.

Parameters:

Name Type Description Default
model_version_filter_model ModelVersionFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ModelVersionResponse]

A page of all model versions.

Source code in src/zenml/zen_stores/rest_zen_store.py
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
def list_model_versions(
    self,
    model_version_filter_model: ModelVersionFilter,
    hydrate: bool = False,
) -> Page[ModelVersionResponse]:
    """Get all model versions by filter.

    Args:
        model_version_filter_model: All filter parameters including
            pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all model versions.
    """
    return self._list_paginated_resources(
        route=MODEL_VERSIONS,
        response_model=ModelVersionResponse,
        filter_model=model_version_filter_model,
        params={"hydrate": hydrate},
    )
list_models(model_filter_model: ModelFilter, hydrate: bool = False) -> Page[ModelResponse]

Get all models by filter.

Parameters:

Name Type Description Default
model_filter_model ModelFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ModelResponse]

A page of all models.

Source code in src/zenml/zen_stores/rest_zen_store.py
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
def list_models(
    self,
    model_filter_model: ModelFilter,
    hydrate: bool = False,
) -> Page[ModelResponse]:
    """Get all models by filter.

    Args:
        model_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all models.
    """
    return self._list_paginated_resources(
        route=MODELS,
        response_model=ModelResponse,
        filter_model=model_filter_model,
        params={"hydrate": hydrate},
    )
list_pipelines(pipeline_filter_model: PipelineFilter, hydrate: bool = False) -> Page[PipelineResponse]

List all pipelines matching the given filter criteria.

Parameters:

Name Type Description Default
pipeline_filter_model PipelineFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineResponse]

A list of all pipelines matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
def list_pipelines(
    self,
    pipeline_filter_model: PipelineFilter,
    hydrate: bool = False,
) -> Page[PipelineResponse]:
    """List all pipelines matching the given filter criteria.

    Args:
        pipeline_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all pipelines matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=PIPELINES,
        response_model=PipelineResponse,
        filter_model=pipeline_filter_model,
        params={"hydrate": hydrate},
    )
list_projects(project_filter_model: ProjectFilter, hydrate: bool = False) -> Page[ProjectResponse]

List all projects matching the given filter criteria.

Parameters:

Name Type Description Default
project_filter_model ProjectFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ProjectResponse]

A list of all projects matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
def list_projects(
    self,
    project_filter_model: ProjectFilter,
    hydrate: bool = False,
) -> Page[ProjectResponse]:
    """List all projects matching the given filter criteria.

    Args:
        project_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all projects matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=PROJECTS,
        response_model=ProjectResponse,
        filter_model=project_filter_model,
        params={"hydrate": hydrate},
    )
list_run_steps(step_run_filter_model: StepRunFilter, hydrate: bool = False) -> Page[StepRunResponse]

List all step runs matching the given filter criteria.

Parameters:

Name Type Description Default
step_run_filter_model StepRunFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[StepRunResponse]

A list of all step runs matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
def list_run_steps(
    self,
    step_run_filter_model: StepRunFilter,
    hydrate: bool = False,
) -> Page[StepRunResponse]:
    """List all step runs matching the given filter criteria.

    Args:
        step_run_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all step runs matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=STEPS,
        response_model=StepRunResponse,
        filter_model=step_run_filter_model,
        params={"hydrate": hydrate},
    )
list_run_templates(template_filter_model: RunTemplateFilter, hydrate: bool = False) -> Page[RunTemplateResponse]

List all run templates matching the given filter criteria.

Parameters:

Name Type Description Default
template_filter_model RunTemplateFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[RunTemplateResponse]

A list of all templates matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
def list_run_templates(
    self,
    template_filter_model: RunTemplateFilter,
    hydrate: bool = False,
) -> Page[RunTemplateResponse]:
    """List all run templates matching the given filter criteria.

    Args:
        template_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all templates matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=RUN_TEMPLATES,
        response_model=RunTemplateResponse,
        filter_model=template_filter_model,
        params={"hydrate": hydrate},
    )
list_runs(runs_filter_model: PipelineRunFilter, hydrate: bool = False) -> Page[PipelineRunResponse]

List all pipeline runs matching the given filter criteria.

Parameters:

Name Type Description Default
runs_filter_model PipelineRunFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineRunResponse]

A list of all pipeline runs matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
def list_runs(
    self,
    runs_filter_model: PipelineRunFilter,
    hydrate: bool = False,
) -> Page[PipelineRunResponse]:
    """List all pipeline runs matching the given filter criteria.

    Args:
        runs_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all pipeline runs matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=RUNS,
        response_model=PipelineRunResponse,
        filter_model=runs_filter_model,
        params={"hydrate": hydrate},
    )
list_schedules(schedule_filter_model: ScheduleFilter, hydrate: bool = False) -> Page[ScheduleResponse]

List all schedules.

Parameters:

Name Type Description Default
schedule_filter_model ScheduleFilter

All filter parameters including pagination params

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ScheduleResponse]

A list of schedules.

Source code in src/zenml/zen_stores/rest_zen_store.py
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
def list_schedules(
    self,
    schedule_filter_model: ScheduleFilter,
    hydrate: bool = False,
) -> Page[ScheduleResponse]:
    """List all schedules.

    Args:
        schedule_filter_model: All filter parameters including pagination
            params
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of schedules.
    """
    return self._list_paginated_resources(
        route=SCHEDULES,
        response_model=ScheduleResponse,
        filter_model=schedule_filter_model,
        params={"hydrate": hydrate},
    )
list_secrets(secret_filter_model: SecretFilter, hydrate: bool = False) -> Page[SecretResponse]

List all secrets matching the given filter criteria.

Note that returned secrets do not include any secret values. To fetch the secret values, use get_secret.

Parameters:

Name Type Description Default
secret_filter_model SecretFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[SecretResponse]

A list of all secrets matching the filter criteria, with pagination

Page[SecretResponse]

information and sorted according to the filter criteria. The

Page[SecretResponse]

returned secrets do not include any secret values, only metadata. To

Page[SecretResponse]

fetch the secret values, use get_secret individually with each

Page[SecretResponse]

secret.

Source code in src/zenml/zen_stores/rest_zen_store.py
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
def list_secrets(
    self, secret_filter_model: SecretFilter, hydrate: bool = False
) -> Page[SecretResponse]:
    """List all secrets matching the given filter criteria.

    Note that returned secrets do not include any secret values. To fetch
    the secret values, use `get_secret`.

    Args:
        secret_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all secrets matching the filter criteria, with pagination
        information and sorted according to the filter criteria. The
        returned secrets do not include any secret values, only metadata. To
        fetch the secret values, use `get_secret` individually with each
        secret.
    """
    return self._list_paginated_resources(
        route=SECRETS,
        response_model=SecretResponse,
        filter_model=secret_filter_model,
        params={"hydrate": hydrate},
    )
list_service_accounts(filter_model: ServiceAccountFilter, hydrate: bool = False) -> Page[ServiceAccountResponse]

List all service accounts.

Parameters:

Name Type Description Default
filter_model ServiceAccountFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ServiceAccountResponse]

A list of filtered service accounts.

Source code in src/zenml/zen_stores/rest_zen_store.py
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
def list_service_accounts(
    self, filter_model: ServiceAccountFilter, hydrate: bool = False
) -> Page[ServiceAccountResponse]:
    """List all service accounts.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of filtered service accounts.
    """
    return self._list_paginated_resources(
        route=SERVICE_ACCOUNTS,
        response_model=ServiceAccountResponse,
        filter_model=filter_model,
        params={"hydrate": hydrate},
    )
list_service_connector_resources(filter_model: ServiceConnectorFilter) -> List[ServiceConnectorResourcesModel]

List resources that can be accessed by service connectors.

Parameters:

Name Type Description Default
filter_model ServiceConnectorFilter

The filter model to use when fetching service connectors.

required

Returns:

Type Description
List[ServiceConnectorResourcesModel]

The matching list of resources that available service

List[ServiceConnectorResourcesModel]

connectors have access to.

Source code in src/zenml/zen_stores/rest_zen_store.py
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
def list_service_connector_resources(
    self,
    filter_model: ServiceConnectorFilter,
) -> List[ServiceConnectorResourcesModel]:
    """List resources that can be accessed by service connectors.

    Args:
        filter_model: The filter model to use when fetching service
            connectors.

    Returns:
        The matching list of resources that available service
        connectors have access to.
    """
    response_body = self.get(
        SERVICE_CONNECTOR_RESOURCES,
        params=filter_model.model_dump(exclude_none=True),
        timeout=max(
            self.config.http_timeout,
            SERVICE_CONNECTOR_VERIFY_REQUEST_TIMEOUT,
        ),
    )

    assert isinstance(response_body, list)
    resource_list = [
        ServiceConnectorResourcesModel.model_validate(item)
        for item in response_body
    ]

    self._populate_connector_type(*resource_list)

    # For service connectors with types that are only locally available,
    # we need to retrieve the resource list locally
    for idx, resources in enumerate(resource_list):
        if isinstance(resources.connector_type, str):
            # Skip connector types that are neither locally nor remotely
            # available
            continue
        if resources.connector_type.remote:
            # Skip connector types that are remotely available
            continue

        # Retrieve the resource list locally
        assert resources.id is not None
        connector = self.get_service_connector(resources.id)
        connector_instance = (
            service_connector_registry.instantiate_connector(
                model=connector
            )
        )

        try:
            local_resources = connector_instance.verify(
                resource_type=filter_model.resource_type,
                resource_id=filter_model.resource_id,
            )
        except (ValueError, AuthorizationException) as e:
            logger.error(
                f"Failed to fetch {filter_model.resource_type or 'available'} "
                f"resources from service connector {connector.name}/"
                f"{connector.id}: {e}"
            )
            continue

        resource_list[idx] = local_resources

    return resource_list
list_service_connector_types(connector_type: Optional[str] = None, resource_type: Optional[str] = None, auth_method: Optional[str] = None) -> List[ServiceConnectorTypeModel]

Get a list of service connector types.

Parameters:

Name Type Description Default
connector_type Optional[str]

Filter by connector type.

None
resource_type Optional[str]

Filter by resource type.

None
auth_method Optional[str]

Filter by authentication method.

None

Returns:

Type Description
List[ServiceConnectorTypeModel]

List of service connector types.

Source code in src/zenml/zen_stores/rest_zen_store.py
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
def list_service_connector_types(
    self,
    connector_type: Optional[str] = None,
    resource_type: Optional[str] = None,
    auth_method: Optional[str] = None,
) -> List[ServiceConnectorTypeModel]:
    """Get a list of service connector types.

    Args:
        connector_type: Filter by connector type.
        resource_type: Filter by resource type.
        auth_method: Filter by authentication method.

    Returns:
        List of service connector types.
    """
    params = {}
    if connector_type:
        params["connector_type"] = connector_type
    if resource_type:
        params["resource_type"] = resource_type
    if auth_method:
        params["auth_method"] = auth_method
    response_body = self.get(
        SERVICE_CONNECTOR_TYPES,
        params=params,
    )

    assert isinstance(response_body, list)
    remote_connector_types = [
        ServiceConnectorTypeModel.model_validate(item)
        for item in response_body
    ]

    # Mark the remote connector types as being only remotely available
    for c in remote_connector_types:
        c.local = False
        c.remote = True

    local_connector_types = (
        service_connector_registry.list_service_connector_types(
            connector_type=connector_type,
            resource_type=resource_type,
            auth_method=auth_method,
        )
    )

    # Add the connector types in the local registry to the list of
    # connector types available remotely. Overwrite those that have
    # the same connector type but mark them as being remotely available.
    connector_types_map = {
        connector_type.connector_type: connector_type
        for connector_type in remote_connector_types
    }

    for connector in local_connector_types:
        if connector.connector_type in connector_types_map:
            connector.remote = True
        connector_types_map[connector.connector_type] = connector

    return list(connector_types_map.values())
list_service_connectors(filter_model: ServiceConnectorFilter, hydrate: bool = False) -> Page[ServiceConnectorResponse]

List all service connectors.

Parameters:

Name Type Description Default
filter_model ServiceConnectorFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ServiceConnectorResponse]

A page of all service connectors.

Source code in src/zenml/zen_stores/rest_zen_store.py
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
def list_service_connectors(
    self,
    filter_model: ServiceConnectorFilter,
    hydrate: bool = False,
) -> Page[ServiceConnectorResponse]:
    """List all service connectors.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all service connectors.
    """
    connector_models = self._list_paginated_resources(
        route=SERVICE_CONNECTORS,
        response_model=ServiceConnectorResponse,
        filter_model=filter_model,
        params={"expand_secrets": False, "hydrate": hydrate},
    )
    self._populate_connector_type(*connector_models.items)
    return connector_models
list_services(filter_model: ServiceFilter, hydrate: bool = False) -> Page[ServiceResponse]

List all services matching the given filter criteria.

Parameters:

Name Type Description Default
filter_model ServiceFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ServiceResponse]

A list of all services matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
def list_services(
    self, filter_model: ServiceFilter, hydrate: bool = False
) -> Page[ServiceResponse]:
    """List all services matching the given filter criteria.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all services matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=SERVICES,
        response_model=ServiceResponse,
        filter_model=filter_model,
        params={"hydrate": hydrate},
    )
list_stack_components(component_filter_model: ComponentFilter, hydrate: bool = False) -> Page[ComponentResponse]

List all stack components matching the given filter criteria.

Parameters:

Name Type Description Default
component_filter_model ComponentFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ComponentResponse]

A list of all stack components matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
def list_stack_components(
    self,
    component_filter_model: ComponentFilter,
    hydrate: bool = False,
) -> Page[ComponentResponse]:
    """List all stack components matching the given filter criteria.

    Args:
        component_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all stack components matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=STACK_COMPONENTS,
        response_model=ComponentResponse,
        filter_model=component_filter_model,
        params={"hydrate": hydrate},
    )
list_stacks(stack_filter_model: StackFilter, hydrate: bool = False) -> Page[StackResponse]

List all stacks matching the given filter criteria.

Parameters:

Name Type Description Default
stack_filter_model StackFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[StackResponse]

A list of all stacks matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
def list_stacks(
    self, stack_filter_model: StackFilter, hydrate: bool = False
) -> Page[StackResponse]:
    """List all stacks matching the given filter criteria.

    Args:
        stack_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all stacks matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=STACKS,
        response_model=StackResponse,
        filter_model=stack_filter_model,
        params={"hydrate": hydrate},
    )
list_tags(tag_filter_model: TagFilter, hydrate: bool = False) -> Page[TagResponse]

Get all tags by filter.

Parameters:

Name Type Description Default
tag_filter_model TagFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[TagResponse]

A page of all tags.

Source code in src/zenml/zen_stores/rest_zen_store.py
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
def list_tags(
    self,
    tag_filter_model: TagFilter,
    hydrate: bool = False,
) -> Page[TagResponse]:
    """Get all tags by filter.

    Args:
        tag_filter_model: All filter parameters including pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all tags.
    """
    return self._list_paginated_resources(
        route=TAGS,
        response_model=TagResponse,
        filter_model=tag_filter_model,
        params={"hydrate": hydrate},
    )
list_trigger_executions(trigger_execution_filter_model: TriggerExecutionFilter, hydrate: bool = False) -> Page[TriggerExecutionResponse]

List all trigger executions matching the given filter criteria.

Parameters:

Name Type Description Default
trigger_execution_filter_model TriggerExecutionFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[TriggerExecutionResponse]

A list of all trigger executions matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
def list_trigger_executions(
    self,
    trigger_execution_filter_model: TriggerExecutionFilter,
    hydrate: bool = False,
) -> Page[TriggerExecutionResponse]:
    """List all trigger executions matching the given filter criteria.

    Args:
        trigger_execution_filter_model: All filter parameters including
            pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all trigger executions matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=TRIGGER_EXECUTIONS,
        response_model=TriggerExecutionResponse,
        filter_model=trigger_execution_filter_model,
        params={"hydrate": hydrate},
    )
list_triggers(trigger_filter_model: TriggerFilter, hydrate: bool = False) -> Page[TriggerResponse]

List all triggers matching the given filter criteria.

Parameters:

Name Type Description Default
trigger_filter_model TriggerFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[TriggerResponse]

A list of all triggers matching the filter criteria.

Source code in src/zenml/zen_stores/rest_zen_store.py
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
def list_triggers(
    self,
    trigger_filter_model: TriggerFilter,
    hydrate: bool = False,
) -> Page[TriggerResponse]:
    """List all triggers matching the given filter criteria.

    Args:
        trigger_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all triggers matching the filter criteria.
    """
    return self._list_paginated_resources(
        route=TRIGGERS,
        response_model=TriggerResponse,
        filter_model=trigger_filter_model,
        params={"hydrate": hydrate},
    )
list_users(user_filter_model: UserFilter, hydrate: bool = False) -> Page[UserResponse]

List all users.

Parameters:

Name Type Description Default
user_filter_model UserFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[UserResponse]

A list of all users.

Source code in src/zenml/zen_stores/rest_zen_store.py
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
def list_users(
    self,
    user_filter_model: UserFilter,
    hydrate: bool = False,
) -> Page[UserResponse]:
    """List all users.

    Args:
        user_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all users.
    """
    return self._list_paginated_resources(
        route=USERS,
        response_model=UserResponse,
        filter_model=user_filter_model,
        params={"hydrate": hydrate},
    )
post(path: str, body: BaseModel, params: Optional[Dict[str, Any]] = None, timeout: Optional[int] = None, **kwargs: Any) -> Json

Make a POST request to the given endpoint path.

Parameters:

Name Type Description Default
path str

The path to the endpoint.

required
body BaseModel

The body to send.

required
params Optional[Dict[str, Any]]

The query parameters to pass to the endpoint.

None
timeout Optional[int]

The request timeout in seconds.

None
kwargs Any

Additional keyword arguments to pass to the request.

{}

Returns:

Type Description
Json

The response body.

Source code in src/zenml/zen_stores/rest_zen_store.py
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
def post(
    self,
    path: str,
    body: BaseModel,
    params: Optional[Dict[str, Any]] = None,
    timeout: Optional[int] = None,
    **kwargs: Any,
) -> Json:
    """Make a POST request to the given endpoint path.

    Args:
        path: The path to the endpoint.
        body: The body to send.
        params: The query parameters to pass to the endpoint.
        timeout: The request timeout in seconds.
        kwargs: Additional keyword arguments to pass to the request.

    Returns:
        The response body.
    """
    logger.debug(f"Sending POST request to {path}...")
    return self._request(
        "POST",
        self.url + API + VERSION_1 + path,
        json=body.model_dump(mode="json"),
        params=params,
        timeout=timeout,
        **kwargs,
    )
prune_artifact_versions(project_name_or_id: Union[str, UUID], only_versions: bool = True) -> None

Prunes unused artifact versions and their artifacts.

Parameters:

Name Type Description Default
project_name_or_id Union[str, UUID]

The project name or ID to prune artifact versions for.

required
only_versions bool

Only delete artifact versions, keeping artifacts

True
Source code in src/zenml/zen_stores/rest_zen_store.py
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
def prune_artifact_versions(
    self,
    project_name_or_id: Union[str, UUID],
    only_versions: bool = True,
) -> None:
    """Prunes unused artifact versions and their artifacts.

    Args:
        project_name_or_id: The project name or ID to prune artifact
            versions for.
        only_versions: Only delete artifact versions, keeping artifacts
    """
    self.delete(
        path=ARTIFACT_VERSIONS,
        params={
            "only_versions": only_versions,
            "project_name_or_id": project_name_or_id,
        },
    )
put(path: str, body: Optional[BaseModel] = None, params: Optional[Dict[str, Any]] = None, timeout: Optional[int] = None, **kwargs: Any) -> Json

Make a PUT request to the given endpoint path.

Parameters:

Name Type Description Default
path str

The path to the endpoint.

required
body Optional[BaseModel]

The body to send.

None
params Optional[Dict[str, Any]]

The query parameters to pass to the endpoint.

None
timeout Optional[int]

The request timeout in seconds.

None
kwargs Any

Additional keyword arguments to pass to the request.

{}

Returns:

Type Description
Json

The response body.

Source code in src/zenml/zen_stores/rest_zen_store.py
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
def put(
    self,
    path: str,
    body: Optional[BaseModel] = None,
    params: Optional[Dict[str, Any]] = None,
    timeout: Optional[int] = None,
    **kwargs: Any,
) -> Json:
    """Make a PUT request to the given endpoint path.

    Args:
        path: The path to the endpoint.
        body: The body to send.
        params: The query parameters to pass to the endpoint.
        timeout: The request timeout in seconds.
        kwargs: Additional keyword arguments to pass to the request.

    Returns:
        The response body.
    """
    logger.debug(f"Sending PUT request to {path}...")
    json = (
        body.model_dump(mode="json", exclude_unset=True) if body else None
    )
    return self._request(
        "PUT",
        self.url + API + VERSION_1 + path,
        json=json,
        params=params,
        timeout=timeout,
        **kwargs,
    )
restore_secrets(ignore_errors: bool = False, delete_secrets: bool = False) -> None

Restore all secrets from the configured backup secrets store.

Parameters:

Name Type Description Default
ignore_errors bool

Whether to ignore individual errors during the restore process and attempt to restore all secrets.

False
delete_secrets bool

Whether to delete the secrets that have been successfully restored from the backup secrets store. Setting this flag effectively moves all secrets from the backup secrets store to the primary secrets store.

False
Source code in src/zenml/zen_stores/rest_zen_store.py
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
def restore_secrets(
    self, ignore_errors: bool = False, delete_secrets: bool = False
) -> None:
    """Restore all secrets from the configured backup secrets store.

    Args:
        ignore_errors: Whether to ignore individual errors during the
            restore process and attempt to restore all secrets.
        delete_secrets: Whether to delete the secrets that have been
            successfully restored from the backup secrets store. Setting
            this flag effectively moves all secrets from the backup secrets
            store to the primary secrets store.
    """
    params: Dict[str, Any] = {
        "ignore_errors": ignore_errors,
        "delete_secrets": delete_secrets,
    }
    self.put(
        f"{SECRETS_OPERATIONS}{SECRETS_RESTORE}",
        params=params,
    )
rotate_api_key(service_account_id: UUID, api_key_name_or_id: Union[str, UUID], rotate_request: APIKeyRotateRequest) -> APIKeyResponse

Rotate an API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to rotate the API key.

required
api_key_name_or_id Union[str, UUID]

The name or ID of the API key to rotate.

required
rotate_request APIKeyRotateRequest

The rotate request on the API key.

required

Returns:

Type Description
APIKeyResponse

The updated API key.

Source code in src/zenml/zen_stores/rest_zen_store.py
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
def rotate_api_key(
    self,
    service_account_id: UUID,
    api_key_name_or_id: Union[str, UUID],
    rotate_request: APIKeyRotateRequest,
) -> APIKeyResponse:
    """Rotate an API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to
            rotate the API key.
        api_key_name_or_id: The name or ID of the API key to rotate.
        rotate_request: The rotate request on the API key.

    Returns:
        The updated API key.
    """
    response_body = self.put(
        f"{SERVICE_ACCOUNTS}/{str(service_account_id)}{API_KEYS}/{str(api_key_name_or_id)}{API_KEY_ROTATE}",
        body=rotate_request,
    )
    return APIKeyResponse.model_validate(response_body)
run_template(template_id: UUID, run_configuration: Optional[PipelineRunConfiguration] = None) -> PipelineRunResponse

Run a template.

Parameters:

Name Type Description Default
template_id UUID

The ID of the template to run.

required
run_configuration Optional[PipelineRunConfiguration]

Configuration for the run.

None

Raises:

Type Description
RuntimeError

If the server does not support running a template.

Returns:

Type Description
PipelineRunResponse

Model of the pipeline run.

Source code in src/zenml/zen_stores/rest_zen_store.py
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
def run_template(
    self,
    template_id: UUID,
    run_configuration: Optional[PipelineRunConfiguration] = None,
) -> PipelineRunResponse:
    """Run a template.

    Args:
        template_id: The ID of the template to run.
        run_configuration: Configuration for the run.

    Raises:
        RuntimeError: If the server does not support running a template.

    Returns:
        Model of the pipeline run.
    """
    run_configuration = run_configuration or PipelineRunConfiguration()

    try:
        response_body = self.post(
            f"{RUN_TEMPLATES}/{template_id}/runs",
            body=run_configuration,
        )
    except MethodNotAllowedError as e:
        raise RuntimeError(
            "Running a template is not supported for this server."
        ) from e

    return PipelineRunResponse.model_validate(response_body)
update_action(action_id: UUID, action_update: ActionUpdate) -> ActionResponse

Update an existing action.

Parameters:

Name Type Description Default
action_id UUID

The ID of the action to update.

required
action_update ActionUpdate

The update to be applied to the action.

required

Returns:

Type Description
ActionResponse

The updated action.

Source code in src/zenml/zen_stores/rest_zen_store.py
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
def update_action(
    self,
    action_id: UUID,
    action_update: ActionUpdate,
) -> ActionResponse:
    """Update an existing action.

    Args:
        action_id: The ID of the action to update.
        action_update: The update to be applied to the action.

    Returns:
        The updated action.
    """
    return self._update_resource(
        resource_id=action_id,
        resource_update=action_update,
        route=ACTIONS,
        response_model=ActionResponse,
    )
update_api_key(service_account_id: UUID, api_key_name_or_id: Union[str, UUID], api_key_update: APIKeyUpdate) -> APIKeyResponse

Update an API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to update the API key.

required
api_key_name_or_id Union[str, UUID]

The name or ID of the API key to update.

required
api_key_update APIKeyUpdate

The update request on the API key.

required

Returns:

Type Description
APIKeyResponse

The updated API key.

Source code in src/zenml/zen_stores/rest_zen_store.py
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
def update_api_key(
    self,
    service_account_id: UUID,
    api_key_name_or_id: Union[str, UUID],
    api_key_update: APIKeyUpdate,
) -> APIKeyResponse:
    """Update an API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to
            update the API key.
        api_key_name_or_id: The name or ID of the API key to update.
        api_key_update: The update request on the API key.

    Returns:
        The updated API key.
    """
    return self._update_resource(
        resource_id=api_key_name_or_id,
        resource_update=api_key_update,
        route=f"{SERVICE_ACCOUNTS}/{str(service_account_id)}{API_KEYS}",
        response_model=APIKeyResponse,
    )
update_artifact(artifact_id: UUID, artifact_update: ArtifactUpdate) -> ArtifactResponse

Updates an artifact.

Parameters:

Name Type Description Default
artifact_id UUID

The ID of the artifact to update.

required
artifact_update ArtifactUpdate

The update to be applied to the artifact.

required

Returns:

Type Description
ArtifactResponse

The updated artifact.

Source code in src/zenml/zen_stores/rest_zen_store.py
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
def update_artifact(
    self, artifact_id: UUID, artifact_update: ArtifactUpdate
) -> ArtifactResponse:
    """Updates an artifact.

    Args:
        artifact_id: The ID of the artifact to update.
        artifact_update: The update to be applied to the artifact.

    Returns:
        The updated artifact.
    """
    return self._update_resource(
        resource_id=artifact_id,
        resource_update=artifact_update,
        response_model=ArtifactResponse,
        route=ARTIFACTS,
    )
update_artifact_version(artifact_version_id: UUID, artifact_version_update: ArtifactVersionUpdate) -> ArtifactVersionResponse

Updates an artifact version.

Parameters:

Name Type Description Default
artifact_version_id UUID

The ID of the artifact version to update.

required
artifact_version_update ArtifactVersionUpdate

The update to be applied to the artifact version.

required

Returns:

Type Description
ArtifactVersionResponse

The updated artifact version.

Source code in src/zenml/zen_stores/rest_zen_store.py
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
def update_artifact_version(
    self,
    artifact_version_id: UUID,
    artifact_version_update: ArtifactVersionUpdate,
) -> ArtifactVersionResponse:
    """Updates an artifact version.

    Args:
        artifact_version_id: The ID of the artifact version to update.
        artifact_version_update: The update to be applied to the artifact
            version.

    Returns:
        The updated artifact version.
    """
    return self._update_resource(
        resource_id=artifact_version_id,
        resource_update=artifact_version_update,
        response_model=ArtifactVersionResponse,
        route=ARTIFACT_VERSIONS,
    )
update_authorized_device(device_id: UUID, update: OAuthDeviceUpdate) -> OAuthDeviceResponse

Updates an existing OAuth 2.0 authorized device for internal use.

Parameters:

Name Type Description Default
device_id UUID

The ID of the device to update.

required
update OAuthDeviceUpdate

The update to be applied to the device.

required

Returns:

Type Description
OAuthDeviceResponse

The updated OAuth 2.0 authorized device.

Source code in src/zenml/zen_stores/rest_zen_store.py
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
def update_authorized_device(
    self, device_id: UUID, update: OAuthDeviceUpdate
) -> OAuthDeviceResponse:
    """Updates an existing OAuth 2.0 authorized device for internal use.

    Args:
        device_id: The ID of the device to update.
        update: The update to be applied to the device.

    Returns:
        The updated OAuth 2.0 authorized device.
    """
    return self._update_resource(
        resource_id=device_id,
        resource_update=update,
        response_model=OAuthDeviceResponse,
        route=DEVICES,
    )
update_code_repository(code_repository_id: UUID, update: CodeRepositoryUpdate) -> CodeRepositoryResponse

Updates an existing code repository.

Parameters:

Name Type Description Default
code_repository_id UUID

The ID of the code repository to update.

required
update CodeRepositoryUpdate

The update to be applied to the code repository.

required

Returns:

Type Description
CodeRepositoryResponse

The updated code repository.

Source code in src/zenml/zen_stores/rest_zen_store.py
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
def update_code_repository(
    self, code_repository_id: UUID, update: CodeRepositoryUpdate
) -> CodeRepositoryResponse:
    """Updates an existing code repository.

    Args:
        code_repository_id: The ID of the code repository to update.
        update: The update to be applied to the code repository.

    Returns:
        The updated code repository.
    """
    return self._update_resource(
        resource_id=code_repository_id,
        resource_update=update,
        response_model=CodeRepositoryResponse,
        route=CODE_REPOSITORIES,
    )
update_event_source(event_source_id: UUID, event_source_update: EventSourceUpdate) -> EventSourceResponse

Update an existing event_source.

Parameters:

Name Type Description Default
event_source_id UUID

The ID of the event_source to update.

required
event_source_update EventSourceUpdate

The update to be applied to the event_source.

required

Returns:

Type Description
EventSourceResponse

The updated event_source.

Source code in src/zenml/zen_stores/rest_zen_store.py
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
def update_event_source(
    self,
    event_source_id: UUID,
    event_source_update: EventSourceUpdate,
) -> EventSourceResponse:
    """Update an existing event_source.

    Args:
        event_source_id: The ID of the event_source to update.
        event_source_update: The update to be applied to the event_source.

    Returns:
        The updated event_source.
    """
    return self._update_resource(
        resource_id=event_source_id,
        resource_update=event_source_update,
        route=EVENT_SOURCES,
        response_model=EventSourceResponse,
    )
update_flavor(flavor_id: UUID, flavor_update: FlavorUpdate) -> FlavorResponse

Updates an existing user.

Parameters:

Name Type Description Default
flavor_id UUID

The id of the flavor to update.

required
flavor_update FlavorUpdate

The update to be applied to the flavor.

required

Returns:

Type Description
FlavorResponse

The updated flavor.

Source code in src/zenml/zen_stores/rest_zen_store.py
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
def update_flavor(
    self, flavor_id: UUID, flavor_update: FlavorUpdate
) -> FlavorResponse:
    """Updates an existing user.

    Args:
        flavor_id: The id of the flavor to update.
        flavor_update: The update to be applied to the flavor.

    Returns:
        The updated flavor.
    """
    return self._update_resource(
        resource_id=flavor_id,
        resource_update=flavor_update,
        route=FLAVORS,
        response_model=FlavorResponse,
    )
update_model(model_id: UUID, model_update: ModelUpdate) -> ModelResponse

Updates an existing model.

Parameters:

Name Type Description Default
model_id UUID

UUID of the model to be updated.

required
model_update ModelUpdate

the Model to be updated.

required

Returns:

Type Description
ModelResponse

The updated model.

Source code in src/zenml/zen_stores/rest_zen_store.py
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
def update_model(
    self,
    model_id: UUID,
    model_update: ModelUpdate,
) -> ModelResponse:
    """Updates an existing model.

    Args:
        model_id: UUID of the model to be updated.
        model_update: the Model to be updated.

    Returns:
        The updated model.
    """
    return self._update_resource(
        resource_id=model_id,
        resource_update=model_update,
        route=MODELS,
        response_model=ModelResponse,
    )
update_model_version(model_version_id: UUID, model_version_update_model: ModelVersionUpdate) -> ModelVersionResponse

Get all model versions by filter.

Parameters:

Name Type Description Default
model_version_id UUID

The ID of model version to be updated.

required
model_version_update_model ModelVersionUpdate

The model version to be updated.

required

Returns:

Type Description
ModelVersionResponse

An updated model version.

Source code in src/zenml/zen_stores/rest_zen_store.py
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
def update_model_version(
    self,
    model_version_id: UUID,
    model_version_update_model: ModelVersionUpdate,
) -> ModelVersionResponse:
    """Get all model versions by filter.

    Args:
        model_version_id: The ID of model version to be updated.
        model_version_update_model: The model version to be updated.

    Returns:
        An updated model version.

    """
    return self._update_resource(
        resource_id=model_version_id,
        resource_update=model_version_update_model,
        route=MODEL_VERSIONS,
        response_model=ModelVersionResponse,
    )
update_pipeline(pipeline_id: UUID, pipeline_update: PipelineUpdate) -> PipelineResponse

Updates a pipeline.

Parameters:

Name Type Description Default
pipeline_id UUID

The ID of the pipeline to be updated.

required
pipeline_update PipelineUpdate

The update to be applied.

required

Returns:

Type Description
PipelineResponse

The updated pipeline.

Source code in src/zenml/zen_stores/rest_zen_store.py
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
def update_pipeline(
    self, pipeline_id: UUID, pipeline_update: PipelineUpdate
) -> PipelineResponse:
    """Updates a pipeline.

    Args:
        pipeline_id: The ID of the pipeline to be updated.
        pipeline_update: The update to be applied.

    Returns:
        The updated pipeline.
    """
    return self._update_resource(
        resource_id=pipeline_id,
        resource_update=pipeline_update,
        route=PIPELINES,
        response_model=PipelineResponse,
    )
update_project(project_id: UUID, project_update: ProjectUpdate) -> ProjectResponse

Update an existing project.

Parameters:

Name Type Description Default
project_id UUID

The ID of the project to be updated.

required
project_update ProjectUpdate

The update to be applied to the project.

required

Returns:

Type Description
ProjectResponse

The updated project.

Source code in src/zenml/zen_stores/rest_zen_store.py
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
def update_project(
    self, project_id: UUID, project_update: ProjectUpdate
) -> ProjectResponse:
    """Update an existing project.

    Args:
        project_id: The ID of the project to be updated.
        project_update: The update to be applied to the project.

    Returns:
        The updated project.
    """
    return self._update_resource(
        resource_id=project_id,
        resource_update=project_update,
        route=PROJECTS,
        response_model=ProjectResponse,
    )
update_run(run_id: UUID, run_update: PipelineRunUpdate) -> PipelineRunResponse

Updates a pipeline run.

Parameters:

Name Type Description Default
run_id UUID

The ID of the pipeline run to update.

required
run_update PipelineRunUpdate

The update to be applied to the pipeline run.

required

Returns:

Type Description
PipelineRunResponse

The updated pipeline run.

Source code in src/zenml/zen_stores/rest_zen_store.py
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
def update_run(
    self, run_id: UUID, run_update: PipelineRunUpdate
) -> PipelineRunResponse:
    """Updates a pipeline run.

    Args:
        run_id: The ID of the pipeline run to update.
        run_update: The update to be applied to the pipeline run.


    Returns:
        The updated pipeline run.
    """
    return self._update_resource(
        resource_id=run_id,
        resource_update=run_update,
        response_model=PipelineRunResponse,
        route=RUNS,
    )
update_run_step(step_run_id: UUID, step_run_update: StepRunUpdate) -> StepRunResponse

Updates a step run.

Parameters:

Name Type Description Default
step_run_id UUID

The ID of the step to update.

required
step_run_update StepRunUpdate

The update to be applied to the step.

required

Returns:

Type Description
StepRunResponse

The updated step run.

Source code in src/zenml/zen_stores/rest_zen_store.py
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
def update_run_step(
    self,
    step_run_id: UUID,
    step_run_update: StepRunUpdate,
) -> StepRunResponse:
    """Updates a step run.

    Args:
        step_run_id: The ID of the step to update.
        step_run_update: The update to be applied to the step.

    Returns:
        The updated step run.
    """
    return self._update_resource(
        resource_id=step_run_id,
        resource_update=step_run_update,
        response_model=StepRunResponse,
        route=STEPS,
    )
update_run_template(template_id: UUID, template_update: RunTemplateUpdate) -> RunTemplateResponse

Updates a run template.

Parameters:

Name Type Description Default
template_id UUID

The ID of the template to update.

required
template_update RunTemplateUpdate

The update to apply.

required

Returns:

Type Description
RunTemplateResponse

The updated template.

Source code in src/zenml/zen_stores/rest_zen_store.py
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
def update_run_template(
    self,
    template_id: UUID,
    template_update: RunTemplateUpdate,
) -> RunTemplateResponse:
    """Updates a run template.

    Args:
        template_id: The ID of the template to update.
        template_update: The update to apply.

    Returns:
        The updated template.
    """
    return self._update_resource(
        resource_id=template_id,
        resource_update=template_update,
        route=RUN_TEMPLATES,
        response_model=RunTemplateResponse,
    )
update_schedule(schedule_id: UUID, schedule_update: ScheduleUpdate) -> ScheduleResponse

Updates a schedule.

Parameters:

Name Type Description Default
schedule_id UUID

The ID of the schedule to be updated.

required
schedule_update ScheduleUpdate

The update to be applied.

required

Returns:

Type Description
ScheduleResponse

The updated schedule.

Source code in src/zenml/zen_stores/rest_zen_store.py
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
def update_schedule(
    self,
    schedule_id: UUID,
    schedule_update: ScheduleUpdate,
) -> ScheduleResponse:
    """Updates a schedule.

    Args:
        schedule_id: The ID of the schedule to be updated.
        schedule_update: The update to be applied.

    Returns:
        The updated schedule.
    """
    return self._update_resource(
        resource_id=schedule_id,
        resource_update=schedule_update,
        route=SCHEDULES,
        response_model=ScheduleResponse,
    )
update_secret(secret_id: UUID, secret_update: SecretUpdate) -> SecretResponse

Updates a secret.

Secret values that are specified as None in the update that are present in the existing secret are removed from the existing secret. Values that are present in both secrets are overwritten. All other values in both the existing secret and the update are kept (merged).

If the update includes a change of name or scope, the scoping rules enforced in the secrets store are used to validate the update:

  • only one private secret with the given name can exist.
  • only one public secret with the given name can exist.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret to be updated.

required
secret_update SecretUpdate

The update to be applied.

required

Returns:

Type Description
SecretResponse

The updated secret.

Source code in src/zenml/zen_stores/rest_zen_store.py
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
def update_secret(
    self, secret_id: UUID, secret_update: SecretUpdate
) -> SecretResponse:
    """Updates a secret.

    Secret values that are specified as `None` in the update that are
    present in the existing secret are removed from the existing secret.
    Values that are present in both secrets are overwritten. All other
    values in both the existing secret and the update are kept (merged).

    If the update includes a change of name or scope, the scoping rules
    enforced in the secrets store are used to validate the update:

      - only one private secret with the given name can exist.
      - only one public secret with the given name can exist.

    Args:
        secret_id: The ID of the secret to be updated.
        secret_update: The update to be applied.

    Returns:
        The updated secret.
    """
    return self._update_resource(
        resource_id=secret_id,
        resource_update=secret_update,
        route=SECRETS,
        response_model=SecretResponse,
        # The default endpoint behavior is to replace all secret values
        # with the values in the update. We want to merge the values
        # instead.
        params=dict(patch_values=True),
    )
update_server_settings(settings_update: ServerSettingsUpdate) -> ServerSettingsResponse

Update the server settings.

Parameters:

Name Type Description Default
settings_update ServerSettingsUpdate

The server settings update.

required

Returns:

Type Description
ServerSettingsResponse

The updated server settings.

Source code in src/zenml/zen_stores/rest_zen_store.py
560
561
562
563
564
565
566
567
568
569
570
571
572
def update_server_settings(
    self, settings_update: ServerSettingsUpdate
) -> ServerSettingsResponse:
    """Update the server settings.

    Args:
        settings_update: The server settings update.

    Returns:
        The updated server settings.
    """
    response_body = self.put(SERVER_SETTINGS, body=settings_update)
    return ServerSettingsResponse.model_validate(response_body)
update_service(service_id: UUID, update: ServiceUpdate) -> ServiceResponse

Update a service.

Parameters:

Name Type Description Default
service_id UUID

The ID of the service to update.

required
update ServiceUpdate

The update to be applied to the service.

required

Returns:

Type Description
ServiceResponse

The updated service.

Source code in src/zenml/zen_stores/rest_zen_store.py
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
def update_service(
    self, service_id: UUID, update: ServiceUpdate
) -> ServiceResponse:
    """Update a service.

    Args:
        service_id: The ID of the service to update.
        update: The update to be applied to the service.

    Returns:
        The updated service.
    """
    return self._update_resource(
        resource_id=service_id,
        resource_update=update,
        response_model=ServiceResponse,
        route=SERVICES,
    )
update_service_account(service_account_name_or_id: Union[str, UUID], service_account_update: ServiceAccountUpdate) -> ServiceAccountResponse

Updates an existing service account.

Parameters:

Name Type Description Default
service_account_name_or_id Union[str, UUID]

The name or the ID of the service account to update.

required
service_account_update ServiceAccountUpdate

The update to be applied to the service account.

required

Returns:

Type Description
ServiceAccountResponse

The updated service account.

Source code in src/zenml/zen_stores/rest_zen_store.py
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
def update_service_account(
    self,
    service_account_name_or_id: Union[str, UUID],
    service_account_update: ServiceAccountUpdate,
) -> ServiceAccountResponse:
    """Updates an existing service account.

    Args:
        service_account_name_or_id: The name or the ID of the service
            account to update.
        service_account_update: The update to be applied to the service
            account.

    Returns:
        The updated service account.
    """
    return self._update_resource(
        resource_id=service_account_name_or_id,
        resource_update=service_account_update,
        route=SERVICE_ACCOUNTS,
        response_model=ServiceAccountResponse,
    )
update_service_connector(service_connector_id: UUID, update: ServiceConnectorUpdate) -> ServiceConnectorResponse

Updates an existing service connector.

The update model contains the fields to be updated. If a field value is set to None in the model, the field is not updated, but there are special rules concerning some fields:

  • the configuration and secrets fields together represent a full valid configuration update, not just a partial update. If either is set (i.e. not None) in the update, their values are merged together and will replace the existing configuration and secrets values.
  • the resource_id field value is also a full replacement value: if set to None, the resource ID is removed from the service connector.
  • the expiration_seconds field value is also a full replacement value: if set to None, the expiration is removed from the service connector.
  • the secret_id field value in the update is ignored, given that secrets are managed internally by the ZenML store.
  • the labels field is also a full labels update: if set (i.e. not None), all existing labels are removed and replaced by the new labels in the update.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the service connector to update.

required
update ServiceConnectorUpdate

The update to be applied to the service connector.

required

Returns:

Type Description
ServiceConnectorResponse

The updated service connector.

Source code in src/zenml/zen_stores/rest_zen_store.py
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
def update_service_connector(
    self, service_connector_id: UUID, update: ServiceConnectorUpdate
) -> ServiceConnectorResponse:
    """Updates an existing service connector.

    The update model contains the fields to be updated. If a field value is
    set to None in the model, the field is not updated, but there are
    special rules concerning some fields:

    * the `configuration` and `secrets` fields together represent a full
    valid configuration update, not just a partial update. If either is
    set (i.e. not None) in the update, their values are merged together and
    will replace the existing configuration and secrets values.
    * the `resource_id` field value is also a full replacement value: if set
    to `None`, the resource ID is removed from the service connector.
    * the `expiration_seconds` field value is also a full replacement value:
    if set to `None`, the expiration is removed from the service connector.
    * the `secret_id` field value in the update is ignored, given that
    secrets are managed internally by the ZenML store.
    * the `labels` field is also a full labels update: if set (i.e. not
    `None`), all existing labels are removed and replaced by the new labels
    in the update.

    Args:
        service_connector_id: The ID of the service connector to update.
        update: The update to be applied to the service connector.

    Returns:
        The updated service connector.
    """
    connector_model = self._update_resource(
        resource_id=service_connector_id,
        resource_update=update,
        response_model=ServiceConnectorResponse,
        route=SERVICE_CONNECTORS,
    )
    self._populate_connector_type(connector_model)
    return connector_model
update_stack(stack_id: UUID, stack_update: StackUpdate) -> StackResponse

Update a stack.

Parameters:

Name Type Description Default
stack_id UUID

The ID of the stack update.

required
stack_update StackUpdate

The update request on the stack.

required

Returns:

Type Description
StackResponse

The updated stack.

Source code in src/zenml/zen_stores/rest_zen_store.py
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
def update_stack(
    self, stack_id: UUID, stack_update: StackUpdate
) -> StackResponse:
    """Update a stack.

    Args:
        stack_id: The ID of the stack update.
        stack_update: The update request on the stack.

    Returns:
        The updated stack.
    """
    return self._update_resource(
        resource_id=stack_id,
        resource_update=stack_update,
        route=STACKS,
        response_model=StackResponse,
    )
update_stack_component(component_id: UUID, component_update: ComponentUpdate) -> ComponentResponse

Update an existing stack component.

Parameters:

Name Type Description Default
component_id UUID

The ID of the stack component to update.

required
component_update ComponentUpdate

The update to be applied to the stack component.

required

Returns:

Type Description
ComponentResponse

The updated stack component.

Source code in src/zenml/zen_stores/rest_zen_store.py
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
def update_stack_component(
    self,
    component_id: UUID,
    component_update: ComponentUpdate,
) -> ComponentResponse:
    """Update an existing stack component.

    Args:
        component_id: The ID of the stack component to update.
        component_update: The update to be applied to the stack component.

    Returns:
        The updated stack component.
    """
    return self._update_resource(
        resource_id=component_id,
        resource_update=component_update,
        route=STACK_COMPONENTS,
        response_model=ComponentResponse,
    )
update_tag(tag_name_or_id: Union[str, UUID], tag_update_model: TagUpdate) -> TagResponse

Update tag.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

name or id of the tag to be updated.

required
tag_update_model TagUpdate

Tag to use for the update.

required

Returns:

Type Description
TagResponse

An updated tag.

Source code in src/zenml/zen_stores/rest_zen_store.py
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
def update_tag(
    self,
    tag_name_or_id: Union[str, UUID],
    tag_update_model: TagUpdate,
) -> TagResponse:
    """Update tag.

    Args:
        tag_name_or_id: name or id of the tag to be updated.
        tag_update_model: Tag to use for the update.

    Returns:
        An updated tag.
    """
    tag = self.get_tag(tag_name_or_id)
    return self._update_resource(
        resource_id=tag.id,
        resource_update=tag_update_model,
        route=TAGS,
        response_model=TagResponse,
    )
update_trigger(trigger_id: UUID, trigger_update: TriggerUpdate) -> TriggerResponse

Update an existing trigger.

Parameters:

Name Type Description Default
trigger_id UUID

The ID of the trigger to update.

required
trigger_update TriggerUpdate

The update to be applied to the trigger.

required

Returns:

Type Description
TriggerResponse

The updated trigger.

Source code in src/zenml/zen_stores/rest_zen_store.py
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
def update_trigger(
    self,
    trigger_id: UUID,
    trigger_update: TriggerUpdate,
) -> TriggerResponse:
    """Update an existing trigger.

    Args:
        trigger_id: The ID of the trigger to update.
        trigger_update: The update to be applied to the trigger.

    Returns:
        The updated trigger.
    """
    return self._update_resource(
        resource_id=trigger_id,
        resource_update=trigger_update,
        route=TRIGGERS,
        response_model=TriggerResponse,
    )
update_user(user_id: UUID, user_update: UserUpdate) -> UserResponse

Updates an existing user.

Parameters:

Name Type Description Default
user_id UUID

The id of the user to update.

required
user_update UserUpdate

The update to be applied to the user.

required

Returns:

Type Description
UserResponse

The updated user.

Source code in src/zenml/zen_stores/rest_zen_store.py
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
def update_user(
    self, user_id: UUID, user_update: UserUpdate
) -> UserResponse:
    """Updates an existing user.

    Args:
        user_id: The id of the user to update.
        user_update: The update to be applied to the user.

    Returns:
        The updated user.
    """
    return self._update_resource(
        resource_id=user_id,
        resource_update=user_update,
        route=USERS,
        response_model=UserResponse,
    )
verify_service_connector(service_connector_id: UUID, resource_type: Optional[str] = None, resource_id: Optional[str] = None, list_resources: bool = True) -> ServiceConnectorResourcesModel

Verifies if a service connector instance has access to one or more resources.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the service connector to verify.

required
resource_type Optional[str]

The type of resource to verify access to.

None
resource_id Optional[str]

The ID of the resource to verify access to.

None
list_resources bool

If True, the list of all resources accessible through the service connector and matching the supplied resource type and ID are returned.

True

Returns:

Type Description
ServiceConnectorResourcesModel

The list of resources that the service connector has access to,

ServiceConnectorResourcesModel

scoped to the supplied resource type and ID, if provided.

Source code in src/zenml/zen_stores/rest_zen_store.py
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
def verify_service_connector(
    self,
    service_connector_id: UUID,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    list_resources: bool = True,
) -> ServiceConnectorResourcesModel:
    """Verifies if a service connector instance has access to one or more resources.

    Args:
        service_connector_id: The ID of the service connector to verify.
        resource_type: The type of resource to verify access to.
        resource_id: The ID of the resource to verify access to.
        list_resources: If True, the list of all resources accessible
            through the service connector and matching the supplied resource
            type and ID are returned.

    Returns:
        The list of resources that the service connector has access to,
        scoped to the supplied resource type and ID, if provided.
    """
    params: Dict[str, Any] = {"list_resources": list_resources}
    if resource_type:
        params["resource_type"] = resource_type
    if resource_id:
        params["resource_id"] = resource_id
    response_body = self.put(
        f"{SERVICE_CONNECTORS}/{str(service_connector_id)}{SERVICE_CONNECTOR_VERIFY}",
        params=params,
        timeout=max(
            self.config.http_timeout,
            SERVICE_CONNECTOR_VERIFY_REQUEST_TIMEOUT,
        ),
    )

    resources = ServiceConnectorResourcesModel.model_validate(
        response_body
    )
    self._populate_connector_type(resources)
    return resources
verify_service_connector_config(service_connector: ServiceConnectorRequest, list_resources: bool = True) -> ServiceConnectorResourcesModel

Verifies if a service connector configuration has access to resources.

Parameters:

Name Type Description Default
service_connector ServiceConnectorRequest

The service connector configuration to verify.

required
list_resources bool

If True, the list of all resources accessible through the service connector and matching the supplied resource type and ID are returned.

True

Returns:

Type Description
ServiceConnectorResourcesModel

The list of resources that the service connector configuration has

ServiceConnectorResourcesModel

access to.

Source code in src/zenml/zen_stores/rest_zen_store.py
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
def verify_service_connector_config(
    self,
    service_connector: ServiceConnectorRequest,
    list_resources: bool = True,
) -> ServiceConnectorResourcesModel:
    """Verifies if a service connector configuration has access to resources.

    Args:
        service_connector: The service connector configuration to verify.
        list_resources: If True, the list of all resources accessible
            through the service connector and matching the supplied resource
            type and ID are returned.

    Returns:
        The list of resources that the service connector configuration has
        access to.
    """
    response_body = self.post(
        f"{SERVICE_CONNECTORS}{SERVICE_CONNECTOR_VERIFY}",
        body=service_connector,
        params={"list_resources": list_resources},
        timeout=max(
            self.config.http_timeout,
            SERVICE_CONNECTOR_VERIFY_REQUEST_TIMEOUT,
        ),
    )

    resources = ServiceConnectorResourcesModel.model_validate(
        response_body
    )
    self._populate_connector_type(resources)
    return resources
RestZenStoreConfiguration

Bases: StoreConfiguration

REST ZenML store configuration.

Attributes:

Name Type Description
type StoreType

The type of the store.

username StoreType

The username to use to connect to the Zen server.

password StoreType

The password to use to connect to the Zen server.

api_key StoreType

The service account API key to use to connect to the Zen server. This is only set if the API key is configured explicitly via environment variables or the ZenML global configuration file. API keys configured via the CLI are stored in the credentials store instead.

verify_ssl Union[bool, str]

Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use or the CA bundle value itself.

http_timeout int

The timeout to use for all requests.

Functions
supports_url_scheme(url: str) -> bool classmethod

Check if a URL scheme is supported by this store.

Parameters:

Name Type Description Default
url str

The URL to check.

required

Returns:

Type Description
bool

True if the URL scheme is supported, False otherwise.

Source code in src/zenml/zen_stores/rest_zen_store.py
377
378
379
380
381
382
383
384
385
386
387
@classmethod
def supports_url_scheme(cls, url: str) -> bool:
    """Check if a URL scheme is supported by this store.

    Args:
        url: The URL to check.

    Returns:
        True if the URL scheme is supported, False otherwise.
    """
    return urlparse(url).scheme in ("http", "https")
validate_url(url: str) -> str classmethod

Validates that the URL is a well-formed REST store URL.

Parameters:

Name Type Description Default
url str

The URL to be validated.

required

Returns:

Type Description
str

The validated URL without trailing slashes.

Raises:

Type Description
ValueError

If the URL is not a well-formed REST store URL.

Source code in src/zenml/zen_stores/rest_zen_store.py
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
@field_validator("url")
@classmethod
def validate_url(cls, url: str) -> str:
    """Validates that the URL is a well-formed REST store URL.

    Args:
        url: The URL to be validated.

    Returns:
        The validated URL without trailing slashes.

    Raises:
        ValueError: If the URL is not a well-formed REST store URL.
    """
    url = url.rstrip("/")
    scheme = re.search("^([a-z0-9]+://)", url)
    if scheme is None or scheme.group() not in ("https://", "http://"):
        raise ValueError(
            "Invalid URL for REST store: {url}. Should be in the form "
            "https://hostname[:port] or http://hostname[:port]."
        )

    # When running inside a container, if the URL uses localhost, the
    # target service will not be available. We try to replace localhost
    # with one of the special Docker or K3D internal hostnames.
    url = replace_localhost_with_internal_hostname(url)

    return url
validate_verify_ssl(verify_ssl: Union[bool, str]) -> Union[bool, str] classmethod

Validates that the verify_ssl either points to a file or is a bool.

Parameters:

Name Type Description Default
verify_ssl Union[bool, str]

The verify_ssl value to be validated.

required

Returns:

Type Description
Union[bool, str]

The validated verify_ssl value.

Source code in src/zenml/zen_stores/rest_zen_store.py
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
@field_validator("verify_ssl")
@classmethod
def validate_verify_ssl(
    cls, verify_ssl: Union[bool, str]
) -> Union[bool, str]:
    """Validates that the verify_ssl either points to a file or is a bool.

    Args:
        verify_ssl: The verify_ssl value to be validated.

    Returns:
        The validated verify_ssl value.
    """
    secret_folder = Path(
        GlobalConfiguration().local_stores_path,
        "certificates",
    )
    if isinstance(verify_ssl, bool) or verify_ssl.startswith(
        str(secret_folder)
    ):
        return verify_ssl

    if os.path.isfile(verify_ssl):
        with open(verify_ssl, "r") as f:
            cert_content = f.read()

    fileio.makedirs(str(secret_folder))
    file_path = Path(secret_folder, "ca_bundle.pem")
    with os.fdopen(
        os.open(file_path, flags=os.O_RDWR | os.O_CREAT, mode=0o600), "w"
    ) as f:
        f.write(cert_content)

    return str(file_path)
Functions
Modules

schemas

SQL Model Implementations.

Classes
APIKeySchema

Bases: NamedSchema

SQL Model for API keys.

Functions
from_request(service_account_id: UUID, request: APIKeyRequest) -> Tuple[APIKeySchema, str] classmethod

Convert a APIKeyRequest to a APIKeySchema.

Parameters:

Name Type Description Default
service_account_id UUID

The service account id to associate the key with.

required
request APIKeyRequest

The request model to convert.

required

Returns:

Type Description
Tuple[APIKeySchema, str]

The converted schema and the un-hashed API key.

Source code in src/zenml/zen_stores/schemas/api_key_schemas.py
 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
@classmethod
def from_request(
    cls,
    service_account_id: UUID,
    request: APIKeyRequest,
) -> Tuple["APIKeySchema", str]:
    """Convert a `APIKeyRequest` to a `APIKeySchema`.

    Args:
        service_account_id: The service account id to associate the key
            with.
        request: The request model to convert.

    Returns:
        The converted schema and the un-hashed API key.
    """
    key = cls._generate_jwt_secret_key()
    hashed_key = cls._get_hashed_key(key)
    now = utc_now()
    return (
        cls(
            name=request.name,
            description=request.description or "",
            key=hashed_key,
            service_account_id=service_account_id,
            created=now,
            updated=now,
        ),
        key,
    )
internal_update(update: APIKeyInternalUpdate) -> APIKeySchema

Update an APIKeySchema with an APIKeyInternalUpdate.

The internal update can also update the last used timestamp.

Parameters:

Name Type Description Default
update APIKeyInternalUpdate

The update model.

required

Returns:

Type Description
APIKeySchema

The updated APIKeySchema.

Source code in src/zenml/zen_stores/schemas/api_key_schemas.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def internal_update(self, update: APIKeyInternalUpdate) -> "APIKeySchema":
    """Update an `APIKeySchema` with an `APIKeyInternalUpdate`.

    The internal update can also update the last used timestamp.

    Args:
        update: The update model.

    Returns:
        The updated `APIKeySchema`.
    """
    self.update(update)

    if update.update_last_login:
        self.last_login = self.updated

    return self
rotate(rotate_request: APIKeyRotateRequest) -> Tuple[APIKeySchema, str]

Rotate the key for an APIKeySchema.

Parameters:

Name Type Description Default
rotate_request APIKeyRotateRequest

The rotate request model.

required

Returns:

Type Description
Tuple[APIKeySchema, str]

The updated APIKeySchema and the new un-hashed key.

Source code in src/zenml/zen_stores/schemas/api_key_schemas.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def rotate(
    self,
    rotate_request: APIKeyRotateRequest,
) -> Tuple["APIKeySchema", str]:
    """Rotate the key for an `APIKeySchema`.

    Args:
        rotate_request: The rotate request model.

    Returns:
        The updated `APIKeySchema` and the new un-hashed key.
    """
    self.updated = utc_now()
    self.previous_key = self.key
    self.retain_period = rotate_request.retain_period_minutes
    new_key = self._generate_jwt_secret_key()
    self.key = self._get_hashed_key(new_key)
    self.last_rotated = self.updated

    return self, new_key
to_internal_model(include_metadata: bool = False, include_resources: bool = False) -> APIKeyInternalResponse

Convert a APIKeySchema to an APIKeyInternalResponse.

The internal response model includes the hashed key values.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False

Returns:

Type Description
APIKeyInternalResponse

The created APIKeyInternalResponse.

Source code in src/zenml/zen_stores/schemas/api_key_schemas.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
def to_internal_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
) -> APIKeyInternalResponse:
    """Convert a `APIKeySchema` to an `APIKeyInternalResponse`.

    The internal response model includes the hashed key values.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.

    Returns:
        The created APIKeyInternalResponse.
    """
    model = self.to_model(
        include_metadata=include_metadata,
        include_resources=include_resources,
    )
    model.get_body().key = self.key

    return APIKeyInternalResponse(
        id=self.id,
        name=self.name,
        previous_key=self.previous_key,
        body=model.body,
        metadata=model.metadata,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> APIKeyResponse

Convert a APIKeySchema to an APIKeyResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}
**kwargs Any

Keyword arguments to filter models.

{}

Returns:

Type Description
APIKeyResponse

The created APIKeyResponse.

Source code in src/zenml/zen_stores/schemas/api_key_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> APIKeyResponse:
    """Convert a `APIKeySchema` to an `APIKeyResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

        **kwargs: Keyword arguments to filter models.

    Returns:
        The created APIKeyResponse.
    """
    metadata = None
    if include_metadata:
        metadata = APIKeyResponseMetadata(
            description=self.description,
            retain_period_minutes=self.retain_period,
            last_login=self.last_login,
            last_rotated=self.last_rotated,
        )

    body = APIKeyResponseBody(
        created=self.created,
        updated=self.updated,
        active=self.active,
        service_account=self.service_account.to_service_account_model(),
    )

    return APIKeyResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(update: APIKeyUpdate) -> APIKeySchema

Update an APIKeySchema with an APIKeyUpdate.

Parameters:

Name Type Description Default
update APIKeyUpdate

The update model.

required

Returns:

Type Description
APIKeySchema

The updated APIKeySchema.

Source code in src/zenml/zen_stores/schemas/api_key_schemas.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def update(self, update: APIKeyUpdate) -> "APIKeySchema":
    """Update an `APIKeySchema` with an `APIKeyUpdate`.

    Args:
        update: The update model.

    Returns:
        The updated `APIKeySchema`.
    """
    for field, value in update.model_dump(exclude_none=True).items():
        if hasattr(self, field):
            setattr(self, field, value)

    self.updated = utc_now()
    return self
ActionSchema

Bases: NamedSchema

SQL Model for actions.

Functions
from_request(request: ActionRequest) -> ActionSchema classmethod

Convert a ActionRequest to a ActionSchema.

Parameters:

Name Type Description Default
request ActionRequest

The request model to convert.

required

Returns:

Type Description
ActionSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/action_schemas.py
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
@classmethod
def from_request(cls, request: "ActionRequest") -> "ActionSchema":
    """Convert a `ActionRequest` to a `ActionSchema`.

    Args:
        request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=request.name,
        project_id=request.project,
        user_id=request.user,
        configuration=base64.b64encode(
            json.dumps(
                request.configuration, default=pydantic_encoder
            ).encode("utf-8"),
        ),
        flavor=request.flavor,
        plugin_subtype=request.plugin_subtype,
        description=request.description,
        service_account_id=request.service_account_id,
        auth_window=request.auth_window,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ActionResponse

Converts the action schema to a model.

Parameters:

Name Type Description Default
include_metadata bool

Flag deciding whether to include the output model(s) metadata fields in the response.

False
include_resources bool

Flag deciding whether to include the output model(s) metadata fields in the response.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ActionResponse

The converted model.

Source code in src/zenml/zen_stores/schemas/action_schemas.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
191
192
193
194
195
196
197
198
199
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "ActionResponse":
    """Converts the action schema to a model.

    Args:
        include_metadata: Flag deciding whether to include the output model(s)
            metadata fields in the response.
        include_resources: Flag deciding whether to include the output model(s)
            metadata fields in the response.
        **kwargs: Keyword arguments to allow schema specific logic

    Returns:
        The converted model.
    """
    body = ActionResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        flavor=self.flavor,
        plugin_subtype=self.plugin_subtype,
    )
    metadata = None
    if include_metadata:
        metadata = ActionResponseMetadata(
            project=self.project.to_model(),
            configuration=json.loads(
                base64.b64decode(self.configuration).decode()
            ),
            description=self.description,
            auth_window=self.auth_window,
        )
    resources = None
    if include_resources:
        resources = ActionResponseResources(
            service_account=self.service_account.to_model(),
        )
    return ActionResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(action_update: ActionUpdate) -> ActionSchema

Updates a action schema with a action update model.

Parameters:

Name Type Description Default
action_update ActionUpdate

ActionUpdate to update the action with.

required

Returns:

Type Description
ActionSchema

The updated ActionSchema.

Source code in src/zenml/zen_stores/schemas/action_schemas.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def update(self, action_update: "ActionUpdate") -> "ActionSchema":
    """Updates a action schema with a action update model.

    Args:
        action_update: `ActionUpdate` to update the action with.

    Returns:
        The updated ActionSchema.
    """
    for field, value in action_update.dict(
        exclude_unset=True,
        exclude_none=True,
    ).items():
        if field == "configuration":
            self.configuration = base64.b64encode(
                json.dumps(
                    action_update.configuration, default=pydantic_encoder
                ).encode("utf-8")
            )
        else:
            setattr(self, field, value)

    self.updated = utc_now()
    return self
ArtifactSchema

Bases: NamedSchema

SQL Model for artifacts.

Attributes
latest_version: Optional[ArtifactVersionSchema] property

Fetch the latest version for this artifact.

Raises:

Type Description
RuntimeError

If no session for the schema exists.

Returns:

Type Description
Optional[ArtifactVersionSchema]

The latest version for this artifact.

Functions
from_request(artifact_request: ArtifactRequest) -> ArtifactSchema classmethod

Convert an ArtifactRequest to an ArtifactSchema.

Parameters:

Name Type Description Default
artifact_request ArtifactRequest

The request model to convert.

required

Returns:

Type Description
ArtifactSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/artifact_schemas.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
@classmethod
def from_request(
    cls,
    artifact_request: ArtifactRequest,
) -> "ArtifactSchema":
    """Convert an `ArtifactRequest` to an `ArtifactSchema`.

    Args:
        artifact_request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=artifact_request.name,
        has_custom_name=artifact_request.has_custom_name,
        project_id=artifact_request.project,
        user_id=artifact_request.user,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ArtifactResponse

Convert an ArtifactSchema to an ArtifactResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ArtifactResponse

The created ArtifactResponse.

Source code in src/zenml/zen_stores/schemas/artifact_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ArtifactResponse:
    """Convert an `ArtifactSchema` to an `ArtifactResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic



    Returns:
        The created `ArtifactResponse`.
    """
    latest_id, latest_name = None, None
    if latest_version := self.latest_version:
        latest_id = latest_version.id
        latest_name = latest_version.version

    # Create the body of the model
    body = ArtifactResponseBody(
        created=self.created,
        updated=self.updated,
        tags=[tag.to_model() for tag in self.tags],
        latest_version_name=latest_name,
        latest_version_id=latest_id,
        user=self.user.to_model() if self.user else None,
    )

    # Create the metadata of the model
    metadata = None
    if include_metadata:
        metadata = ArtifactResponseMetadata(
            has_custom_name=self.has_custom_name,
            project=self.project.to_model(),
        )

    return ArtifactResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(artifact_update: ArtifactUpdate) -> ArtifactSchema

Update an ArtifactSchema with an ArtifactUpdate.

Parameters:

Name Type Description Default
artifact_update ArtifactUpdate

The update model to apply.

required

Returns:

Type Description
ArtifactSchema

The updated ArtifactSchema.

Source code in src/zenml/zen_stores/schemas/artifact_schemas.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def update(self, artifact_update: ArtifactUpdate) -> "ArtifactSchema":
    """Update an `ArtifactSchema` with an `ArtifactUpdate`.

    Args:
        artifact_update: The update model to apply.

    Returns:
        The updated `ArtifactSchema`.
    """
    self.updated = utc_now()
    if artifact_update.name:
        self.name = artifact_update.name
        self.has_custom_name = True
    if artifact_update.has_custom_name is not None:
        self.has_custom_name = artifact_update.has_custom_name
    return self
ArtifactVersionSchema

Bases: BaseSchema, RunMetadataInterface

SQL Model for artifact versions.

Functions
from_request(artifact_version_request: ArtifactVersionRequest) -> ArtifactVersionSchema classmethod

Convert an ArtifactVersionRequest to an ArtifactVersionSchema.

Parameters:

Name Type Description Default
artifact_version_request ArtifactVersionRequest

The request model to convert.

required

Raises:

Type Description
ValueError

If the request does not specify a version number.

Returns:

Type Description
ArtifactVersionSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/artifact_schemas.py
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
@classmethod
def from_request(
    cls,
    artifact_version_request: ArtifactVersionRequest,
) -> "ArtifactVersionSchema":
    """Convert an `ArtifactVersionRequest` to an `ArtifactVersionSchema`.

    Args:
        artifact_version_request: The request model to convert.

    Raises:
        ValueError: If the request does not specify a version number.

    Returns:
        The converted schema.
    """
    if not artifact_version_request.version:
        raise ValueError("Missing version for artifact version request.")

    try:
        version_number = int(artifact_version_request.version)
    except ValueError:
        version_number = None
    return cls(
        artifact_id=artifact_version_request.artifact_id,
        version=str(artifact_version_request.version),
        version_number=version_number,
        artifact_store_id=artifact_version_request.artifact_store_id,
        project_id=artifact_version_request.project,
        user_id=artifact_version_request.user,
        type=artifact_version_request.type.value,
        uri=artifact_version_request.uri,
        materializer=artifact_version_request.materializer.model_dump_json(),
        data_type=artifact_version_request.data_type.model_dump_json(),
        save_type=artifact_version_request.save_type.value,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ArtifactVersionResponse

Convert an ArtifactVersionSchema to an ArtifactVersionResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ArtifactVersionResponse

The created ArtifactVersionResponse.

Source code in src/zenml/zen_stores/schemas/artifact_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ArtifactVersionResponse:
    """Convert an `ArtifactVersionSchema` to an `ArtifactVersionResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic



    Returns:
        The created `ArtifactVersionResponse`.
    """
    try:
        materializer = Source.model_validate_json(self.materializer)
    except ValidationError:
        # This is an old source which was an importable source path
        materializer = Source.from_import_path(self.materializer)

    try:
        data_type = Source.model_validate_json(self.data_type)
    except ValidationError:
        # This is an old source which was an importable source path
        data_type = Source.from_import_path(self.data_type)

    producer_step_run_id, producer_pipeline_run_id = None, None
    if self.output_of_step_runs:
        original_step_runs = [
            sr
            for sr in self.output_of_step_runs
            if sr.step_run.status == ExecutionStatus.COMPLETED
        ]
        if len(original_step_runs) == 1:
            step_run = original_step_runs[0].step_run
            producer_step_run_id = step_run.id
            producer_pipeline_run_id = step_run.pipeline_run_id
        else:
            step_run = self.output_of_step_runs[0].step_run
            producer_step_run_id = step_run.original_step_run_id

    # Create the body of the model
    artifact = self.artifact.to_model()
    body = ArtifactVersionResponseBody(
        artifact=artifact,
        version=self.version or str(self.version_number),
        user=self.user.to_model() if self.user else None,
        uri=self.uri,
        type=ArtifactType(self.type),
        materializer=materializer,
        data_type=data_type,
        created=self.created,
        updated=self.updated,
        tags=[tag.to_model() for tag in self.tags],
        producer_pipeline_run_id=producer_pipeline_run_id,
        save_type=ArtifactSaveType(self.save_type),
        artifact_store_id=self.artifact_store_id,
    )

    # Create the metadata of the model
    metadata = None
    if include_metadata:
        metadata = ArtifactVersionResponseMetadata(
            project=self.project.to_model(),
            producer_step_run_id=producer_step_run_id,
            visualizations=[v.to_model() for v in self.visualizations],
            run_metadata=self.fetch_metadata(),
        )

    resources = None

    return ArtifactVersionResponse(
        id=self.id,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(artifact_version_update: ArtifactVersionUpdate) -> ArtifactVersionSchema

Update an ArtifactVersionSchema with an ArtifactVersionUpdate.

Parameters:

Name Type Description Default
artifact_version_update ArtifactVersionUpdate

The update model to apply.

required

Returns:

Type Description
ArtifactVersionSchema

The updated ArtifactVersionSchema.

Source code in src/zenml/zen_stores/schemas/artifact_schemas.py
445
446
447
448
449
450
451
452
453
454
455
456
457
def update(
    self, artifact_version_update: ArtifactVersionUpdate
) -> "ArtifactVersionSchema":
    """Update an `ArtifactVersionSchema` with an `ArtifactVersionUpdate`.

    Args:
        artifact_version_update: The update model to apply.

    Returns:
        The updated `ArtifactVersionSchema`.
    """
    self.updated = utc_now()
    return self
ArtifactVisualizationSchema

Bases: BaseSchema

SQL Model for visualizations of artifacts.

Functions
from_model(artifact_visualization_request: ArtifactVisualizationRequest, artifact_version_id: UUID) -> ArtifactVisualizationSchema classmethod

Convert a ArtifactVisualizationRequest to a ArtifactVisualizationSchema.

Parameters:

Name Type Description Default
artifact_visualization_request ArtifactVisualizationRequest

The visualization.

required
artifact_version_id UUID

The UUID of the artifact version.

required

Returns:

Type Description
ArtifactVisualizationSchema

The ArtifactVisualizationSchema.

Source code in src/zenml/zen_stores/schemas/artifact_visualization_schemas.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
@classmethod
def from_model(
    cls,
    artifact_visualization_request: ArtifactVisualizationRequest,
    artifact_version_id: UUID,
) -> "ArtifactVisualizationSchema":
    """Convert a `ArtifactVisualizationRequest` to a `ArtifactVisualizationSchema`.

    Args:
        artifact_visualization_request: The visualization.
        artifact_version_id: The UUID of the artifact version.

    Returns:
        The `ArtifactVisualizationSchema`.
    """
    return cls(
        type=artifact_visualization_request.type.value,
        uri=artifact_visualization_request.uri,
        artifact_version_id=artifact_version_id,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ArtifactVisualizationResponse

Convert an ArtifactVisualizationSchema to a Visualization.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ArtifactVisualizationResponse

The Visualization.

Source code in src/zenml/zen_stores/schemas/artifact_visualization_schemas.py
 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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ArtifactVisualizationResponse:
    """Convert an `ArtifactVisualizationSchema` to a `Visualization`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic



    Returns:
        The `Visualization`.
    """
    body = ArtifactVisualizationResponseBody(
        type=VisualizationType(self.type),
        uri=self.uri,
        created=self.created,
        updated=self.updated,
    )

    metadata = None
    if include_metadata:
        metadata = ArtifactVisualizationResponseMetadata(
            artifact_version_id=self.artifact_version_id,
        )

    return ArtifactVisualizationResponse(
        id=self.id,
        body=body,
        metadata=metadata,
    )
BaseSchema

Bases: SQLModel

Base SQL Model for ZenML entities.

Functions
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> Any

In case the Schema has a corresponding Model, this allows conversion to that model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Raises:

Type Description
NotImplementedError

When the base class fails to implement this.

Source code in src/zenml/zen_stores/schemas/base_schemas.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> Any:
    """In case the Schema has a corresponding Model, this allows conversion to that model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

    Raises:
        NotImplementedError: When the base class fails to implement this.
    """
    raise NotImplementedError(
        "No 'to_model()' method implemented for this"
        f"schema: '{self.__class__.__name__}'."
    )
CodeReferenceSchema

Bases: BaseSchema

SQL Model for code references.

Functions
from_request(request: CodeReferenceRequest, project_id: UUID) -> CodeReferenceSchema classmethod

Convert a CodeReferenceRequest to a CodeReferenceSchema.

Parameters:

Name Type Description Default
request CodeReferenceRequest

The request model to convert.

required
project_id UUID

The project ID.

required

Returns:

Type Description
CodeReferenceSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/code_repository_schemas.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
@classmethod
def from_request(
    cls, request: "CodeReferenceRequest", project_id: UUID
) -> "CodeReferenceSchema":
    """Convert a `CodeReferenceRequest` to a `CodeReferenceSchema`.

    Args:
        request: The request model to convert.
        project_id: The project ID.

    Returns:
        The converted schema.
    """
    return cls(
        project_id=project_id,
        commit=request.commit,
        subdirectory=request.subdirectory,
        code_repository_id=request.code_repository,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> CodeReferenceResponse

Convert a CodeReferenceSchema to a CodeReferenceResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}
kwargs Any

Additional keyword arguments.

{}

Returns:

Type Description
CodeReferenceResponse

The converted model.

Source code in src/zenml/zen_stores/schemas/code_repository_schemas.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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "CodeReferenceResponse":
    """Convert a `CodeReferenceSchema` to a `CodeReferenceResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

        kwargs: Additional keyword arguments.

    Returns:
        The converted model.
    """
    body = CodeReferenceResponseBody(
        commit=self.commit,
        subdirectory=self.subdirectory,
        code_repository=self.code_repository.to_model(),
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        metadata = CodeReferenceResponseMetadata()

    return CodeReferenceResponse(
        id=self.id,
        body=body,
        metadata=metadata,
    )
CodeRepositorySchema

Bases: NamedSchema

SQL Model for code repositories.

Functions
from_request(request: CodeRepositoryRequest) -> CodeRepositorySchema classmethod

Convert a CodeRepositoryRequest to a CodeRepositorySchema.

Parameters:

Name Type Description Default
request CodeRepositoryRequest

The request model to convert.

required

Returns:

Type Description
CodeRepositorySchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/code_repository_schemas.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
@classmethod
def from_request(
    cls, request: "CodeRepositoryRequest"
) -> "CodeRepositorySchema":
    """Convert a `CodeRepositoryRequest` to a `CodeRepositorySchema`.

    Args:
        request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=request.name,
        project_id=request.project,
        user_id=request.user,
        config=json.dumps(request.config),
        source=request.source.model_dump_json(),
        description=request.description,
        logo_url=request.logo_url,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> CodeRepositoryResponse

Convert a CodeRepositorySchema to a CodeRepositoryResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
CodeRepositoryResponse

The created CodeRepositoryResponse.

Source code in src/zenml/zen_stores/schemas/code_repository_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "CodeRepositoryResponse":
    """Convert a `CodeRepositorySchema` to a `CodeRepositoryResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created CodeRepositoryResponse.
    """
    body = CodeRepositoryResponseBody(
        user=self.user.to_model() if self.user else None,
        source=json.loads(self.source),
        logo_url=self.logo_url,
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        metadata = CodeRepositoryResponseMetadata(
            project=self.project.to_model(),
            config=json.loads(self.config),
            description=self.description,
        )
    return CodeRepositoryResponse(
        id=self.id,
        name=self.name,
        metadata=metadata,
        body=body,
    )
update(update: CodeRepositoryUpdate) -> CodeRepositorySchema

Update a CodeRepositorySchema with a CodeRepositoryUpdate.

Parameters:

Name Type Description Default
update CodeRepositoryUpdate

The update model.

required

Returns:

Type Description
CodeRepositorySchema

The updated CodeRepositorySchema.

Source code in src/zenml/zen_stores/schemas/code_repository_schemas.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def update(self, update: "CodeRepositoryUpdate") -> "CodeRepositorySchema":
    """Update a `CodeRepositorySchema` with a `CodeRepositoryUpdate`.

    Args:
        update: The update model.

    Returns:
        The updated `CodeRepositorySchema`.
    """
    if update.name:
        self.name = update.name

    if update.description:
        self.description = update.description

    if update.logo_url:
        self.logo_url = update.logo_url

    if update.config:
        self.config = json.dumps(update.config)

    self.updated = utc_now()
    return self
EventSourceSchema

Bases: NamedSchema

SQL Model for tag.

Functions
from_request(request: EventSourceRequest) -> EventSourceSchema classmethod

Convert an EventSourceRequest to an EventSourceSchema.

Parameters:

Name Type Description Default
request EventSourceRequest

The request model to convert.

required

Returns:

Type Description
EventSourceSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/event_source_schemas.py
 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
@classmethod
def from_request(cls, request: EventSourceRequest) -> "EventSourceSchema":
    """Convert an `EventSourceRequest` to an `EventSourceSchema`.

    Args:
        request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        project_id=request.project,
        user_id=request.user,
        flavor=request.flavor,
        plugin_subtype=request.plugin_subtype,
        name=request.name,
        description=request.description,
        configuration=base64.b64encode(
            json.dumps(
                request.configuration,
                sort_keys=False,
                default=pydantic_encoder,
            ).encode("utf-8")
        ),
        is_active=True,  # Makes no sense to create an inactive event source
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> EventSourceResponse

Convert an EventSourceSchema to an EventSourceResponse.

Parameters:

Name Type Description Default
include_metadata bool

Flag deciding whether to include the output model(s) metadata fields in the response.

False
include_resources bool

Flag deciding whether to include the output model(s) metadata fields in the response.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
EventSourceResponse

The created EventSourceResponse.

Source code in src/zenml/zen_stores/schemas/event_source_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> EventSourceResponse:
    """Convert an `EventSourceSchema` to an `EventSourceResponse`.

    Args:
        include_metadata: Flag deciding whether to include the output model(s)
            metadata fields in the response.
        include_resources: Flag deciding whether to include the output model(s)
            metadata fields in the response.
        **kwargs: Keyword arguments to allow schema specific logic

    Returns:
        The created `EventSourceResponse`.
    """
    from zenml.models import TriggerResponse

    body = EventSourceResponseBody(
        created=self.created,
        updated=self.updated,
        user=self.user.to_model() if self.user else None,
        flavor=self.flavor,
        plugin_subtype=self.plugin_subtype,
        is_active=self.is_active,
    )
    resources = None
    if include_resources:
        triggers = cast(
            Page[TriggerResponse],
            get_page_from_list(
                items_list=self.triggers,
                response_model=TriggerResponse,
                include_resources=include_resources,
                include_metadata=include_metadata,
            ),
        )
        resources = EventSourceResponseResources(
            triggers=triggers,
        )
    metadata = None
    if include_metadata:
        metadata = EventSourceResponseMetadata(
            project=self.project.to_model(),
            description=self.description,
            configuration=json.loads(
                base64.b64decode(self.configuration).decode()
            ),
        )
    return EventSourceResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(update: EventSourceUpdate) -> EventSourceSchema

Updates a EventSourceSchema from a EventSourceUpdate.

Parameters:

Name Type Description Default
update EventSourceUpdate

The EventSourceUpdate to update from.

required

Returns:

Type Description
EventSourceSchema

The updated EventSourceSchema.

Source code in src/zenml/zen_stores/schemas/event_source_schemas.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def update(self, update: EventSourceUpdate) -> "EventSourceSchema":
    """Updates a `EventSourceSchema` from a `EventSourceUpdate`.

    Args:
        update: The `EventSourceUpdate` to update from.

    Returns:
        The updated `EventSourceSchema`.
    """
    for field, value in update.model_dump(
        exclude_unset=True, exclude_none=True
    ).items():
        if field == "configuration":
            self.configuration = base64.b64encode(
                json.dumps(
                    update.configuration, default=pydantic_encoder
                ).encode("utf-8")
            )
        else:
            setattr(self, field, value)
    self.updated = utc_now()
    return self
FlavorSchema

Bases: NamedSchema

SQL Model for flavors.

Attributes:

Name Type Description
type str

The type of the flavor.

source str

The source of the flavor.

config_schema str

The config schema of the flavor.

integration Optional[str]

The integration associated with the flavor.

Functions
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> FlavorResponse

Converts a flavor schema to a flavor model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
FlavorResponse

The flavor model.

Source code in src/zenml/zen_stores/schemas/flavor_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "FlavorResponse":
    """Converts a flavor schema to a flavor model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The flavor model.
    """
    body = FlavorResponseBody(
        user=self.user.to_model() if self.user else None,
        type=StackComponentType(self.type),
        integration=self.integration,
        source=self.source,
        logo_url=self.logo_url,
        is_custom=self.is_custom,
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        metadata = FlavorResponseMetadata(
            config_schema=json.loads(self.config_schema),
            connector_type=self.connector_type,
            connector_resource_type=self.connector_resource_type,
            connector_resource_id_attr=self.connector_resource_id_attr,
            docs_url=self.docs_url,
            sdk_docs_url=self.sdk_docs_url,
        )
    return FlavorResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(flavor_update: FlavorUpdate) -> FlavorSchema

Update a FlavorSchema from a FlavorUpdate.

Parameters:

Name Type Description Default
flavor_update FlavorUpdate

The FlavorUpdate from which to update the schema.

required

Returns:

Type Description
FlavorSchema

The updated FlavorSchema.

Source code in src/zenml/zen_stores/schemas/flavor_schemas.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def update(
    self,
    flavor_update: "FlavorUpdate",
) -> "FlavorSchema":
    """Update a `FlavorSchema` from a `FlavorUpdate`.

    Args:
        flavor_update: The `FlavorUpdate` from which to update the schema.

    Returns:
        The updated `FlavorSchema`.
    """
    for field, value in flavor_update.model_dump(
        exclude_unset=True, exclude={"user"}
    ).items():
        if field == "config_schema":
            setattr(self, field, json.dumps(value))
        elif field == "type":
            setattr(self, field, value.value)
        else:
            setattr(self, field, value)

    self.updated = utc_now()
    return self
LogsSchema

Bases: BaseSchema

SQL Model for logs.

Functions
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> LogsResponse

Convert a LogsSchema to a LogsResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
LogsResponse

The created LogsResponse.

Source code in src/zenml/zen_stores/schemas/logs_schemas.py
 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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "LogsResponse":
    """Convert a `LogsSchema` to a `LogsResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `LogsResponse`.
    """
    body = LogsResponseBody(
        uri=self.uri,
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        metadata = LogsResponseMetadata(
            step_run_id=self.step_run_id,
            pipeline_run_id=self.pipeline_run_id,
            artifact_store_id=self.artifact_store_id,
        )
    return LogsResponse(
        id=self.id,
        body=body,
        metadata=metadata,
    )
ModelSchema

Bases: NamedSchema

SQL Model for model.

Attributes
latest_version: Optional[ModelVersionSchema] property

Fetch the latest version for this model.

Raises:

Type Description
RuntimeError

If no session for the schema exists.

Returns:

Type Description
Optional[ModelVersionSchema]

The latest version for this model.

Functions
from_request(model_request: ModelRequest) -> ModelSchema classmethod

Convert an ModelRequest to an ModelSchema.

Parameters:

Name Type Description Default
model_request ModelRequest

The request model to convert.

required

Returns:

Type Description
ModelSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
@classmethod
def from_request(cls, model_request: ModelRequest) -> "ModelSchema":
    """Convert an `ModelRequest` to an `ModelSchema`.

    Args:
        model_request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=model_request.name,
        project_id=model_request.project,
        user_id=model_request.user,
        license=model_request.license,
        description=model_request.description,
        audience=model_request.audience,
        use_cases=model_request.use_cases,
        limitations=model_request.limitations,
        trade_offs=model_request.trade_offs,
        ethics=model_request.ethics,
        save_models_to_registry=model_request.save_models_to_registry,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ModelResponse

Convert an ModelSchema to an ModelResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ModelResponse

The created ModelResponse.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ModelResponse:
    """Convert an `ModelSchema` to an `ModelResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `ModelResponse`.
    """
    tags = [tag.to_model() for tag in self.tags]

    if latest_version := self.latest_version:
        latest_version_name = latest_version.name
        latest_version_id = latest_version.id
    else:
        latest_version_name = None
        latest_version_id = None

    metadata = None
    if include_metadata:
        metadata = ModelResponseMetadata(
            project=self.project.to_model(),
            license=self.license,
            description=self.description,
            audience=self.audience,
            use_cases=self.use_cases,
            limitations=self.limitations,
            trade_offs=self.trade_offs,
            ethics=self.ethics,
            save_models_to_registry=self.save_models_to_registry,
        )

    body = ModelResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        tags=tags,
        latest_version_name=latest_version_name,
        latest_version_id=latest_version_id,
    )

    return ModelResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(model_update: ModelUpdate) -> ModelSchema

Updates a ModelSchema from a ModelUpdate.

Parameters:

Name Type Description Default
model_update ModelUpdate

The ModelUpdate to update from.

required

Returns:

Type Description
ModelSchema

The updated ModelSchema.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def update(
    self,
    model_update: ModelUpdate,
) -> "ModelSchema":
    """Updates a `ModelSchema` from a `ModelUpdate`.

    Args:
        model_update: The `ModelUpdate` to update from.

    Returns:
        The updated `ModelSchema`.
    """
    for field, value in model_update.model_dump(
        exclude_unset=True, exclude_none=True
    ).items():
        if field in ["add_tags", "remove_tags"]:
            # Tags are handled separately
            continue
        setattr(self, field, value)
    self.updated = utc_now()
    return self
ModelVersionArtifactSchema

Bases: BaseSchema

SQL Model for linking of Model Versions and Artifacts M:M.

Functions
from_request(model_version_artifact_request: ModelVersionArtifactRequest) -> ModelVersionArtifactSchema classmethod

Convert an ModelVersionArtifactRequest to a ModelVersionArtifactSchema.

Parameters:

Name Type Description Default
model_version_artifact_request ModelVersionArtifactRequest

The request link to convert.

required

Returns:

Type Description
ModelVersionArtifactSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
@classmethod
def from_request(
    cls,
    model_version_artifact_request: ModelVersionArtifactRequest,
) -> "ModelVersionArtifactSchema":
    """Convert an `ModelVersionArtifactRequest` to a `ModelVersionArtifactSchema`.

    Args:
        model_version_artifact_request: The request link to convert.

    Returns:
        The converted schema.
    """
    return cls(
        model_version_id=model_version_artifact_request.model_version,
        artifact_version_id=model_version_artifact_request.artifact_version,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ModelVersionArtifactResponse

Convert an ModelVersionArtifactSchema to an ModelVersionArtifactResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ModelVersionArtifactResponse

The created ModelVersionArtifactResponseModel.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ModelVersionArtifactResponse:
    """Convert an `ModelVersionArtifactSchema` to an `ModelVersionArtifactResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `ModelVersionArtifactResponseModel`.
    """
    return ModelVersionArtifactResponse(
        id=self.id,
        body=ModelVersionArtifactResponseBody(
            created=self.created,
            updated=self.updated,
            model_version=self.model_version_id,
            artifact_version=self.artifact_version.to_model(),
        ),
        metadata=BaseResponseMetadata() if include_metadata else None,
    )
ModelVersionPipelineRunSchema

Bases: BaseSchema

SQL Model for linking of Model Versions and Pipeline Runs M:M.

Functions
from_request(model_version_pipeline_run_request: ModelVersionPipelineRunRequest) -> ModelVersionPipelineRunSchema classmethod

Convert an ModelVersionPipelineRunRequest to an ModelVersionPipelineRunSchema.

Parameters:

Name Type Description Default
model_version_pipeline_run_request ModelVersionPipelineRunRequest

The request link to convert.

required

Returns:

Type Description
ModelVersionPipelineRunSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
@classmethod
def from_request(
    cls,
    model_version_pipeline_run_request: ModelVersionPipelineRunRequest,
) -> "ModelVersionPipelineRunSchema":
    """Convert an `ModelVersionPipelineRunRequest` to an `ModelVersionPipelineRunSchema`.

    Args:
        model_version_pipeline_run_request: The request link to convert.

    Returns:
        The converted schema.
    """
    return cls(
        model_version_id=model_version_pipeline_run_request.model_version,
        pipeline_run_id=model_version_pipeline_run_request.pipeline_run,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ModelVersionPipelineRunResponse

Convert an ModelVersionPipelineRunSchema to an ModelVersionPipelineRunResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ModelVersionPipelineRunResponse

The created ModelVersionPipelineRunResponse.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ModelVersionPipelineRunResponse:
    """Convert an `ModelVersionPipelineRunSchema` to an `ModelVersionPipelineRunResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `ModelVersionPipelineRunResponse`.
    """
    return ModelVersionPipelineRunResponse(
        id=self.id,
        body=ModelVersionPipelineRunResponseBody(
            created=self.created,
            updated=self.updated,
            model_version=self.model_version_id,
            pipeline_run=self.pipeline_run.to_model(),
        ),
        metadata=BaseResponseMetadata() if include_metadata else None,
    )
ModelVersionSchema

Bases: NamedSchema, RunMetadataInterface

SQL Model for model version.

Functions
from_request(model_version_request: ModelVersionRequest, model_version_number: int, producer_run_id: Optional[UUID] = None) -> ModelVersionSchema classmethod

Convert an ModelVersionRequest to an ModelVersionSchema.

Parameters:

Name Type Description Default
model_version_request ModelVersionRequest

The request model version to convert.

required
model_version_number int

The model version number.

required
producer_run_id Optional[UUID]

The ID of the producer run.

None

Returns:

Type Description
ModelVersionSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
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
@classmethod
def from_request(
    cls,
    model_version_request: ModelVersionRequest,
    model_version_number: int,
    producer_run_id: Optional[UUID] = None,
) -> "ModelVersionSchema":
    """Convert an `ModelVersionRequest` to an `ModelVersionSchema`.

    Args:
        model_version_request: The request model version to convert.
        model_version_number: The model version number.
        producer_run_id: The ID of the producer run.

    Returns:
        The converted schema.
    """
    id_ = uuid4()
    is_numeric = str(model_version_number) == model_version_request.name

    return cls(
        id=id_,
        project_id=model_version_request.project,
        user_id=model_version_request.user,
        model_id=model_version_request.model,
        name=model_version_request.name,
        number=model_version_number,
        description=model_version_request.description,
        stage=model_version_request.stage,
        producer_run_id_if_numeric=producer_run_id
        if (producer_run_id and is_numeric)
        else id_,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ModelVersionResponse

Convert an ModelVersionSchema to an ModelVersionResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ModelVersionResponse

The created ModelVersionResponse.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ModelVersionResponse:
    """Convert an `ModelVersionSchema` to an `ModelVersionResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `ModelVersionResponse`.
    """
    from zenml.models import ServiceResponse

    # Construct {name: {version: id}} dicts for all linked artifacts
    model_artifact_ids: Dict[str, Dict[str, UUID]] = {}
    deployment_artifact_ids: Dict[str, Dict[str, UUID]] = {}
    data_artifact_ids: Dict[str, Dict[str, UUID]] = {}
    for artifact_link in self.artifact_links:
        if not artifact_link.artifact_version:
            continue
        artifact_name = artifact_link.artifact_version.artifact.name
        artifact_version = str(artifact_link.artifact_version.version)
        artifact_version_id = artifact_link.artifact_version.id
        if artifact_link.artifact_version.type == ArtifactType.MODEL.value:
            model_artifact_ids.setdefault(artifact_name, {}).update(
                {str(artifact_version): artifact_version_id}
            )
        elif (
            artifact_link.artifact_version.type
            == ArtifactType.SERVICE.value
        ):
            deployment_artifact_ids.setdefault(artifact_name, {}).update(
                {str(artifact_version): artifact_version_id}
            )
        else:
            data_artifact_ids.setdefault(artifact_name, {}).update(
                {str(artifact_version): artifact_version_id}
            )

    # Construct {name: id} dict for all linked pipeline runs
    pipeline_run_ids: Dict[str, UUID] = {}
    for pipeline_run_link in self.pipeline_run_links:
        if not pipeline_run_link.pipeline_run:
            continue
        pipeline_run = pipeline_run_link.pipeline_run
        pipeline_run_ids[pipeline_run.name] = pipeline_run.id

    metadata = None
    if include_metadata:
        metadata = ModelVersionResponseMetadata(
            project=self.project.to_model(),
            description=self.description,
            run_metadata=self.fetch_metadata(),
        )

    resources = None
    if include_resources:
        services = cast(
            Page[ServiceResponse],
            get_page_from_list(
                items_list=self.services,
                response_model=ServiceResponse,
                include_resources=include_resources,
                include_metadata=include_metadata,
            ),
        )
        resources = ModelVersionResponseResources(
            services=services,
        )

    body = ModelVersionResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        stage=self.stage,
        number=self.number,
        model=self.model.to_model(),
        model_artifact_ids=model_artifact_ids,
        data_artifact_ids=data_artifact_ids,
        deployment_artifact_ids=deployment_artifact_ids,
        pipeline_run_ids=pipeline_run_ids,
        tags=[tag.to_model() for tag in self.tags],
    )

    return ModelVersionResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(target_stage: Optional[str] = None, target_name: Optional[str] = None, target_description: Optional[str] = None) -> ModelVersionSchema

Updates a ModelVersionSchema to a target stage.

Parameters:

Name Type Description Default
target_stage Optional[str]

The stage to be updated.

None
target_name Optional[str]

The version name to be updated.

None
target_description Optional[str]

The version description to be updated.

None

Returns:

Type Description
ModelVersionSchema

The updated ModelVersionSchema.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
def update(
    self,
    target_stage: Optional[str] = None,
    target_name: Optional[str] = None,
    target_description: Optional[str] = None,
) -> "ModelVersionSchema":
    """Updates a `ModelVersionSchema` to a target stage.

    Args:
        target_stage: The stage to be updated.
        target_name: The version name to be updated.
        target_description: The version description to be updated.

    Returns:
        The updated `ModelVersionSchema`.
    """
    if target_stage is not None:
        self.stage = target_stage
    if target_name is not None:
        self.name = target_name
    if target_description is not None:
        self.description = target_description
    self.updated = utc_now()
    return self
NamedSchema

Bases: BaseSchema

Base Named SQL Model.

OAuthDeviceSchema

Bases: BaseSchema

SQL Model for authorized OAuth2 devices.

Functions
from_request(request: OAuthDeviceInternalRequest) -> Tuple[OAuthDeviceSchema, str, str] classmethod

Create an authorized device DB entry from a device authorization request.

Parameters:

Name Type Description Default
request OAuthDeviceInternalRequest

The device authorization request.

required

Returns:

Type Description
Tuple[OAuthDeviceSchema, str, str]

The created OAuthDeviceSchema, the user code and the device code.

Source code in src/zenml/zen_stores/schemas/device_schemas.py
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
@classmethod
def from_request(
    cls, request: OAuthDeviceInternalRequest
) -> Tuple["OAuthDeviceSchema", str, str]:
    """Create an authorized device DB entry from a device authorization request.

    Args:
        request: The device authorization request.

    Returns:
        The created `OAuthDeviceSchema`, the user code and the device code.
    """
    user_code = cls._generate_user_code()
    device_code = cls._generate_device_code()
    hashed_user_code = cls._get_hashed_code(user_code)
    hashed_device_code = cls._get_hashed_code(device_code)
    now = utc_now()
    return (
        cls(
            client_id=request.client_id,
            user_code=hashed_user_code,
            device_code=hashed_device_code,
            status=OAuthDeviceStatus.PENDING.value,
            failed_auth_attempts=0,
            expires=now + timedelta(seconds=request.expires_in),
            os=request.os,
            ip_address=request.ip_address,
            hostname=request.hostname,
            python_version=request.python_version,
            zenml_version=request.zenml_version,
            city=request.city,
            region=request.region,
            country=request.country,
            created=now,
            updated=now,
        ),
        user_code,
        device_code,
    )
internal_update(device_update: OAuthDeviceInternalUpdate) -> Tuple[OAuthDeviceSchema, Optional[str], Optional[str]]

Update an authorized device from an internal device update model.

Parameters:

Name Type Description Default
device_update OAuthDeviceInternalUpdate

The internal device update model.

required

Returns:

Type Description
OAuthDeviceSchema

The updated OAuthDeviceSchema and the new user code and device

Optional[str]

code, if they were generated.

Source code in src/zenml/zen_stores/schemas/device_schemas.py
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
def internal_update(
    self, device_update: OAuthDeviceInternalUpdate
) -> Tuple["OAuthDeviceSchema", Optional[str], Optional[str]]:
    """Update an authorized device from an internal device update model.

    Args:
        device_update: The internal device update model.

    Returns:
        The updated `OAuthDeviceSchema` and the new user code and device
        code, if they were generated.
    """
    now = utc_now()
    user_code: Optional[str] = None
    device_code: Optional[str] = None

    # This call also takes care of setting fields that have the same
    # name in the internal model and the schema.
    self.update(device_update)

    if device_update.expires_in is not None:
        if device_update.expires_in <= 0:
            self.expires = None
        else:
            self.expires = now + timedelta(
                seconds=device_update.expires_in
            )
    if device_update.update_last_login:
        self.last_login = now
    if device_update.generate_new_codes:
        user_code = self._generate_user_code()
        device_code = self._generate_device_code()
        self.user_code = self._get_hashed_code(user_code)
        self.device_code = self._get_hashed_code(device_code)
    self.updated = now
    return self, user_code, device_code
to_internal_model(include_metadata: bool = False, include_resources: bool = False) -> OAuthDeviceInternalResponse

Convert a device schema to an internal device response model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False

Returns:

Type Description
OAuthDeviceInternalResponse

The converted internal device response model.

Source code in src/zenml/zen_stores/schemas/device_schemas.py
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
def to_internal_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
) -> OAuthDeviceInternalResponse:
    """Convert a device schema to an internal device response model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.

    Returns:
        The converted internal device response model.
    """
    device_model = self.to_model(
        include_metadata=include_metadata,
        include_resources=include_resources,
    )
    return OAuthDeviceInternalResponse(
        id=device_model.id,
        body=device_model.body,
        metadata=device_model.metadata,
        user_code=self.user_code,
        device_code=self.device_code,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> OAuthDeviceResponse

Convert a device schema to a device response model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
OAuthDeviceResponse

The converted device response model.

Source code in src/zenml/zen_stores/schemas/device_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> OAuthDeviceResponse:
    """Convert a device schema to a device response model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The converted device response model.
    """
    metadata = None
    if include_metadata:
        metadata = OAuthDeviceResponseMetadata(
            python_version=self.python_version,
            zenml_version=self.zenml_version,
            city=self.city,
            region=self.region,
            country=self.country,
            failed_auth_attempts=self.failed_auth_attempts,
            last_login=self.last_login,
        )

    body = OAuthDeviceResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        client_id=self.client_id,
        expires=self.expires,
        trusted_device=self.trusted_device,
        status=OAuthDeviceStatus(self.status),
        os=self.os,
        ip_address=self.ip_address,
        hostname=self.hostname,
    )
    return OAuthDeviceResponse(
        id=self.id,
        body=body,
        metadata=metadata,
    )
update(device_update: OAuthDeviceUpdate) -> OAuthDeviceSchema

Update an authorized device from a device update model.

Parameters:

Name Type Description Default
device_update OAuthDeviceUpdate

The device update model.

required

Returns:

Type Description
OAuthDeviceSchema

The updated OAuthDeviceSchema.

Source code in src/zenml/zen_stores/schemas/device_schemas.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def update(self, device_update: OAuthDeviceUpdate) -> "OAuthDeviceSchema":
    """Update an authorized device from a device update model.

    Args:
        device_update: The device update model.

    Returns:
        The updated `OAuthDeviceSchema`.
    """
    for field, value in device_update.model_dump(
        exclude_none=True
    ).items():
        if hasattr(self, field):
            setattr(self, field, value)

    if device_update.locked is True:
        self.status = OAuthDeviceStatus.LOCKED.value
    elif device_update.locked is False:
        self.status = OAuthDeviceStatus.ACTIVE.value

    self.updated = utc_now()
    return self
PipelineBuildSchema

Bases: BaseSchema

SQL Model for pipeline builds.

Functions
from_request(request: PipelineBuildRequest) -> PipelineBuildSchema classmethod

Convert a PipelineBuildRequest to a PipelineBuildSchema.

Parameters:

Name Type Description Default
request PipelineBuildRequest

The request to convert.

required

Returns:

Type Description
PipelineBuildSchema

The created PipelineBuildSchema.

Source code in src/zenml/zen_stores/schemas/pipeline_build_schemas.py
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
@classmethod
def from_request(
    cls, request: PipelineBuildRequest
) -> "PipelineBuildSchema":
    """Convert a `PipelineBuildRequest` to a `PipelineBuildSchema`.

    Args:
        request: The request to convert.

    Returns:
        The created `PipelineBuildSchema`.
    """
    return cls(
        stack_id=request.stack,
        project_id=request.project,
        user_id=request.user,
        pipeline_id=request.pipeline,
        images=json.dumps(request.images, default=pydantic_encoder),
        is_local=request.is_local,
        contains_code=request.contains_code,
        zenml_version=request.zenml_version,
        python_version=request.python_version,
        checksum=request.checksum,
        stack_checksum=request.stack_checksum,
        duration=request.duration,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> PipelineBuildResponse

Convert a PipelineBuildSchema to a PipelineBuildResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
PipelineBuildResponse

The created PipelineBuildResponse.

Source code in src/zenml/zen_stores/schemas/pipeline_build_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> PipelineBuildResponse:
    """Convert a `PipelineBuildSchema` to a `PipelineBuildResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `PipelineBuildResponse`.
    """
    body = PipelineBuildResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        metadata = PipelineBuildResponseMetadata(
            project=self.project.to_model(),
            pipeline=self.pipeline.to_model() if self.pipeline else None,
            stack=self.stack.to_model() if self.stack else None,
            images=json.loads(self.images),
            zenml_version=self.zenml_version,
            python_version=self.python_version,
            checksum=self.checksum,
            stack_checksum=self.stack_checksum,
            is_local=self.is_local,
            contains_code=self.contains_code,
            duration=self.duration,
        )
    return PipelineBuildResponse(
        id=self.id,
        body=body,
        metadata=metadata,
    )
PipelineDeploymentSchema

Bases: BaseSchema

SQL Model for pipeline deployments.

Functions
from_request(request: PipelineDeploymentRequest, code_reference_id: Optional[UUID]) -> PipelineDeploymentSchema classmethod

Convert a PipelineDeploymentRequest to a PipelineDeploymentSchema.

Parameters:

Name Type Description Default
request PipelineDeploymentRequest

The request to convert.

required
code_reference_id Optional[UUID]

Optional ID of the code reference for the deployment.

required

Returns:

Type Description
PipelineDeploymentSchema

The created PipelineDeploymentSchema.

Source code in src/zenml/zen_stores/schemas/pipeline_deployment_schemas.py
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
@classmethod
def from_request(
    cls,
    request: PipelineDeploymentRequest,
    code_reference_id: Optional[UUID],
) -> "PipelineDeploymentSchema":
    """Convert a `PipelineDeploymentRequest` to a `PipelineDeploymentSchema`.

    Args:
        request: The request to convert.
        code_reference_id: Optional ID of the code reference for the
            deployment.

    Returns:
        The created `PipelineDeploymentSchema`.
    """
    return cls(
        stack_id=request.stack,
        project_id=request.project,
        pipeline_id=request.pipeline,
        build_id=request.build,
        user_id=request.user,
        schedule_id=request.schedule,
        template_id=request.template,
        code_reference_id=code_reference_id,
        run_name_template=request.run_name_template,
        pipeline_configuration=request.pipeline_configuration.model_dump_json(),
        step_configurations=json.dumps(
            request.step_configurations,
            sort_keys=False,
            default=pydantic_encoder,
        ),
        client_environment=json.dumps(request.client_environment),
        client_version=request.client_version,
        server_version=request.server_version,
        pipeline_version_hash=request.pipeline_version_hash,
        pipeline_spec=json.dumps(
            request.pipeline_spec.model_dump(mode="json"), sort_keys=True
        )
        if request.pipeline_spec
        else None,
        code_path=request.code_path,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> PipelineDeploymentResponse

Convert a PipelineDeploymentSchema to a PipelineDeploymentResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
PipelineDeploymentResponse

The created PipelineDeploymentResponse.

Source code in src/zenml/zen_stores/schemas/pipeline_deployment_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> PipelineDeploymentResponse:
    """Convert a `PipelineDeploymentSchema` to a `PipelineDeploymentResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `PipelineDeploymentResponse`.
    """
    body = PipelineDeploymentResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        pipeline_configuration = PipelineConfiguration.model_validate_json(
            self.pipeline_configuration
        )
        step_configurations = json.loads(self.step_configurations)
        for s, c in step_configurations.items():
            step_configurations[s] = Step.model_validate(c)

        metadata = PipelineDeploymentResponseMetadata(
            project=self.project.to_model(),
            run_name_template=self.run_name_template,
            pipeline_configuration=pipeline_configuration,
            step_configurations=step_configurations,
            client_environment=json.loads(self.client_environment),
            client_version=self.client_version,
            server_version=self.server_version,
            pipeline=self.pipeline.to_model() if self.pipeline else None,
            stack=self.stack.to_model() if self.stack else None,
            build=self.build.to_model() if self.build else None,
            schedule=self.schedule.to_model() if self.schedule else None,
            code_reference=self.code_reference.to_model()
            if self.code_reference
            else None,
            pipeline_version_hash=self.pipeline_version_hash,
            pipeline_spec=PipelineSpec.model_validate_json(
                self.pipeline_spec
            )
            if self.pipeline_spec
            else None,
            code_path=self.code_path,
            template_id=self.template_id,
        )
    return PipelineDeploymentResponse(
        id=self.id,
        body=body,
        metadata=metadata,
    )
PipelineRunSchema

Bases: NamedSchema, RunMetadataInterface

SQL Model for pipeline runs.

Functions
fetch_metadata_collection() -> Dict[str, List[RunMetadataEntry]]

Fetches all the metadata entries related to the pipeline run.

Returns:

Type Description
Dict[str, List[RunMetadataEntry]]

a dictionary, where the key is the key of the metadata entry and the values represent the list of entries with this key.

Source code in src/zenml/zen_stores/schemas/pipeline_run_schemas.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def fetch_metadata_collection(self) -> Dict[str, List[RunMetadataEntry]]:
    """Fetches all the metadata entries related to the pipeline run.

    Returns:
        a dictionary, where the key is the key of the metadata entry
            and the values represent the list of entries with this key.
    """
    # Fetch the metadata related to this run
    metadata_collection = super().fetch_metadata_collection()

    # Fetch the metadata related to the steps of this run
    for s in self.step_runs:
        step_metadata = s.fetch_metadata_collection()
        for k, v in step_metadata.items():
            metadata_collection[f"{s.name}::{k}"] = v

    # Fetch the metadata related to the schedule of this run
    if self.deployment is not None:
        if schedule := self.deployment.schedule:
            schedule_metadata = schedule.fetch_metadata_collection()
            for k, v in schedule_metadata.items():
                metadata_collection[f"schedule:{k}"] = v

    return metadata_collection
from_request(request: PipelineRunRequest) -> PipelineRunSchema classmethod

Convert a PipelineRunRequest to a PipelineRunSchema.

Parameters:

Name Type Description Default
request PipelineRunRequest

The request to convert.

required

Returns:

Type Description
PipelineRunSchema

The created PipelineRunSchema.

Source code in src/zenml/zen_stores/schemas/pipeline_run_schemas.py
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
@classmethod
def from_request(
    cls, request: "PipelineRunRequest"
) -> "PipelineRunSchema":
    """Convert a `PipelineRunRequest` to a `PipelineRunSchema`.

    Args:
        request: The request to convert.

    Returns:
        The created `PipelineRunSchema`.
    """
    orchestrator_environment = json.dumps(request.orchestrator_environment)

    return cls(
        project_id=request.project,
        user_id=request.user,
        name=request.name,
        orchestrator_run_id=request.orchestrator_run_id,
        orchestrator_environment=orchestrator_environment,
        start_time=request.start_time,
        status=request.status.value,
        pipeline_id=request.pipeline,
        deployment_id=request.deployment,
        trigger_execution_id=request.trigger_execution_id,
    )
is_placeholder_run() -> bool

Whether the pipeline run is a placeholder run.

Returns:

Type Description
bool

Whether the pipeline run is a placeholder run.

Source code in src/zenml/zen_stores/schemas/pipeline_run_schemas.py
483
484
485
486
487
488
489
490
491
492
def is_placeholder_run(self) -> bool:
    """Whether the pipeline run is a placeholder run.

    Returns:
        Whether the pipeline run is a placeholder run.
    """
    return (
        self.orchestrator_run_id is None
        and self.status == ExecutionStatus.INITIALIZING
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> PipelineRunResponse

Convert a PipelineRunSchema to a PipelineRunResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
PipelineRunResponse

The created PipelineRunResponse.

Raises:

Type Description
RuntimeError

if the model creation fails.

Source code in src/zenml/zen_stores/schemas/pipeline_run_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "PipelineRunResponse":
    """Convert a `PipelineRunSchema` to a `PipelineRunResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `PipelineRunResponse`.

    Raises:
        RuntimeError: if the model creation fails.
    """
    if self.deployment is not None:
        deployment = self.deployment.to_model(include_metadata=True)

        config = deployment.pipeline_configuration
        new_substitutions = config._get_full_substitutions(self.start_time)
        config = config.model_copy(
            update={"substitutions": new_substitutions}
        )
        client_environment = deployment.client_environment

        stack = deployment.stack
        pipeline = deployment.pipeline
        build = deployment.build
        schedule = deployment.schedule
        code_reference = deployment.code_reference

    elif self.pipeline_configuration is not None:
        config = PipelineConfiguration.model_validate_json(
            self.pipeline_configuration
        )
        client_environment = (
            json.loads(self.client_environment)
            if self.client_environment
            else {}
        )

        stack = self.stack.to_model() if self.stack else None
        pipeline = self.pipeline.to_model() if self.pipeline else None
        build = self.build.to_model() if self.build else None
        schedule = self.schedule.to_model() if self.schedule else None
        code_reference = None

    else:
        raise RuntimeError(
            "Pipeline run model creation has failed. Each pipeline run "
            "entry should either have a deployment_id or "
            "pipeline_configuration."
        )

    body = PipelineRunResponseBody(
        user=self.user.to_model() if self.user else None,
        status=ExecutionStatus(self.status),
        stack=stack,
        pipeline=pipeline,
        build=build,
        schedule=schedule,
        code_reference=code_reference,
        trigger_execution=(
            self.trigger_execution.to_model()
            if self.trigger_execution
            else None
        ),
        created=self.created,
        updated=self.updated,
        deployment_id=self.deployment_id,
        model_version_id=self.model_version_id,
    )
    metadata = None
    if include_metadata:
        is_templatable = False
        if (
            self.deployment
            and self.deployment.build
            and not self.deployment.build.is_local
            and self.deployment.build.stack
        ):
            is_templatable = True

        steps = {
            step.name: step.to_model(include_metadata=True)
            for step in self.step_runs
        }

        step_substitutions = {}
        for step_name, step in steps.items():
            step_substitutions[step_name] = step.config.substitutions
            # We fetch the steps hydrated before, but want them unhydrated
            # in the response -> We need to reset the metadata here
            step.metadata = None

        orchestrator_environment = (
            json.loads(self.orchestrator_environment)
            if self.orchestrator_environment
            else {}
        )
        metadata = PipelineRunResponseMetadata(
            project=self.project.to_model(),
            run_metadata=self.fetch_metadata(),
            config=config,
            steps=steps,
            start_time=self.start_time,
            end_time=self.end_time,
            client_environment=client_environment,
            orchestrator_environment=orchestrator_environment,
            orchestrator_run_id=self.orchestrator_run_id,
            code_path=self.deployment.code_path
            if self.deployment
            else None,
            template_id=self.deployment.template_id
            if self.deployment
            else None,
            is_templatable=is_templatable,
            step_substitutions=step_substitutions,
        )

    resources = None
    if include_resources:
        model_version = None
        if self.model_version:
            model_version = self.model_version.to_model()

        resources = PipelineRunResponseResources(
            model_version=model_version,
            tags=[tag.to_model() for tag in self.tags],
        )

    return PipelineRunResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(run_update: PipelineRunUpdate) -> PipelineRunSchema

Update a PipelineRunSchema with a PipelineRunUpdate.

Parameters:

Name Type Description Default
run_update PipelineRunUpdate

The PipelineRunUpdate to update with.

required

Returns:

Type Description
PipelineRunSchema

The updated PipelineRunSchema.

Source code in src/zenml/zen_stores/schemas/pipeline_run_schemas.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
def update(self, run_update: "PipelineRunUpdate") -> "PipelineRunSchema":
    """Update a `PipelineRunSchema` with a `PipelineRunUpdate`.

    Args:
        run_update: The `PipelineRunUpdate` to update with.

    Returns:
        The updated `PipelineRunSchema`.
    """
    if run_update.status:
        self.status = run_update.status.value
        self.end_time = run_update.end_time

    self.updated = utc_now()
    return self
update_placeholder(request: PipelineRunRequest) -> PipelineRunSchema

Update a placeholder run.

Parameters:

Name Type Description Default
request PipelineRunRequest

The pipeline run request which should replace the placeholder.

required

Raises:

Type Description
RuntimeError

If the DB entry does not represent a placeholder run.

ValueError

If the run request does not match the deployment or pipeline ID of the placeholder run.

Returns:

Type Description
PipelineRunSchema

The updated PipelineRunSchema.

Source code in src/zenml/zen_stores/schemas/pipeline_run_schemas.py
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
def update_placeholder(
    self, request: "PipelineRunRequest"
) -> "PipelineRunSchema":
    """Update a placeholder run.

    Args:
        request: The pipeline run request which should replace the
            placeholder.

    Raises:
        RuntimeError: If the DB entry does not represent a placeholder run.
        ValueError: If the run request does not match the deployment or
            pipeline ID of the placeholder run.

    Returns:
        The updated `PipelineRunSchema`.
    """
    if not self.is_placeholder_run():
        raise RuntimeError(
            f"Unable to replace pipeline run {self.id} which is not a "
            "placeholder run."
        )

    if (
        self.deployment_id != request.deployment
        or self.pipeline_id != request.pipeline
    ):
        raise ValueError(
            "Deployment or orchestrator run ID of placeholder run do not "
            "match the IDs of the run request."
        )

    orchestrator_environment = json.dumps(request.orchestrator_environment)

    self.orchestrator_run_id = request.orchestrator_run_id
    self.orchestrator_environment = orchestrator_environment
    self.status = request.status.value

    self.updated = utc_now()

    return self
PipelineSchema

Bases: NamedSchema

SQL Model for pipelines.

Attributes
latest_run: Optional[PipelineRunSchema] property

Fetch the latest run for this pipeline.

Raises:

Type Description
RuntimeError

If no session for the schema exists.

Returns:

Type Description
Optional[PipelineRunSchema]

The latest run for this pipeline.

Functions
from_request(pipeline_request: PipelineRequest) -> PipelineSchema classmethod

Convert a PipelineRequest to a PipelineSchema.

Parameters:

Name Type Description Default
pipeline_request PipelineRequest

The request model to convert.

required

Returns:

Type Description
PipelineSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/pipeline_schemas.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
@classmethod
def from_request(
    cls,
    pipeline_request: "PipelineRequest",
) -> "PipelineSchema":
    """Convert a `PipelineRequest` to a `PipelineSchema`.

    Args:
        pipeline_request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=pipeline_request.name,
        description=pipeline_request.description,
        project_id=pipeline_request.project,
        user_id=pipeline_request.user,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> PipelineResponse

Convert a PipelineSchema to a PipelineResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
PipelineResponse

The created PipelineResponse.

Source code in src/zenml/zen_stores/schemas/pipeline_schemas.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
191
192
193
194
195
196
197
198
199
200
201
202
203
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "PipelineResponse":
    """Convert a `PipelineSchema` to a `PipelineResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

    Returns:
        The created PipelineResponse.
    """
    latest_run = self.latest_run

    body = PipelineResponseBody(
        user=self.user.to_model() if self.user else None,
        latest_run_id=latest_run.id if latest_run else None,
        latest_run_status=latest_run.status if latest_run else None,
        created=self.created,
        updated=self.updated,
    )

    metadata = None
    if include_metadata:
        metadata = PipelineResponseMetadata(
            project=self.project.to_model(),
            description=self.description,
        )

    resources = None
    if include_resources:
        latest_run_user = latest_run.user if latest_run else None

        resources = PipelineResponseResources(
            latest_run_user=latest_run_user.to_model()
            if latest_run_user
            else None,
            tags=[tag.to_model() for tag in self.tags],
        )

    return PipelineResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(pipeline_update: PipelineUpdate) -> PipelineSchema

Update a PipelineSchema with a PipelineUpdate.

Parameters:

Name Type Description Default
pipeline_update PipelineUpdate

The update model.

required

Returns:

Type Description
PipelineSchema

The updated PipelineSchema.

Source code in src/zenml/zen_stores/schemas/pipeline_schemas.py
205
206
207
208
209
210
211
212
213
214
215
216
def update(self, pipeline_update: "PipelineUpdate") -> "PipelineSchema":
    """Update a `PipelineSchema` with a `PipelineUpdate`.

    Args:
        pipeline_update: The update model.

    Returns:
        The updated `PipelineSchema`.
    """
    self.description = pipeline_update.description
    self.updated = utc_now()
    return self
ProjectSchema

Bases: NamedSchema

SQL Model for projects.

Functions
from_request(project: ProjectRequest) -> ProjectSchema classmethod

Create a ProjectSchema from a ProjectResponse.

Parameters:

Name Type Description Default
project ProjectRequest

The ProjectResponse from which to create the schema.

required

Returns:

Type Description
ProjectSchema

The created ProjectSchema.

Source code in src/zenml/zen_stores/schemas/project_schemas.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
@classmethod
def from_request(cls, project: ProjectRequest) -> "ProjectSchema":
    """Create a `ProjectSchema` from a `ProjectResponse`.

    Args:
        project: The `ProjectResponse` from which to create the schema.

    Returns:
        The created `ProjectSchema`.
    """
    return cls(
        name=project.name,
        description=project.description,
        display_name=project.display_name,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ProjectResponse

Convert a ProjectSchema to a ProjectResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ProjectResponse

The converted ProjectResponseModel.

Source code in src/zenml/zen_stores/schemas/project_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ProjectResponse:
    """Convert a `ProjectSchema` to a `ProjectResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The converted `ProjectResponseModel`.
    """
    metadata = None
    if include_metadata:
        metadata = ProjectResponseMetadata(
            description=self.description,
        )
    return ProjectResponse(
        id=self.id,
        name=self.name,
        body=ProjectResponseBody(
            display_name=self.display_name,
            created=self.created,
            updated=self.updated,
        ),
        metadata=metadata,
    )
update(project_update: ProjectUpdate) -> ProjectSchema

Update a ProjectSchema from a ProjectUpdate.

Parameters:

Name Type Description Default
project_update ProjectUpdate

The ProjectUpdate from which to update the schema.

required

Returns:

Type Description
ProjectSchema

The updated ProjectSchema.

Source code in src/zenml/zen_stores/schemas/project_schemas.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def update(self, project_update: ProjectUpdate) -> "ProjectSchema":
    """Update a `ProjectSchema` from a `ProjectUpdate`.

    Args:
        project_update: The `ProjectUpdate` from which to update the
            schema.

    Returns:
        The updated `ProjectSchema`.
    """
    for field, value in project_update.model_dump(
        exclude_unset=True
    ).items():
        setattr(self, field, value)

    self.updated = utc_now()
    return self
RunMetadataResourceSchema

Bases: SQLModel

Table for linking resources to run metadata entries.

RunMetadataSchema

Bases: BaseSchema

SQL Model for run metadata.

RunTemplateSchema

Bases: NamedSchema

SQL Model for run templates.

Attributes
latest_run: Optional[PipelineRunSchema] property

Fetch the latest run for this template.

Raises:

Type Description
RuntimeError

If no session for the schema exists.

Returns:

Type Description
Optional[PipelineRunSchema]

The latest run for this template.

Functions
from_request(request: RunTemplateRequest) -> RunTemplateSchema classmethod

Create a schema from a request.

Parameters:

Name Type Description Default
request RunTemplateRequest

The request to convert.

required

Returns:

Type Description
RunTemplateSchema

The created schema.

Source code in src/zenml/zen_stores/schemas/run_template_schemas.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
@classmethod
def from_request(
    cls,
    request: RunTemplateRequest,
) -> "RunTemplateSchema":
    """Create a schema from a request.

    Args:
        request: The request to convert.


    Returns:
        The created schema.
    """
    return cls(
        user_id=request.user,
        project_id=request.project,
        name=request.name,
        description=request.description,
        source_deployment_id=request.source_deployment_id,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> RunTemplateResponse

Convert the schema to a response model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
RunTemplateResponse

Model representing this schema.

Source code in src/zenml/zen_stores/schemas/run_template_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> RunTemplateResponse:
    """Convert the schema to a response model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

    Returns:
        Model representing this schema.
    """
    runnable = False
    if (
        self.source_deployment
        and self.source_deployment.build
        and not self.source_deployment.build.is_local
        and self.source_deployment.build.stack
    ):
        runnable = True

    latest_run = self.latest_run

    body = RunTemplateResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        runnable=runnable,
        latest_run_id=latest_run.id if latest_run else None,
        latest_run_status=latest_run.status if latest_run else None,
    )

    metadata = None
    if include_metadata:
        pipeline_spec = None
        config_template = None
        config_schema = None

        if self.source_deployment:
            from zenml.zen_stores import template_utils

            pipeline_spec = self.source_deployment.to_model(
                include_metadata=True, include_resources=True
            ).pipeline_spec

            if (
                self.source_deployment.build
                and self.source_deployment.build.stack
            ):
                config_template = template_utils.generate_config_template(
                    deployment=self.source_deployment
                )
                config_schema = template_utils.generate_config_schema(
                    deployment=self.source_deployment
                )

        metadata = RunTemplateResponseMetadata(
            project=self.project.to_model(),
            description=self.description,
            pipeline_spec=pipeline_spec,
            config_template=config_template,
            config_schema=config_schema,
        )

    resources = None
    if include_resources:
        if self.source_deployment:
            pipeline = (
                self.source_deployment.pipeline.to_model()
                if self.source_deployment.pipeline
                else None
            )
            build = (
                self.source_deployment.build.to_model()
                if self.source_deployment.build
                else None
            )
            code_reference = (
                self.source_deployment.code_reference.to_model()
                if self.source_deployment.code_reference
                else None
            )
        else:
            pipeline = None
            build = None
            code_reference = None

        resources = RunTemplateResponseResources(
            source_deployment=self.source_deployment.to_model()
            if self.source_deployment
            else None,
            pipeline=pipeline,
            build=build,
            code_reference=code_reference,
            tags=[tag.to_model() for tag in self.tags],
        )

    return RunTemplateResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(update: RunTemplateUpdate) -> RunTemplateSchema

Update the schema.

Parameters:

Name Type Description Default
update RunTemplateUpdate

The update model.

required

Returns:

Type Description
RunTemplateSchema

The updated schema.

Source code in src/zenml/zen_stores/schemas/run_template_schemas.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def update(self, update: RunTemplateUpdate) -> "RunTemplateSchema":
    """Update the schema.

    Args:
        update: The update model.

    Returns:
        The updated schema.
    """
    for field, value in update.model_dump(
        exclude_unset=True, exclude_none=True
    ).items():
        if field in ["add_tags", "remove_tags"]:
            # Tags are handled separately
            continue
        setattr(self, field, value)

    self.updated = utc_now()
    return self
ScheduleSchema

Bases: NamedSchema, RunMetadataInterface

SQL Model for schedules.

Functions
from_request(schedule_request: ScheduleRequest) -> ScheduleSchema classmethod

Create a ScheduleSchema from a ScheduleRequest.

Parameters:

Name Type Description Default
schedule_request ScheduleRequest

The ScheduleRequest to create the schema from.

required

Returns:

Type Description
ScheduleSchema

The created ScheduleSchema.

Source code in src/zenml/zen_stores/schemas/schedule_schema.py
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
@classmethod
def from_request(
    cls, schedule_request: ScheduleRequest
) -> "ScheduleSchema":
    """Create a `ScheduleSchema` from a `ScheduleRequest`.

    Args:
        schedule_request: The `ScheduleRequest` to create the schema from.

    Returns:
        The created `ScheduleSchema`.
    """
    if schedule_request.interval_second is not None:
        interval_second = schedule_request.interval_second.total_seconds()
    else:
        interval_second = None
    return cls(
        name=schedule_request.name,
        project_id=schedule_request.project,
        user_id=schedule_request.user,
        pipeline_id=schedule_request.pipeline_id,
        orchestrator_id=schedule_request.orchestrator_id,
        active=schedule_request.active,
        cron_expression=schedule_request.cron_expression,
        start_time=schedule_request.start_time,
        end_time=schedule_request.end_time,
        interval_second=interval_second,
        catchup=schedule_request.catchup,
        run_once_start_time=schedule_request.run_once_start_time,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ScheduleResponse

Convert a ScheduleSchema to a ScheduleResponseModel.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ScheduleResponse

The created ScheduleResponseModel.

Source code in src/zenml/zen_stores/schemas/schedule_schema.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ScheduleResponse:
    """Convert a `ScheduleSchema` to a `ScheduleResponseModel`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `ScheduleResponseModel`.
    """
    if self.interval_second is not None:
        interval_second = timedelta(seconds=self.interval_second)
    else:
        interval_second = None

    body = ScheduleResponseBody(
        user=self.user.to_model() if self.user else None,
        active=self.active,
        cron_expression=self.cron_expression,
        start_time=self.start_time,
        end_time=self.end_time,
        interval_second=interval_second,
        catchup=self.catchup,
        updated=self.updated,
        created=self.created,
        run_once_start_time=self.run_once_start_time,
    )
    metadata = None
    if include_metadata:
        metadata = ScheduleResponseMetadata(
            project=self.project.to_model(),
            pipeline_id=self.pipeline_id,
            orchestrator_id=self.orchestrator_id,
            run_metadata=self.fetch_metadata(),
        )

    return ScheduleResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(schedule_update: ScheduleUpdate) -> ScheduleSchema

Update a ScheduleSchema from a ScheduleUpdateModel.

Parameters:

Name Type Description Default
schedule_update ScheduleUpdate

The ScheduleUpdateModel to update the schema from.

required

Returns:

Type Description
ScheduleSchema

The updated ScheduleSchema.

Source code in src/zenml/zen_stores/schemas/schedule_schema.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def update(self, schedule_update: ScheduleUpdate) -> "ScheduleSchema":
    """Update a `ScheduleSchema` from a `ScheduleUpdateModel`.

    Args:
        schedule_update: The `ScheduleUpdateModel` to update the schema from.

    Returns:
        The updated `ScheduleSchema`.
    """
    if schedule_update.name is not None:
        self.name = schedule_update.name

    self.updated = utc_now()
    return self
SecretSchema

Bases: NamedSchema

SQL Model for secrets.

Attributes:

Name Type Description
name str

The name of the secret.

values Optional[bytes]

The values of the secret.

Functions
from_request(secret: SecretRequest) -> SecretSchema classmethod

Create a SecretSchema from a SecretRequest.

Parameters:

Name Type Description Default
secret SecretRequest

The SecretRequest from which to create the schema.

required

Returns:

Type Description
SecretSchema

The created SecretSchema.

Source code in src/zenml/zen_stores/schemas/secret_schemas.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
@classmethod
def from_request(
    cls,
    secret: SecretRequest,
) -> "SecretSchema":
    """Create a `SecretSchema` from a `SecretRequest`.

    Args:
        secret: The `SecretRequest` from which to create the schema.

    Returns:
        The created `SecretSchema`.
    """
    assert secret.user is not None, "User must be set for secret creation."
    return cls(
        name=secret.name,
        private=secret.private,
        user_id=secret.user,
        # Don't store secret values implicitly in the secret. The
        # SQL secret store will call `store_secret_values` to store the
        # values separately if SQL is used as the secrets store.
        values=None,
    )
get_secret_values(encryption_engine: Optional[AesGcmEngine] = None) -> Dict[str, str]

Get the secret values for this secret.

This method is used by the SQL secrets store to load the secret values from the database.

Parameters:

Name Type Description Default
encryption_engine Optional[AesGcmEngine]

The encryption engine to use to decrypt the secret values. If None, the values will be base64 decoded.

None

Returns:

Type Description
Dict[str, str]

The secret values

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

Source code in src/zenml/zen_stores/schemas/secret_schemas.py
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
def get_secret_values(
    self,
    encryption_engine: Optional[AesGcmEngine] = None,
) -> Dict[str, str]:
    """Get the secret values for this secret.

    This method is used by the SQL secrets store to load the secret values
    from the database.

    Args:
        encryption_engine: The encryption engine to use to decrypt the
            secret values. If None, the values will be base64 decoded.

    Returns:
        The secret values

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
    """
    if not self.values:
        raise KeyError(
            f"Secret values for secret {self.id} have not been stored in "
            f"the SQL secrets store."
        )
    return self._load_secret_values(self.values, encryption_engine)
set_secret_values(secret_values: Dict[str, str], encryption_engine: Optional[AesGcmEngine] = None) -> None

Create a SecretSchema from a SecretRequest.

This method is used by the SQL secrets store to store the secret values in the database.

Parameters:

Name Type Description Default
secret_values Dict[str, str]

The new secret values.

required
encryption_engine Optional[AesGcmEngine]

The encryption engine to use to encrypt the secret values. If None, the values will be base64 encoded.

None
Source code in src/zenml/zen_stores/schemas/secret_schemas.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def set_secret_values(
    self,
    secret_values: Dict[str, str],
    encryption_engine: Optional[AesGcmEngine] = None,
) -> None:
    """Create a `SecretSchema` from a `SecretRequest`.

    This method is used by the SQL secrets store to store the secret values
    in the database.

    Args:
        secret_values: The new secret values.
        encryption_engine: The encryption engine to use to encrypt the
            secret values. If None, the values will be base64 encoded.
    """
    self.values = self._dump_secret_values(
        secret_values, encryption_engine
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> SecretResponse

Converts a secret schema to a secret model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
SecretResponse

The secret model.

Source code in src/zenml/zen_stores/schemas/secret_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> SecretResponse:
    """Converts a secret schema to a secret model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The secret model.
    """
    metadata = None
    if include_metadata:
        metadata = SecretResponseMetadata()

    # Don't load the secret values implicitly in the secret. The
    # SQL secret store will call `get_secret_values` to load the
    # values separately if SQL is used as the secrets store.
    body = SecretResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        private=self.private,
    )
    return SecretResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(secret_update: SecretUpdate) -> SecretSchema

Update a SecretSchema from a SecretUpdate.

Parameters:

Name Type Description Default
secret_update SecretUpdate

The SecretUpdate from which to update the schema.

required

Returns:

Type Description
SecretSchema

The updated SecretSchema.

Source code in src/zenml/zen_stores/schemas/secret_schemas.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def update(
    self,
    secret_update: SecretUpdate,
) -> "SecretSchema":
    """Update a `SecretSchema` from a `SecretUpdate`.

    Args:
        secret_update: The `SecretUpdate` from which to update the schema.

    Returns:
        The updated `SecretSchema`.
    """
    # Don't update the secret values implicitly in the secret. The
    # SQL secret store will call `set_secret_values` to update the
    # values separately if SQL is used as the secrets store.
    for field, value in secret_update.model_dump(
        exclude_unset=True, exclude={"user", "values"}
    ).items():
        setattr(self, field, value)

    self.updated = utc_now()
    return self
ServerSettingsSchema

Bases: SQLModel

SQL Model for the server settings.

Functions
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ServerSettingsResponse

Convert an ServerSettingsSchema to an ServerSettingsResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ServerSettingsResponse

The created SettingsResponse.

Source code in src/zenml/zen_stores/schemas/server_settings_schemas.py
 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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ServerSettingsResponse:
    """Convert an `ServerSettingsSchema` to an `ServerSettingsResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

    Returns:
        The created `SettingsResponse`.
    """
    body = ServerSettingsResponseBody(
        server_id=self.id,
        server_name=self.server_name,
        logo_url=self.logo_url,
        enable_analytics=self.enable_analytics,
        display_announcements=self.display_announcements,
        display_updates=self.display_updates,
        active=self.active,
        updated=self.updated,
        last_user_activity=self.last_user_activity,
    )

    metadata = None
    resources = None

    if include_metadata:
        metadata = ServerSettingsResponseMetadata()

    if include_resources:
        resources = ServerSettingsResponseResources()

    return ServerSettingsResponse(
        body=body, metadata=metadata, resources=resources
    )
update(settings_update: ServerSettingsUpdate) -> ServerSettingsSchema

Update a ServerSettingsSchema from a ServerSettingsUpdate.

Parameters:

Name Type Description Default
settings_update ServerSettingsUpdate

The ServerSettingsUpdate from which to update the schema.

required

Returns:

Type Description
ServerSettingsSchema

The updated ServerSettingsSchema.

Source code in src/zenml/zen_stores/schemas/server_settings_schemas.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def update(
    self, settings_update: ServerSettingsUpdate
) -> "ServerSettingsSchema":
    """Update a `ServerSettingsSchema` from a `ServerSettingsUpdate`.

    Args:
        settings_update: The `ServerSettingsUpdate` from which
            to update the schema.

    Returns:
        The updated `ServerSettingsSchema`.
    """
    for field, value in settings_update.model_dump(
        exclude_unset=True
    ).items():
        if hasattr(self, field):
            setattr(self, field, value)

    self.updated = utc_now()

    return self
update_onboarding_state(completed_steps: Set[str]) -> ServerSettingsSchema

Update the onboarding state.

Parameters:

Name Type Description Default
completed_steps Set[str]

Newly completed onboarding steps.

required

Returns:

Type Description
ServerSettingsSchema

The updated schema.

Source code in src/zenml/zen_stores/schemas/server_settings_schemas.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def update_onboarding_state(
    self, completed_steps: Set[str]
) -> "ServerSettingsSchema":
    """Update the onboarding state.

    Args:
        completed_steps: Newly completed onboarding steps.

    Returns:
        The updated schema.
    """
    old_state = set(
        json.loads(self.onboarding_state) if self.onboarding_state else []
    )
    new_state = old_state.union(completed_steps)
    self.onboarding_state = json.dumps(list(new_state))
    self.updated = utc_now()

    return self
ServiceConnectorSchema

Bases: NamedSchema

SQL Model for service connectors.

Attributes
labels_dict: Dict[str, str] property

Returns the labels as a dictionary.

Returns:

Type Description
Dict[str, str]

The labels as a dictionary.

resource_types_list: List[str] property

Returns the resource types as a list.

Returns:

Type Description
List[str]

The resource types as a list.

Functions
from_request(connector_request: ServiceConnectorRequest, secret_id: Optional[UUID] = None) -> ServiceConnectorSchema classmethod

Create a ServiceConnectorSchema from a ServiceConnectorRequest.

Parameters:

Name Type Description Default
connector_request ServiceConnectorRequest

The ServiceConnectorRequest from which to create the schema.

required
secret_id Optional[UUID]

The ID of the secret to use for this connector.

None

Returns:

Type Description
ServiceConnectorSchema

The created ServiceConnectorSchema.

Source code in src/zenml/zen_stores/schemas/service_connector_schemas.py
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
@classmethod
def from_request(
    cls,
    connector_request: ServiceConnectorRequest,
    secret_id: Optional[UUID] = None,
) -> "ServiceConnectorSchema":
    """Create a `ServiceConnectorSchema` from a `ServiceConnectorRequest`.

    Args:
        connector_request: The `ServiceConnectorRequest` from which to
            create the schema.
        secret_id: The ID of the secret to use for this connector.

    Returns:
        The created `ServiceConnectorSchema`.
    """
    assert connector_request.user is not None, "User must be set."
    return cls(
        user_id=connector_request.user,
        name=connector_request.name,
        description=connector_request.description,
        connector_type=connector_request.type,
        auth_method=connector_request.auth_method,
        resource_types=base64.b64encode(
            json.dumps(connector_request.resource_types).encode("utf-8")
        ),
        resource_id=connector_request.resource_id,
        supports_instances=connector_request.supports_instances,
        configuration=base64.b64encode(
            json.dumps(connector_request.configuration).encode("utf-8")
        )
        if connector_request.configuration
        else None,
        secret_id=secret_id,
        expires_at=connector_request.expires_at,
        expires_skew_tolerance=connector_request.expires_skew_tolerance,
        expiration_seconds=connector_request.expiration_seconds,
        labels=base64.b64encode(
            json.dumps(connector_request.labels).encode("utf-8")
        )
        if connector_request.labels
        else None,
    )
has_labels(labels: Dict[str, Optional[str]]) -> bool

Checks if the connector has the given labels.

Parameters:

Name Type Description Default
labels Dict[str, Optional[str]]

The labels to check for.

required

Returns:

Type Description
bool

Whether the connector has the given labels.

Source code in src/zenml/zen_stores/schemas/service_connector_schemas.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def has_labels(self, labels: Dict[str, Optional[str]]) -> bool:
    """Checks if the connector has the given labels.

    Args:
        labels: The labels to check for.

    Returns:
        Whether the connector has the given labels.
    """
    return all(
        self.labels_dict.get(key, None) == value
        for key, value in labels.items()
        if value is not None
    ) and all(
        key in self.labels_dict
        for key, value in labels.items()
        if value is None
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ServiceConnectorResponse

Creates a ServiceConnector from a ServiceConnectorSchema.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ServiceConnectorResponse

A ServiceConnectorModel

Source code in src/zenml/zen_stores/schemas/service_connector_schemas.py
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 to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "ServiceConnectorResponse":
    """Creates a `ServiceConnector` from a `ServiceConnectorSchema`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        A `ServiceConnectorModel`
    """
    body = ServiceConnectorResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        description=self.description,
        connector_type=self.connector_type,
        auth_method=self.auth_method,
        resource_types=self.resource_types_list,
        resource_id=self.resource_id,
        supports_instances=self.supports_instances,
        expires_at=self.expires_at,
        expires_skew_tolerance=self.expires_skew_tolerance,
    )
    metadata = None
    if include_metadata:
        metadata = ServiceConnectorResponseMetadata(
            configuration=json.loads(
                base64.b64decode(self.configuration).decode()
            )
            if self.configuration
            else {},
            secret_id=self.secret_id,
            expiration_seconds=self.expiration_seconds,
            labels=self.labels_dict,
        )
    return ServiceConnectorResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(connector_update: ServiceConnectorUpdate, secret_id: Optional[UUID] = None) -> ServiceConnectorSchema

Updates a ServiceConnectorSchema from a ServiceConnectorUpdate.

Parameters:

Name Type Description Default
connector_update ServiceConnectorUpdate

The ServiceConnectorUpdate to update from.

required
secret_id Optional[UUID]

The ID of the secret to use for this connector.

None

Returns:

Type Description
ServiceConnectorSchema

The updated ServiceConnectorSchema.

Source code in src/zenml/zen_stores/schemas/service_connector_schemas.py
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
def update(
    self,
    connector_update: ServiceConnectorUpdate,
    secret_id: Optional[UUID] = None,
) -> "ServiceConnectorSchema":
    """Updates a `ServiceConnectorSchema` from a `ServiceConnectorUpdate`.

    Args:
        connector_update: The `ServiceConnectorUpdate` to update from.
        secret_id: The ID of the secret to use for this connector.

    Returns:
        The updated `ServiceConnectorSchema`.
    """
    for field, value in connector_update.model_dump(
        exclude_unset=False,
        exclude={"user", "secrets"},
    ).items():
        if value is None:
            if field == "resource_id":
                # The resource ID field in the update is special: if set
                # to None in the update, it triggers the existing resource
                # ID to be cleared.
                self.resource_id = None
            if field == "expiration_seconds":
                # The expiration_seconds field in the update is special:
                # if set to None in the update, it triggers the existing
                # expiration_seconds to be cleared.
                self.expiration_seconds = None
            continue
        if field == "configuration":
            self.configuration = (
                base64.b64encode(
                    json.dumps(connector_update.configuration).encode(
                        "utf-8"
                    )
                )
                if connector_update.configuration
                else None
            )
        elif field == "resource_types":
            self.resource_types = base64.b64encode(
                json.dumps(connector_update.resource_types).encode("utf-8")
            )
        elif field == "labels":
            self.labels = (
                base64.b64encode(
                    json.dumps(connector_update.labels).encode("utf-8")
                )
                if connector_update.labels
                else None
            )
        else:
            setattr(self, field, value)
    self.secret_id = secret_id
    self.updated = utc_now()
    return self
ServiceSchema

Bases: NamedSchema

SQL Model for service.

Functions
from_request(service_request: ServiceRequest) -> ServiceSchema classmethod

Convert a ServiceRequest to a ServiceSchema.

Parameters:

Name Type Description Default
service_request ServiceRequest

The request model to convert.

required

Returns:

Type Description
ServiceSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/service_schemas.py
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
@classmethod
def from_request(
    cls, service_request: "ServiceRequest"
) -> "ServiceSchema":
    """Convert a `ServiceRequest` to a `ServiceSchema`.

    Args:
        service_request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=service_request.name,
        project_id=service_request.project,
        user_id=service_request.user,
        service_source=service_request.service_source,
        service_type=service_request.service_type.model_dump_json(),
        type=service_request.service_type.type,
        flavor=service_request.service_type.flavor,
        admin_state=service_request.admin_state,
        config=dict_to_bytes(service_request.config),
        labels=dict_to_bytes(service_request.labels)
        if service_request.labels
        else None,
        status=dict_to_bytes(service_request.status)
        if service_request.status
        else None,
        endpoint=dict_to_bytes(service_request.endpoint)
        if service_request.endpoint
        else None,
        state=service_request.status.get("state")
        if service_request.status
        else None,
        model_version_id=service_request.model_version_id,
        pipeline_run_id=service_request.pipeline_run_id,
        prediction_url=service_request.prediction_url,
        health_check_url=service_request.health_check_url,
        pipeline_name=service_request.config.get("pipeline_name"),
        pipeline_step_name=service_request.config.get(
            "pipeline_step_name"
        ),
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ServiceResponse

Convert an ServiceSchema to an ServiceResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether to include metadata in the response.

False
include_resources bool

Whether to include resources in the response.

False
kwargs Any

Additional keyword arguments.

{}

Returns:

Type Description
ServiceResponse

The created ServiceResponse.

Source code in src/zenml/zen_stores/schemas/service_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ServiceResponse:
    """Convert an `ServiceSchema` to an `ServiceResponse`.

    Args:
        include_metadata: Whether to include metadata in the response.
        include_resources: Whether to include resources in the response.
        kwargs: Additional keyword arguments.

    Returns:
        The created `ServiceResponse`.
    """
    body = ServiceResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        service_type=json.loads(self.service_type),
        labels=json.loads(base64.b64decode(self.labels).decode())
        if self.labels
        else None,
        state=self.state,
    )
    metadata = None
    if include_metadata:
        metadata = ServiceResponseMetadata(
            project=self.project.to_model(),
            service_source=self.service_source,
            config=json.loads(base64.b64decode(self.config).decode()),
            status=json.loads(base64.b64decode(self.status).decode())
            if self.status
            else None,
            endpoint=json.loads(base64.b64decode(self.endpoint).decode())
            if self.endpoint
            else None,
            admin_state=self.admin_state or None,
            prediction_url=self.prediction_url or None,
            health_check_url=self.health_check_url,
        )
    resources = None
    if include_resources:
        resources = ServiceResponseResources(
            model_version=self.model_version.to_model()
            if self.model_version
            else None,
            pipeline_run=self.pipeline_run.to_model()
            if self.pipeline_run
            else None,
        )
    return ServiceResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(update: ServiceUpdate) -> ServiceSchema

Updates a ServiceSchema from a ServiceUpdate.

Parameters:

Name Type Description Default
update ServiceUpdate

The ServiceUpdate to update from.

required

Returns:

Type Description
ServiceSchema

The updated ServiceSchema.

Source code in src/zenml/zen_stores/schemas/service_schemas.py
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
def update(
    self,
    update: ServiceUpdate,
) -> "ServiceSchema":
    """Updates a `ServiceSchema` from a `ServiceUpdate`.

    Args:
        update: The `ServiceUpdate` to update from.

    Returns:
        The updated `ServiceSchema`.
    """
    for field, value in update.model_dump(
        exclude_unset=True, exclude_none=True
    ).items():
        if field == "labels":
            self.labels = (
                dict_to_bytes(update.labels) if update.labels else None
            )
        elif field == "status":
            self.status = (
                dict_to_bytes(update.status) if update.status else None
            )
            self.state = (
                update.status.get("state") if update.status else None
            )
        elif field == "endpoint":
            self.endpoint = (
                dict_to_bytes(update.endpoint) if update.endpoint else None
            )
        else:
            setattr(self, field, value)
    self.updated = utc_now()
    return self
StackComponentSchema

Bases: NamedSchema

SQL Model for stack components.

Functions
from_request(request: ComponentRequest, service_connector: Optional[ServiceConnectorSchema] = None) -> StackComponentSchema classmethod

Create a component schema from a request.

Parameters:

Name Type Description Default
request ComponentRequest

The request from which to create the component.

required
service_connector Optional[ServiceConnectorSchema]

Optional service connector to link to the component.

None

Returns:

Type Description
StackComponentSchema

The component schema.

Source code in src/zenml/zen_stores/schemas/component_schemas.py
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
@classmethod
def from_request(
    cls,
    request: "ComponentRequest",
    service_connector: Optional[ServiceConnectorSchema] = None,
) -> "StackComponentSchema":
    """Create a component schema from a request.

    Args:
        request: The request from which to create the component.
        service_connector: Optional service connector to link to the
            component.

    Returns:
        The component schema.
    """
    return cls(
        name=request.name,
        user_id=request.user,
        type=request.type,
        flavor=request.flavor,
        configuration=base64.b64encode(
            json.dumps(request.configuration).encode("utf-8")
        ),
        labels=base64.b64encode(
            json.dumps(request.labels).encode("utf-8")
        ),
        connector=service_connector,
        connector_resource_id=request.connector_resource_id,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ComponentResponse

Creates a ComponentModel from an instance of a StackComponentSchema.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Raises:

Type Description
RuntimeError

If the flavor for the component is missing in the DB.

Returns:

Type Description
ComponentResponse

A ComponentModel

Source code in src/zenml/zen_stores/schemas/component_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "ComponentResponse":
    """Creates a `ComponentModel` from an instance of a `StackComponentSchema`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

    Raises:
        RuntimeError: If the flavor for the component is missing in the DB.

    Returns:
        A `ComponentModel`
    """
    body = ComponentResponseBody(
        type=StackComponentType(self.type),
        flavor_name=self.flavor,
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        logo_url=self.flavor_schema.logo_url
        if self.flavor_schema
        else None,
        integration=self.flavor_schema.integration
        if self.flavor_schema
        else None,
    )
    metadata = None
    if include_metadata:
        metadata = ComponentResponseMetadata(
            configuration=json.loads(
                base64.b64decode(self.configuration).decode()
            ),
            labels=json.loads(base64.b64decode(self.labels).decode())
            if self.labels
            else None,
            connector_resource_id=self.connector_resource_id,
            connector=self.connector.to_model()
            if self.connector
            else None,
        )
    resources = None
    if include_resources:
        if not self.flavor_schema:
            raise RuntimeError(
                f"Missing flavor {self.flavor} for component {self.name}."
            )

        resources = ComponentResponseResources(
            flavor=self.flavor_schema.to_model()
        )
    return ComponentResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(component_update: ComponentUpdate) -> StackComponentSchema

Updates a StackComponentSchema from a ComponentUpdate.

Parameters:

Name Type Description Default
component_update ComponentUpdate

The ComponentUpdate to update from.

required

Returns:

Type Description
StackComponentSchema

The updated StackComponentSchema.

Source code in src/zenml/zen_stores/schemas/component_schemas.py
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
def update(
    self, component_update: "ComponentUpdate"
) -> "StackComponentSchema":
    """Updates a `StackComponentSchema` from a `ComponentUpdate`.

    Args:
        component_update: The `ComponentUpdate` to update from.

    Returns:
        The updated `StackComponentSchema`.
    """
    for field, value in component_update.model_dump(
        exclude_unset=True, exclude={"user", "connector"}
    ).items():
        if field == "configuration":
            self.configuration = base64.b64encode(
                json.dumps(component_update.configuration).encode("utf-8")
            )
        elif field == "labels":
            self.labels = base64.b64encode(
                json.dumps(component_update.labels).encode("utf-8")
            )
        else:
            setattr(self, field, value)

    self.updated = utc_now()
    return self
StackCompositionSchema

Bases: SQLModel

SQL Model for stack definitions.

Join table between Stacks and StackComponents.

StackSchema

Bases: NamedSchema

SQL Model for stacks.

Functions
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> StackResponse

Converts the schema to a model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
StackResponse

The converted model.

Source code in src/zenml/zen_stores/schemas/stack_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "StackResponse":
    """Converts the schema to a model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

    Returns:
        The converted model.
    """
    body = StackResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        metadata = StackResponseMetadata(
            components={c.type: [c.to_model()] for c in self.components},
            stack_spec_path=self.stack_spec_path,
            labels=json.loads(base64.b64decode(self.labels).decode())
            if self.labels
            else None,
            description=self.description,
        )

    return StackResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(stack_update: StackUpdate, components: List[StackComponentSchema]) -> StackSchema

Updates a stack schema with a stack update model.

Parameters:

Name Type Description Default
stack_update StackUpdate

StackUpdate to update the stack with.

required
components List[StackComponentSchema]

List of StackComponentSchema to update the stack with.

required

Returns:

Type Description
StackSchema

The updated StackSchema.

Source code in src/zenml/zen_stores/schemas/stack_schemas.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
def update(
    self,
    stack_update: "StackUpdate",
    components: List["StackComponentSchema"],
) -> "StackSchema":
    """Updates a stack schema with a stack update model.

    Args:
        stack_update: `StackUpdate` to update the stack with.
        components: List of `StackComponentSchema` to update the stack with.

    Returns:
        The updated StackSchema.
    """
    for field, value in stack_update.model_dump(
        exclude_unset=True, exclude={"user"}
    ).items():
        if field == "components":
            self.components = components
        elif field == "labels":
            self.labels = base64.b64encode(
                json.dumps(stack_update.labels).encode("utf-8")
            )
        else:
            setattr(self, field, value)

    self.updated = utc_now()
    return self
StepRunInputArtifactSchema

Bases: SQLModel

SQL Model that defines which artifacts are inputs to which step.

StepRunOutputArtifactSchema

Bases: SQLModel

SQL Model that defines which artifacts are outputs of which step.

StepRunParentsSchema

Bases: SQLModel

SQL Model that defines the order of steps.

StepRunSchema

Bases: NamedSchema, RunMetadataInterface

SQL Model for steps of pipeline runs.

Functions
from_request(request: StepRunRequest, deployment_id: Optional[UUID]) -> StepRunSchema classmethod

Create a step run schema from a step run request model.

Parameters:

Name Type Description Default
request StepRunRequest

The step run request model.

required
deployment_id Optional[UUID]

The deployment ID.

required

Returns:

Type Description
StepRunSchema

The step run schema.

Source code in src/zenml/zen_stores/schemas/step_run_schemas.py
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
@classmethod
def from_request(
    cls, request: StepRunRequest, deployment_id: Optional[UUID]
) -> "StepRunSchema":
    """Create a step run schema from a step run request model.

    Args:
        request: The step run request model.
        deployment_id: The deployment ID.

    Returns:
        The step run schema.
    """
    return cls(
        name=request.name,
        project_id=request.project,
        user_id=request.user,
        start_time=request.start_time,
        end_time=request.end_time,
        status=request.status.value,
        deployment_id=deployment_id,
        original_step_run_id=request.original_step_run_id,
        pipeline_run_id=request.pipeline_run_id,
        docstring=request.docstring,
        cache_key=request.cache_key,
        code_hash=request.code_hash,
        source_code=request.source_code,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> StepRunResponse

Convert a StepRunSchema to a StepRunResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
StepRunResponse

The created StepRunResponse.

Raises:

Type Description
ValueError

In case the step run configuration can not be loaded.

RuntimeError

If the step run schema does not have a deployment_id or a step_configuration.

Source code in src/zenml/zen_stores/schemas/step_run_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> StepRunResponse:
    """Convert a `StepRunSchema` to a `StepRunResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created StepRunResponse.

    Raises:
        ValueError: In case the step run configuration can not be loaded.
        RuntimeError: If the step run schema does not have a deployment_id
            or a step_configuration.
    """
    input_artifacts = {
        artifact.name: StepRunInputResponse(
            input_type=StepRunInputArtifactType(artifact.type),
            **artifact.artifact_version.to_model().model_dump(),
        )
        for artifact in self.input_artifacts
    }

    output_artifacts: Dict[str, List["ArtifactVersionResponse"]] = {}
    for artifact in self.output_artifacts:
        if artifact.name not in output_artifacts:
            output_artifacts[artifact.name] = []
        output_artifacts[artifact.name].append(
            artifact.artifact_version.to_model()
        )

    full_step_config = None
    if self.deployment is not None:
        step_configuration = json.loads(
            self.deployment.step_configurations
        )
        if self.name in step_configuration:
            full_step_config = Step.model_validate(
                step_configuration[self.name]
            )
            new_substitutions = (
                full_step_config.config._get_full_substitutions(
                    PipelineConfiguration.model_validate_json(
                        self.deployment.pipeline_configuration
                    ),
                    self.pipeline_run.start_time,
                )
            )
            full_step_config = full_step_config.model_copy(
                update={
                    "config": full_step_config.config.model_copy(
                        update={"substitutions": new_substitutions}
                    )
                }
            )
        elif not self.step_configuration:
            raise ValueError(
                f"Unable to load the configuration for step `{self.name}` from the"
                f"database. To solve this please delete the pipeline run that this"
                f"step run belongs to. Pipeline Run ID: `{self.pipeline_run_id}`."
            )

    # the step configuration moved into the deployment - the following case is to ensure
    # backwards compatibility
    if full_step_config is None:
        if self.step_configuration:
            full_step_config = Step.model_validate_json(
                self.step_configuration
            )
        else:
            raise RuntimeError(
                "Step run model creation has failed. Each step run entry "
                "should either have a deployment_id or step_configuration."
            )

    body = StepRunResponseBody(
        user=self.user.to_model() if self.user else None,
        status=ExecutionStatus(self.status),
        start_time=self.start_time,
        end_time=self.end_time,
        inputs=input_artifacts,
        outputs=output_artifacts,
        created=self.created,
        updated=self.updated,
        model_version_id=self.model_version_id,
    )
    metadata = None
    if include_metadata:
        metadata = StepRunResponseMetadata(
            project=self.project.to_model(),
            config=full_step_config.config,
            spec=full_step_config.spec,
            cache_key=self.cache_key,
            code_hash=self.code_hash,
            docstring=self.docstring,
            source_code=self.source_code,
            logs=self.logs.to_model() if self.logs else None,
            deployment_id=self.deployment_id,
            pipeline_run_id=self.pipeline_run_id,
            original_step_run_id=self.original_step_run_id,
            parent_step_ids=[p.parent_id for p in self.parents],
            run_metadata=self.fetch_metadata(),
        )

    resources = None
    if include_resources:
        model_version = None
        if self.model_version:
            model_version = self.model_version.to_model()

        resources = StepRunResponseResources(model_version=model_version)

    return StepRunResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(step_update: StepRunUpdate) -> StepRunSchema

Update a step run schema with a step run update model.

Parameters:

Name Type Description Default
step_update StepRunUpdate

The step run update model.

required

Returns:

Type Description
StepRunSchema

The updated step run schema.

Source code in src/zenml/zen_stores/schemas/step_run_schemas.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def update(self, step_update: "StepRunUpdate") -> "StepRunSchema":
    """Update a step run schema with a step run update model.

    Args:
        step_update: The step run update model.

    Returns:
        The updated step run schema.
    """
    for key, value in step_update.model_dump(
        exclude_unset=True, exclude_none=True
    ).items():
        if key == "status":
            self.status = value.value
        if key == "end_time":
            self.end_time = value

    self.updated = utc_now()

    return self
TagResourceSchema

Bases: BaseSchema

SQL Model for tag resource relationship.

Functions
from_request(request: TagResourceRequest) -> TagResourceSchema classmethod

Convert an TagResourceRequest to an TagResourceSchema.

Parameters:

Name Type Description Default
request TagResourceRequest

The request model version to convert.

required

Returns:

Type Description
TagResourceSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/tag_schemas.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
@classmethod
def from_request(cls, request: TagResourceRequest) -> "TagResourceSchema":
    """Convert an `TagResourceRequest` to an `TagResourceSchema`.

    Args:
        request: The request model version to convert.

    Returns:
        The converted schema.
    """
    return cls(
        tag_id=request.tag_id,
        resource_id=request.resource_id,
        resource_type=request.resource_type.value,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> TagResourceResponse

Convert an TagResourceSchema to an TagResourceResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
TagResourceResponse

The created TagResourceResponse.

Source code in src/zenml/zen_stores/schemas/tag_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> TagResourceResponse:
    """Convert an `TagResourceSchema` to an `TagResourceResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `TagResourceResponse`.
    """
    return TagResourceResponse(
        id=self.id,
        body=TagResourceResponseBody(
            tag_id=self.tag_id,
            resource_id=self.resource_id,
            created=self.created,
            updated=self.updated,
            resource_type=TaggableResourceTypes(self.resource_type),
        ),
    )
TagSchema

Bases: NamedSchema

SQL Model for tag.

Functions
from_request(request: TagRequest) -> TagSchema classmethod

Convert an TagRequest to an TagSchema.

Parameters:

Name Type Description Default
request TagRequest

The request model to convert.

required

Returns:

Type Description
TagSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/tag_schemas.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
@classmethod
def from_request(cls, request: TagRequest) -> "TagSchema":
    """Convert an `TagRequest` to an `TagSchema`.

    Args:
        request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=request.name,
        exclusive=request.exclusive,
        color=request.color.value,
        user_id=request.user,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> TagResponse

Convert an TagSchema to an TagResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
TagResponse

The created TagResponse.

Source code in src/zenml/zen_stores/schemas/tag_schemas.py
 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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> TagResponse:
    """Convert an `TagSchema` to an `TagResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `TagResponse`.
    """
    metadata = None
    if include_metadata:
        metadata = TagResponseMetadata()
    return TagResponse(
        id=self.id,
        name=self.name,
        body=TagResponseBody(
            user=self.user.to_model() if self.user else None,
            created=self.created,
            updated=self.updated,
            color=ColorVariants(self.color),
            exclusive=self.exclusive,
            tagged_count=len(self.links),
        ),
        metadata=metadata,
    )
update(update: TagUpdate) -> TagSchema

Updates a TagSchema from a TagUpdate.

Parameters:

Name Type Description Default
update TagUpdate

The TagUpdate to update from.

required

Returns:

Type Description
TagSchema

The updated TagSchema.

Source code in src/zenml/zen_stores/schemas/tag_schemas.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def update(self, update: TagUpdate) -> "TagSchema":
    """Updates a `TagSchema` from a `TagUpdate`.

    Args:
        update: The `TagUpdate` to update from.

    Returns:
        The updated `TagSchema`.
    """
    for field, value in update.model_dump(exclude_unset=True).items():
        if field == "color":
            setattr(self, field, value.value)
        else:
            setattr(self, field, value)

    self.updated = utc_now()
    return self
TriggerExecutionSchema

Bases: BaseSchema

SQL Model for trigger executions.

Functions
from_request(request: TriggerExecutionRequest) -> TriggerExecutionSchema classmethod

Convert a TriggerExecutionRequest to a TriggerExecutionSchema.

Parameters:

Name Type Description Default
request TriggerExecutionRequest

The request model to convert.

required

Returns:

Type Description
TriggerExecutionSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/trigger_schemas.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
@classmethod
def from_request(
    cls, request: "TriggerExecutionRequest"
) -> "TriggerExecutionSchema":
    """Convert a `TriggerExecutionRequest` to a `TriggerExecutionSchema`.

    Args:
        request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        trigger_id=request.trigger,
        event_metadata=base64.b64encode(
            json.dumps(request.event_metadata).encode("utf-8")
        ),
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> TriggerExecutionResponse

Converts the schema to a model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
TriggerExecutionResponse

The converted model.

Source code in src/zenml/zen_stores/schemas/trigger_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "TriggerExecutionResponse":
    """Converts the schema to a model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The converted model.
    """
    body = TriggerExecutionResponseBody(
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        metadata = TriggerExecutionResponseMetadata(
            event_metadata=json.loads(
                base64.b64decode(self.event_metadata).decode()
            )
            if self.event_metadata
            else {},
        )
    resources = None
    if include_resources:
        resources = TriggerExecutionResponseResources(
            trigger=self.trigger.to_model(),
        )

    return TriggerExecutionResponse(
        id=self.id, body=body, metadata=metadata, resources=resources
    )
TriggerSchema

Bases: NamedSchema

SQL Model for triggers.

Functions
from_request(request: TriggerRequest) -> TriggerSchema classmethod

Convert a TriggerRequest to a TriggerSchema.

Parameters:

Name Type Description Default
request TriggerRequest

The request model to convert.

required

Returns:

Type Description
TriggerSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/trigger_schemas.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
@classmethod
def from_request(cls, request: "TriggerRequest") -> "TriggerSchema":
    """Convert a `TriggerRequest` to a `TriggerSchema`.

    Args:
        request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=request.name,
        project_id=request.project,
        user_id=request.user,
        action_id=request.action_id,
        event_source_id=request.event_source_id,
        event_filter=base64.b64encode(
            json.dumps(
                request.event_filter, default=pydantic_encoder
            ).encode("utf-8")
        ),
        schedule=base64.b64encode(request.schedule.json().encode("utf-8"))
        if request.schedule
        else None,
        description=request.description,
        is_active=True,  # Makes no sense for it to be created inactive
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> TriggerResponse

Converts the schema to a model.

Parameters:

Name Type Description Default
include_metadata bool

Flag deciding whether to include the output model(s) metadata fields in the response.

False
include_resources bool

Flag deciding whether to include the output model(s) metadata fields in the response.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
TriggerResponse

The converted model.

Source code in src/zenml/zen_stores/schemas/trigger_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "TriggerResponse":
    """Converts the schema to a model.

    Args:
        include_metadata: Flag deciding whether to include the output model(s)
            metadata fields in the response.
        include_resources: Flag deciding whether to include the output model(s)
            metadata fields in the response.
        **kwargs: Keyword arguments to allow schema specific logic

    Returns:
        The converted model.
    """
    from zenml.models import TriggerExecutionResponse

    body = TriggerResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        action_flavor=self.action.flavor,
        action_subtype=self.action.plugin_subtype,
        event_source_flavor=self.event_source.flavor
        if self.event_source
        else None,
        event_source_subtype=self.event_source.plugin_subtype
        if self.event_source
        else None,
        is_active=self.is_active,
    )
    metadata = None
    if include_metadata:
        metadata = TriggerResponseMetadata(
            project=self.project.to_model(),
            event_filter=json.loads(
                base64.b64decode(self.event_filter).decode()
            ),
            schedule=Schedule.parse_raw(
                base64.b64decode(self.schedule).decode()
            )
            if self.schedule
            else None,
            description=self.description,
        )
    resources = None
    if include_resources:
        executions = cast(
            Page[TriggerExecutionResponse],
            get_page_from_list(
                items_list=self.executions,
                response_model=TriggerExecutionResponse,
                include_resources=False,
                include_metadata=False,
            ),
        )
        resources = TriggerResponseResources(
            action=self.action.to_model(),
            event_source=self.event_source.to_model()
            if self.event_source
            else None,
            executions=executions,
        )
    return TriggerResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(trigger_update: TriggerUpdate) -> TriggerSchema

Updates a trigger schema with a trigger update model.

Parameters:

Name Type Description Default
trigger_update TriggerUpdate

TriggerUpdate to update the trigger with.

required

Returns:

Type Description
TriggerSchema

The updated TriggerSchema.

Source code in src/zenml/zen_stores/schemas/trigger_schemas.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def update(self, trigger_update: "TriggerUpdate") -> "TriggerSchema":
    """Updates a trigger schema with a trigger update model.

    Args:
        trigger_update: `TriggerUpdate` to update the trigger with.

    Returns:
        The updated TriggerSchema.
    """
    for field, value in trigger_update.model_dump(
        exclude_unset=True,
        exclude_none=True,
    ).items():
        if field == "event_filter":
            self.event_filter = base64.b64encode(
                json.dumps(
                    trigger_update.event_filter, default=pydantic_encoder
                ).encode("utf-8")
            )
        else:
            setattr(self, field, value)

    self.updated = utc_now()
    return self
UserSchema

Bases: NamedSchema

SQL Model for users.

Functions
from_service_account_request(model: ServiceAccountRequest) -> UserSchema classmethod

Create a UserSchema from a Service Account request.

Parameters:

Name Type Description Default
model ServiceAccountRequest

The ServiceAccountRequest from which to create the schema.

required

Returns:

Type Description
UserSchema

The created UserSchema.

Source code in src/zenml/zen_stores/schemas/user_schemas.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
@classmethod
def from_service_account_request(
    cls, model: ServiceAccountRequest
) -> "UserSchema":
    """Create a `UserSchema` from a Service Account request.

    Args:
        model: The `ServiceAccountRequest` from which to create the
            schema.

    Returns:
        The created `UserSchema`.
    """
    return cls(
        name=model.name,
        description=model.description or "",
        active=model.active,
        is_service_account=True,
        email_opted_in=False,
        full_name="",
        is_admin=False,
    )
from_user_request(model: UserRequest) -> UserSchema classmethod

Create a UserSchema from a UserRequest.

Parameters:

Name Type Description Default
model UserRequest

The UserRequest from which to create the schema.

required

Returns:

Type Description
UserSchema

The created UserSchema.

Source code in src/zenml/zen_stores/schemas/user_schemas.py
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
@classmethod
def from_user_request(cls, model: UserRequest) -> "UserSchema":
    """Create a `UserSchema` from a `UserRequest`.

    Args:
        model: The `UserRequest` from which to create the schema.

    Returns:
        The created `UserSchema`.
    """
    return cls(
        name=model.name,
        full_name=model.full_name,
        active=model.active,
        password=model.create_hashed_password(),
        activation_token=model.create_hashed_activation_token(),
        external_user_id=model.external_user_id,
        email_opted_in=model.email_opted_in,
        email=model.email,
        is_service_account=False,
        is_admin=model.is_admin,
        user_metadata=json.dumps(model.user_metadata)
        if model.user_metadata
        else None,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, include_private: bool = False, **kwargs: Any) -> UserResponse

Convert a UserSchema to a UserResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}
include_private bool

Whether to include the user private information this is to limit the amount of data one can get about other users.

False

Returns:

Type Description
UserResponse

The converted UserResponse.

Source code in src/zenml/zen_stores/schemas/user_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    include_private: bool = False,
    **kwargs: Any,
) -> UserResponse:
    """Convert a `UserSchema` to a `UserResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic
        include_private: Whether to include the user private information
            this is to limit the amount of data one can get about other
            users.

    Returns:
        The converted `UserResponse`.
    """
    metadata = None
    if include_metadata:
        metadata = UserResponseMetadata(
            email=self.email if include_private else None,
            external_user_id=self.external_user_id,
            user_metadata=json.loads(self.user_metadata)
            if self.user_metadata
            else {},
        )

    return UserResponse(
        id=self.id,
        name=self.name,
        body=UserResponseBody(
            active=self.active,
            full_name=self.full_name,
            email_opted_in=self.email_opted_in,
            is_service_account=self.is_service_account,
            created=self.created,
            updated=self.updated,
            is_admin=self.is_admin,
            default_project_id=self.default_project_id,
        ),
        metadata=metadata,
    )
to_service_account_model(include_metadata: bool = False, include_resources: bool = False) -> ServiceAccountResponse

Convert a UserSchema to a ServiceAccountResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False

Returns:

Type Description
ServiceAccountResponse

The converted ServiceAccountResponse.

Source code in src/zenml/zen_stores/schemas/user_schemas.py
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
def to_service_account_model(
    self, include_metadata: bool = False, include_resources: bool = False
) -> ServiceAccountResponse:
    """Convert a `UserSchema` to a `ServiceAccountResponse`.

    Args:
         include_metadata: Whether the metadata will be filled.
         include_resources: Whether the resources will be filled.

    Returns:
         The converted `ServiceAccountResponse`.
    """
    metadata = None
    if include_metadata:
        metadata = ServiceAccountResponseMetadata(
            description=self.description or "",
        )

    body = ServiceAccountResponseBody(
        created=self.created,
        updated=self.updated,
        active=self.active,
    )

    return ServiceAccountResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update_service_account(service_account_update: ServiceAccountUpdate) -> UserSchema

Update a UserSchema from a ServiceAccountUpdate.

Parameters:

Name Type Description Default
service_account_update ServiceAccountUpdate

The ServiceAccountUpdate from which to update the schema.

required

Returns:

Type Description
UserSchema

The updated UserSchema.

Source code in src/zenml/zen_stores/schemas/user_schemas.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def update_service_account(
    self, service_account_update: ServiceAccountUpdate
) -> "UserSchema":
    """Update a `UserSchema` from a `ServiceAccountUpdate`.

    Args:
        service_account_update: The `ServiceAccountUpdate` from which
            to update the schema.

    Returns:
        The updated `UserSchema`.
    """
    for field, value in service_account_update.model_dump(
        exclude_none=True
    ).items():
        setattr(self, field, value)

    self.updated = utc_now()
    return self
update_user(user_update: UserUpdate) -> UserSchema

Update a UserSchema from a UserUpdate.

Parameters:

Name Type Description Default
user_update UserUpdate

The UserUpdate from which to update the schema.

required

Returns:

Type Description
UserSchema

The updated UserSchema.

Source code in src/zenml/zen_stores/schemas/user_schemas.py
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
def update_user(self, user_update: UserUpdate) -> "UserSchema":
    """Update a `UserSchema` from a `UserUpdate`.

    Args:
        user_update: The `UserUpdate` from which to update the schema.

    Returns:
        The updated `UserSchema`.
    """
    for field, value in user_update.model_dump(exclude_unset=True).items():
        if field == "old_password":
            continue

        if field == "password":
            setattr(self, field, user_update.create_hashed_password())
        elif field == "activation_token":
            setattr(
                self, field, user_update.create_hashed_activation_token()
            )
        elif field == "user_metadata":
            if value is not None:
                self.user_metadata = json.dumps(value)
        else:
            setattr(self, field, value)

    self.updated = utc_now()
    return self
Modules
action_schemas

SQL Model Implementations for Actions.

Classes
ActionSchema

Bases: NamedSchema

SQL Model for actions.

Functions
from_request(request: ActionRequest) -> ActionSchema classmethod

Convert a ActionRequest to a ActionSchema.

Parameters:

Name Type Description Default
request ActionRequest

The request model to convert.

required

Returns:

Type Description
ActionSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/action_schemas.py
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
@classmethod
def from_request(cls, request: "ActionRequest") -> "ActionSchema":
    """Convert a `ActionRequest` to a `ActionSchema`.

    Args:
        request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=request.name,
        project_id=request.project,
        user_id=request.user,
        configuration=base64.b64encode(
            json.dumps(
                request.configuration, default=pydantic_encoder
            ).encode("utf-8"),
        ),
        flavor=request.flavor,
        plugin_subtype=request.plugin_subtype,
        description=request.description,
        service_account_id=request.service_account_id,
        auth_window=request.auth_window,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ActionResponse

Converts the action schema to a model.

Parameters:

Name Type Description Default
include_metadata bool

Flag deciding whether to include the output model(s) metadata fields in the response.

False
include_resources bool

Flag deciding whether to include the output model(s) metadata fields in the response.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ActionResponse

The converted model.

Source code in src/zenml/zen_stores/schemas/action_schemas.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
191
192
193
194
195
196
197
198
199
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "ActionResponse":
    """Converts the action schema to a model.

    Args:
        include_metadata: Flag deciding whether to include the output model(s)
            metadata fields in the response.
        include_resources: Flag deciding whether to include the output model(s)
            metadata fields in the response.
        **kwargs: Keyword arguments to allow schema specific logic

    Returns:
        The converted model.
    """
    body = ActionResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        flavor=self.flavor,
        plugin_subtype=self.plugin_subtype,
    )
    metadata = None
    if include_metadata:
        metadata = ActionResponseMetadata(
            project=self.project.to_model(),
            configuration=json.loads(
                base64.b64decode(self.configuration).decode()
            ),
            description=self.description,
            auth_window=self.auth_window,
        )
    resources = None
    if include_resources:
        resources = ActionResponseResources(
            service_account=self.service_account.to_model(),
        )
    return ActionResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(action_update: ActionUpdate) -> ActionSchema

Updates a action schema with a action update model.

Parameters:

Name Type Description Default
action_update ActionUpdate

ActionUpdate to update the action with.

required

Returns:

Type Description
ActionSchema

The updated ActionSchema.

Source code in src/zenml/zen_stores/schemas/action_schemas.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def update(self, action_update: "ActionUpdate") -> "ActionSchema":
    """Updates a action schema with a action update model.

    Args:
        action_update: `ActionUpdate` to update the action with.

    Returns:
        The updated ActionSchema.
    """
    for field, value in action_update.dict(
        exclude_unset=True,
        exclude_none=True,
    ).items():
        if field == "configuration":
            self.configuration = base64.b64encode(
                json.dumps(
                    action_update.configuration, default=pydantic_encoder
                ).encode("utf-8")
            )
        else:
            setattr(self, field, value)

    self.updated = utc_now()
    return self
Functions
api_key_schemas

SQLModel implementation of user tables.

Classes
APIKeySchema

Bases: NamedSchema

SQL Model for API keys.

Functions
from_request(service_account_id: UUID, request: APIKeyRequest) -> Tuple[APIKeySchema, str] classmethod

Convert a APIKeyRequest to a APIKeySchema.

Parameters:

Name Type Description Default
service_account_id UUID

The service account id to associate the key with.

required
request APIKeyRequest

The request model to convert.

required

Returns:

Type Description
Tuple[APIKeySchema, str]

The converted schema and the un-hashed API key.

Source code in src/zenml/zen_stores/schemas/api_key_schemas.py
 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
@classmethod
def from_request(
    cls,
    service_account_id: UUID,
    request: APIKeyRequest,
) -> Tuple["APIKeySchema", str]:
    """Convert a `APIKeyRequest` to a `APIKeySchema`.

    Args:
        service_account_id: The service account id to associate the key
            with.
        request: The request model to convert.

    Returns:
        The converted schema and the un-hashed API key.
    """
    key = cls._generate_jwt_secret_key()
    hashed_key = cls._get_hashed_key(key)
    now = utc_now()
    return (
        cls(
            name=request.name,
            description=request.description or "",
            key=hashed_key,
            service_account_id=service_account_id,
            created=now,
            updated=now,
        ),
        key,
    )
internal_update(update: APIKeyInternalUpdate) -> APIKeySchema

Update an APIKeySchema with an APIKeyInternalUpdate.

The internal update can also update the last used timestamp.

Parameters:

Name Type Description Default
update APIKeyInternalUpdate

The update model.

required

Returns:

Type Description
APIKeySchema

The updated APIKeySchema.

Source code in src/zenml/zen_stores/schemas/api_key_schemas.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def internal_update(self, update: APIKeyInternalUpdate) -> "APIKeySchema":
    """Update an `APIKeySchema` with an `APIKeyInternalUpdate`.

    The internal update can also update the last used timestamp.

    Args:
        update: The update model.

    Returns:
        The updated `APIKeySchema`.
    """
    self.update(update)

    if update.update_last_login:
        self.last_login = self.updated

    return self
rotate(rotate_request: APIKeyRotateRequest) -> Tuple[APIKeySchema, str]

Rotate the key for an APIKeySchema.

Parameters:

Name Type Description Default
rotate_request APIKeyRotateRequest

The rotate request model.

required

Returns:

Type Description
Tuple[APIKeySchema, str]

The updated APIKeySchema and the new un-hashed key.

Source code in src/zenml/zen_stores/schemas/api_key_schemas.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def rotate(
    self,
    rotate_request: APIKeyRotateRequest,
) -> Tuple["APIKeySchema", str]:
    """Rotate the key for an `APIKeySchema`.

    Args:
        rotate_request: The rotate request model.

    Returns:
        The updated `APIKeySchema` and the new un-hashed key.
    """
    self.updated = utc_now()
    self.previous_key = self.key
    self.retain_period = rotate_request.retain_period_minutes
    new_key = self._generate_jwt_secret_key()
    self.key = self._get_hashed_key(new_key)
    self.last_rotated = self.updated

    return self, new_key
to_internal_model(include_metadata: bool = False, include_resources: bool = False) -> APIKeyInternalResponse

Convert a APIKeySchema to an APIKeyInternalResponse.

The internal response model includes the hashed key values.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False

Returns:

Type Description
APIKeyInternalResponse

The created APIKeyInternalResponse.

Source code in src/zenml/zen_stores/schemas/api_key_schemas.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
def to_internal_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
) -> APIKeyInternalResponse:
    """Convert a `APIKeySchema` to an `APIKeyInternalResponse`.

    The internal response model includes the hashed key values.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.

    Returns:
        The created APIKeyInternalResponse.
    """
    model = self.to_model(
        include_metadata=include_metadata,
        include_resources=include_resources,
    )
    model.get_body().key = self.key

    return APIKeyInternalResponse(
        id=self.id,
        name=self.name,
        previous_key=self.previous_key,
        body=model.body,
        metadata=model.metadata,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> APIKeyResponse

Convert a APIKeySchema to an APIKeyResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}
**kwargs Any

Keyword arguments to filter models.

{}

Returns:

Type Description
APIKeyResponse

The created APIKeyResponse.

Source code in src/zenml/zen_stores/schemas/api_key_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> APIKeyResponse:
    """Convert a `APIKeySchema` to an `APIKeyResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

        **kwargs: Keyword arguments to filter models.

    Returns:
        The created APIKeyResponse.
    """
    metadata = None
    if include_metadata:
        metadata = APIKeyResponseMetadata(
            description=self.description,
            retain_period_minutes=self.retain_period,
            last_login=self.last_login,
            last_rotated=self.last_rotated,
        )

    body = APIKeyResponseBody(
        created=self.created,
        updated=self.updated,
        active=self.active,
        service_account=self.service_account.to_service_account_model(),
    )

    return APIKeyResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(update: APIKeyUpdate) -> APIKeySchema

Update an APIKeySchema with an APIKeyUpdate.

Parameters:

Name Type Description Default
update APIKeyUpdate

The update model.

required

Returns:

Type Description
APIKeySchema

The updated APIKeySchema.

Source code in src/zenml/zen_stores/schemas/api_key_schemas.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def update(self, update: APIKeyUpdate) -> "APIKeySchema":
    """Update an `APIKeySchema` with an `APIKeyUpdate`.

    Args:
        update: The update model.

    Returns:
        The updated `APIKeySchema`.
    """
    for field, value in update.model_dump(exclude_none=True).items():
        if hasattr(self, field):
            setattr(self, field, value)

    self.updated = utc_now()
    return self
Functions
artifact_schemas

SQLModel implementation of artifact table.

Classes
ArtifactSchema

Bases: NamedSchema

SQL Model for artifacts.

Attributes
latest_version: Optional[ArtifactVersionSchema] property

Fetch the latest version for this artifact.

Raises:

Type Description
RuntimeError

If no session for the schema exists.

Returns:

Type Description
Optional[ArtifactVersionSchema]

The latest version for this artifact.

Functions
from_request(artifact_request: ArtifactRequest) -> ArtifactSchema classmethod

Convert an ArtifactRequest to an ArtifactSchema.

Parameters:

Name Type Description Default
artifact_request ArtifactRequest

The request model to convert.

required

Returns:

Type Description
ArtifactSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/artifact_schemas.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
@classmethod
def from_request(
    cls,
    artifact_request: ArtifactRequest,
) -> "ArtifactSchema":
    """Convert an `ArtifactRequest` to an `ArtifactSchema`.

    Args:
        artifact_request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=artifact_request.name,
        has_custom_name=artifact_request.has_custom_name,
        project_id=artifact_request.project,
        user_id=artifact_request.user,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ArtifactResponse

Convert an ArtifactSchema to an ArtifactResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ArtifactResponse

The created ArtifactResponse.

Source code in src/zenml/zen_stores/schemas/artifact_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ArtifactResponse:
    """Convert an `ArtifactSchema` to an `ArtifactResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic



    Returns:
        The created `ArtifactResponse`.
    """
    latest_id, latest_name = None, None
    if latest_version := self.latest_version:
        latest_id = latest_version.id
        latest_name = latest_version.version

    # Create the body of the model
    body = ArtifactResponseBody(
        created=self.created,
        updated=self.updated,
        tags=[tag.to_model() for tag in self.tags],
        latest_version_name=latest_name,
        latest_version_id=latest_id,
        user=self.user.to_model() if self.user else None,
    )

    # Create the metadata of the model
    metadata = None
    if include_metadata:
        metadata = ArtifactResponseMetadata(
            has_custom_name=self.has_custom_name,
            project=self.project.to_model(),
        )

    return ArtifactResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(artifact_update: ArtifactUpdate) -> ArtifactSchema

Update an ArtifactSchema with an ArtifactUpdate.

Parameters:

Name Type Description Default
artifact_update ArtifactUpdate

The update model to apply.

required

Returns:

Type Description
ArtifactSchema

The updated ArtifactSchema.

Source code in src/zenml/zen_stores/schemas/artifact_schemas.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def update(self, artifact_update: ArtifactUpdate) -> "ArtifactSchema":
    """Update an `ArtifactSchema` with an `ArtifactUpdate`.

    Args:
        artifact_update: The update model to apply.

    Returns:
        The updated `ArtifactSchema`.
    """
    self.updated = utc_now()
    if artifact_update.name:
        self.name = artifact_update.name
        self.has_custom_name = True
    if artifact_update.has_custom_name is not None:
        self.has_custom_name = artifact_update.has_custom_name
    return self
ArtifactVersionSchema

Bases: BaseSchema, RunMetadataInterface

SQL Model for artifact versions.

Functions
from_request(artifact_version_request: ArtifactVersionRequest) -> ArtifactVersionSchema classmethod

Convert an ArtifactVersionRequest to an ArtifactVersionSchema.

Parameters:

Name Type Description Default
artifact_version_request ArtifactVersionRequest

The request model to convert.

required

Raises:

Type Description
ValueError

If the request does not specify a version number.

Returns:

Type Description
ArtifactVersionSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/artifact_schemas.py
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
@classmethod
def from_request(
    cls,
    artifact_version_request: ArtifactVersionRequest,
) -> "ArtifactVersionSchema":
    """Convert an `ArtifactVersionRequest` to an `ArtifactVersionSchema`.

    Args:
        artifact_version_request: The request model to convert.

    Raises:
        ValueError: If the request does not specify a version number.

    Returns:
        The converted schema.
    """
    if not artifact_version_request.version:
        raise ValueError("Missing version for artifact version request.")

    try:
        version_number = int(artifact_version_request.version)
    except ValueError:
        version_number = None
    return cls(
        artifact_id=artifact_version_request.artifact_id,
        version=str(artifact_version_request.version),
        version_number=version_number,
        artifact_store_id=artifact_version_request.artifact_store_id,
        project_id=artifact_version_request.project,
        user_id=artifact_version_request.user,
        type=artifact_version_request.type.value,
        uri=artifact_version_request.uri,
        materializer=artifact_version_request.materializer.model_dump_json(),
        data_type=artifact_version_request.data_type.model_dump_json(),
        save_type=artifact_version_request.save_type.value,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ArtifactVersionResponse

Convert an ArtifactVersionSchema to an ArtifactVersionResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ArtifactVersionResponse

The created ArtifactVersionResponse.

Source code in src/zenml/zen_stores/schemas/artifact_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ArtifactVersionResponse:
    """Convert an `ArtifactVersionSchema` to an `ArtifactVersionResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic



    Returns:
        The created `ArtifactVersionResponse`.
    """
    try:
        materializer = Source.model_validate_json(self.materializer)
    except ValidationError:
        # This is an old source which was an importable source path
        materializer = Source.from_import_path(self.materializer)

    try:
        data_type = Source.model_validate_json(self.data_type)
    except ValidationError:
        # This is an old source which was an importable source path
        data_type = Source.from_import_path(self.data_type)

    producer_step_run_id, producer_pipeline_run_id = None, None
    if self.output_of_step_runs:
        original_step_runs = [
            sr
            for sr in self.output_of_step_runs
            if sr.step_run.status == ExecutionStatus.COMPLETED
        ]
        if len(original_step_runs) == 1:
            step_run = original_step_runs[0].step_run
            producer_step_run_id = step_run.id
            producer_pipeline_run_id = step_run.pipeline_run_id
        else:
            step_run = self.output_of_step_runs[0].step_run
            producer_step_run_id = step_run.original_step_run_id

    # Create the body of the model
    artifact = self.artifact.to_model()
    body = ArtifactVersionResponseBody(
        artifact=artifact,
        version=self.version or str(self.version_number),
        user=self.user.to_model() if self.user else None,
        uri=self.uri,
        type=ArtifactType(self.type),
        materializer=materializer,
        data_type=data_type,
        created=self.created,
        updated=self.updated,
        tags=[tag.to_model() for tag in self.tags],
        producer_pipeline_run_id=producer_pipeline_run_id,
        save_type=ArtifactSaveType(self.save_type),
        artifact_store_id=self.artifact_store_id,
    )

    # Create the metadata of the model
    metadata = None
    if include_metadata:
        metadata = ArtifactVersionResponseMetadata(
            project=self.project.to_model(),
            producer_step_run_id=producer_step_run_id,
            visualizations=[v.to_model() for v in self.visualizations],
            run_metadata=self.fetch_metadata(),
        )

    resources = None

    return ArtifactVersionResponse(
        id=self.id,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(artifact_version_update: ArtifactVersionUpdate) -> ArtifactVersionSchema

Update an ArtifactVersionSchema with an ArtifactVersionUpdate.

Parameters:

Name Type Description Default
artifact_version_update ArtifactVersionUpdate

The update model to apply.

required

Returns:

Type Description
ArtifactVersionSchema

The updated ArtifactVersionSchema.

Source code in src/zenml/zen_stores/schemas/artifact_schemas.py
445
446
447
448
449
450
451
452
453
454
455
456
457
def update(
    self, artifact_version_update: ArtifactVersionUpdate
) -> "ArtifactVersionSchema":
    """Update an `ArtifactVersionSchema` with an `ArtifactVersionUpdate`.

    Args:
        artifact_version_update: The update model to apply.

    Returns:
        The updated `ArtifactVersionSchema`.
    """
    self.updated = utc_now()
    return self
Functions
artifact_visualization_schemas

SQLModel implementation of artifact visualization table.

Classes
ArtifactVisualizationSchema

Bases: BaseSchema

SQL Model for visualizations of artifacts.

Functions
from_model(artifact_visualization_request: ArtifactVisualizationRequest, artifact_version_id: UUID) -> ArtifactVisualizationSchema classmethod

Convert a ArtifactVisualizationRequest to a ArtifactVisualizationSchema.

Parameters:

Name Type Description Default
artifact_visualization_request ArtifactVisualizationRequest

The visualization.

required
artifact_version_id UUID

The UUID of the artifact version.

required

Returns:

Type Description
ArtifactVisualizationSchema

The ArtifactVisualizationSchema.

Source code in src/zenml/zen_stores/schemas/artifact_visualization_schemas.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
@classmethod
def from_model(
    cls,
    artifact_visualization_request: ArtifactVisualizationRequest,
    artifact_version_id: UUID,
) -> "ArtifactVisualizationSchema":
    """Convert a `ArtifactVisualizationRequest` to a `ArtifactVisualizationSchema`.

    Args:
        artifact_visualization_request: The visualization.
        artifact_version_id: The UUID of the artifact version.

    Returns:
        The `ArtifactVisualizationSchema`.
    """
    return cls(
        type=artifact_visualization_request.type.value,
        uri=artifact_visualization_request.uri,
        artifact_version_id=artifact_version_id,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ArtifactVisualizationResponse

Convert an ArtifactVisualizationSchema to a Visualization.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ArtifactVisualizationResponse

The Visualization.

Source code in src/zenml/zen_stores/schemas/artifact_visualization_schemas.py
 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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ArtifactVisualizationResponse:
    """Convert an `ArtifactVisualizationSchema` to a `Visualization`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic



    Returns:
        The `Visualization`.
    """
    body = ArtifactVisualizationResponseBody(
        type=VisualizationType(self.type),
        uri=self.uri,
        created=self.created,
        updated=self.updated,
    )

    metadata = None
    if include_metadata:
        metadata = ArtifactVisualizationResponseMetadata(
            artifact_version_id=self.artifact_version_id,
        )

    return ArtifactVisualizationResponse(
        id=self.id,
        body=body,
        metadata=metadata,
    )
Functions
base_schemas

Base classes for SQLModel schemas.

Classes
BaseSchema

Bases: SQLModel

Base SQL Model for ZenML entities.

Functions
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> Any

In case the Schema has a corresponding Model, this allows conversion to that model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Raises:

Type Description
NotImplementedError

When the base class fails to implement this.

Source code in src/zenml/zen_stores/schemas/base_schemas.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> Any:
    """In case the Schema has a corresponding Model, this allows conversion to that model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

    Raises:
        NotImplementedError: When the base class fails to implement this.
    """
    raise NotImplementedError(
        "No 'to_model()' method implemented for this"
        f"schema: '{self.__class__.__name__}'."
    )
NamedSchema

Bases: BaseSchema

Base Named SQL Model.

Functions
code_repository_schemas

SQL Model Implementations for code repositories.

Classes
CodeReferenceSchema

Bases: BaseSchema

SQL Model for code references.

Functions
from_request(request: CodeReferenceRequest, project_id: UUID) -> CodeReferenceSchema classmethod

Convert a CodeReferenceRequest to a CodeReferenceSchema.

Parameters:

Name Type Description Default
request CodeReferenceRequest

The request model to convert.

required
project_id UUID

The project ID.

required

Returns:

Type Description
CodeReferenceSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/code_repository_schemas.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
@classmethod
def from_request(
    cls, request: "CodeReferenceRequest", project_id: UUID
) -> "CodeReferenceSchema":
    """Convert a `CodeReferenceRequest` to a `CodeReferenceSchema`.

    Args:
        request: The request model to convert.
        project_id: The project ID.

    Returns:
        The converted schema.
    """
    return cls(
        project_id=project_id,
        commit=request.commit,
        subdirectory=request.subdirectory,
        code_repository_id=request.code_repository,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> CodeReferenceResponse

Convert a CodeReferenceSchema to a CodeReferenceResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}
kwargs Any

Additional keyword arguments.

{}

Returns:

Type Description
CodeReferenceResponse

The converted model.

Source code in src/zenml/zen_stores/schemas/code_repository_schemas.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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "CodeReferenceResponse":
    """Convert a `CodeReferenceSchema` to a `CodeReferenceResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

        kwargs: Additional keyword arguments.

    Returns:
        The converted model.
    """
    body = CodeReferenceResponseBody(
        commit=self.commit,
        subdirectory=self.subdirectory,
        code_repository=self.code_repository.to_model(),
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        metadata = CodeReferenceResponseMetadata()

    return CodeReferenceResponse(
        id=self.id,
        body=body,
        metadata=metadata,
    )
CodeRepositorySchema

Bases: NamedSchema

SQL Model for code repositories.

Functions
from_request(request: CodeRepositoryRequest) -> CodeRepositorySchema classmethod

Convert a CodeRepositoryRequest to a CodeRepositorySchema.

Parameters:

Name Type Description Default
request CodeRepositoryRequest

The request model to convert.

required

Returns:

Type Description
CodeRepositorySchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/code_repository_schemas.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
@classmethod
def from_request(
    cls, request: "CodeRepositoryRequest"
) -> "CodeRepositorySchema":
    """Convert a `CodeRepositoryRequest` to a `CodeRepositorySchema`.

    Args:
        request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=request.name,
        project_id=request.project,
        user_id=request.user,
        config=json.dumps(request.config),
        source=request.source.model_dump_json(),
        description=request.description,
        logo_url=request.logo_url,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> CodeRepositoryResponse

Convert a CodeRepositorySchema to a CodeRepositoryResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
CodeRepositoryResponse

The created CodeRepositoryResponse.

Source code in src/zenml/zen_stores/schemas/code_repository_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "CodeRepositoryResponse":
    """Convert a `CodeRepositorySchema` to a `CodeRepositoryResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created CodeRepositoryResponse.
    """
    body = CodeRepositoryResponseBody(
        user=self.user.to_model() if self.user else None,
        source=json.loads(self.source),
        logo_url=self.logo_url,
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        metadata = CodeRepositoryResponseMetadata(
            project=self.project.to_model(),
            config=json.loads(self.config),
            description=self.description,
        )
    return CodeRepositoryResponse(
        id=self.id,
        name=self.name,
        metadata=metadata,
        body=body,
    )
update(update: CodeRepositoryUpdate) -> CodeRepositorySchema

Update a CodeRepositorySchema with a CodeRepositoryUpdate.

Parameters:

Name Type Description Default
update CodeRepositoryUpdate

The update model.

required

Returns:

Type Description
CodeRepositorySchema

The updated CodeRepositorySchema.

Source code in src/zenml/zen_stores/schemas/code_repository_schemas.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def update(self, update: "CodeRepositoryUpdate") -> "CodeRepositorySchema":
    """Update a `CodeRepositorySchema` with a `CodeRepositoryUpdate`.

    Args:
        update: The update model.

    Returns:
        The updated `CodeRepositorySchema`.
    """
    if update.name:
        self.name = update.name

    if update.description:
        self.description = update.description

    if update.logo_url:
        self.logo_url = update.logo_url

    if update.config:
        self.config = json.dumps(update.config)

    self.updated = utc_now()
    return self
Functions
component_schemas

SQL Model Implementations for Stack Components.

Classes
StackComponentSchema

Bases: NamedSchema

SQL Model for stack components.

Functions
from_request(request: ComponentRequest, service_connector: Optional[ServiceConnectorSchema] = None) -> StackComponentSchema classmethod

Create a component schema from a request.

Parameters:

Name Type Description Default
request ComponentRequest

The request from which to create the component.

required
service_connector Optional[ServiceConnectorSchema]

Optional service connector to link to the component.

None

Returns:

Type Description
StackComponentSchema

The component schema.

Source code in src/zenml/zen_stores/schemas/component_schemas.py
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
@classmethod
def from_request(
    cls,
    request: "ComponentRequest",
    service_connector: Optional[ServiceConnectorSchema] = None,
) -> "StackComponentSchema":
    """Create a component schema from a request.

    Args:
        request: The request from which to create the component.
        service_connector: Optional service connector to link to the
            component.

    Returns:
        The component schema.
    """
    return cls(
        name=request.name,
        user_id=request.user,
        type=request.type,
        flavor=request.flavor,
        configuration=base64.b64encode(
            json.dumps(request.configuration).encode("utf-8")
        ),
        labels=base64.b64encode(
            json.dumps(request.labels).encode("utf-8")
        ),
        connector=service_connector,
        connector_resource_id=request.connector_resource_id,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ComponentResponse

Creates a ComponentModel from an instance of a StackComponentSchema.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Raises:

Type Description
RuntimeError

If the flavor for the component is missing in the DB.

Returns:

Type Description
ComponentResponse

A ComponentModel

Source code in src/zenml/zen_stores/schemas/component_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "ComponentResponse":
    """Creates a `ComponentModel` from an instance of a `StackComponentSchema`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

    Raises:
        RuntimeError: If the flavor for the component is missing in the DB.

    Returns:
        A `ComponentModel`
    """
    body = ComponentResponseBody(
        type=StackComponentType(self.type),
        flavor_name=self.flavor,
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        logo_url=self.flavor_schema.logo_url
        if self.flavor_schema
        else None,
        integration=self.flavor_schema.integration
        if self.flavor_schema
        else None,
    )
    metadata = None
    if include_metadata:
        metadata = ComponentResponseMetadata(
            configuration=json.loads(
                base64.b64decode(self.configuration).decode()
            ),
            labels=json.loads(base64.b64decode(self.labels).decode())
            if self.labels
            else None,
            connector_resource_id=self.connector_resource_id,
            connector=self.connector.to_model()
            if self.connector
            else None,
        )
    resources = None
    if include_resources:
        if not self.flavor_schema:
            raise RuntimeError(
                f"Missing flavor {self.flavor} for component {self.name}."
            )

        resources = ComponentResponseResources(
            flavor=self.flavor_schema.to_model()
        )
    return ComponentResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(component_update: ComponentUpdate) -> StackComponentSchema

Updates a StackComponentSchema from a ComponentUpdate.

Parameters:

Name Type Description Default
component_update ComponentUpdate

The ComponentUpdate to update from.

required

Returns:

Type Description
StackComponentSchema

The updated StackComponentSchema.

Source code in src/zenml/zen_stores/schemas/component_schemas.py
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
def update(
    self, component_update: "ComponentUpdate"
) -> "StackComponentSchema":
    """Updates a `StackComponentSchema` from a `ComponentUpdate`.

    Args:
        component_update: The `ComponentUpdate` to update from.

    Returns:
        The updated `StackComponentSchema`.
    """
    for field, value in component_update.model_dump(
        exclude_unset=True, exclude={"user", "connector"}
    ).items():
        if field == "configuration":
            self.configuration = base64.b64encode(
                json.dumps(component_update.configuration).encode("utf-8")
            )
        elif field == "labels":
            self.labels = base64.b64encode(
                json.dumps(component_update.labels).encode("utf-8")
            )
        else:
            setattr(self, field, value)

    self.updated = utc_now()
    return self
Functions
constants

Constant values needed by schema objects.

device_schemas

SQLModel implementation for authorized OAuth2 devices.

Classes
OAuthDeviceSchema

Bases: BaseSchema

SQL Model for authorized OAuth2 devices.

Functions
from_request(request: OAuthDeviceInternalRequest) -> Tuple[OAuthDeviceSchema, str, str] classmethod

Create an authorized device DB entry from a device authorization request.

Parameters:

Name Type Description Default
request OAuthDeviceInternalRequest

The device authorization request.

required

Returns:

Type Description
Tuple[OAuthDeviceSchema, str, str]

The created OAuthDeviceSchema, the user code and the device code.

Source code in src/zenml/zen_stores/schemas/device_schemas.py
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
@classmethod
def from_request(
    cls, request: OAuthDeviceInternalRequest
) -> Tuple["OAuthDeviceSchema", str, str]:
    """Create an authorized device DB entry from a device authorization request.

    Args:
        request: The device authorization request.

    Returns:
        The created `OAuthDeviceSchema`, the user code and the device code.
    """
    user_code = cls._generate_user_code()
    device_code = cls._generate_device_code()
    hashed_user_code = cls._get_hashed_code(user_code)
    hashed_device_code = cls._get_hashed_code(device_code)
    now = utc_now()
    return (
        cls(
            client_id=request.client_id,
            user_code=hashed_user_code,
            device_code=hashed_device_code,
            status=OAuthDeviceStatus.PENDING.value,
            failed_auth_attempts=0,
            expires=now + timedelta(seconds=request.expires_in),
            os=request.os,
            ip_address=request.ip_address,
            hostname=request.hostname,
            python_version=request.python_version,
            zenml_version=request.zenml_version,
            city=request.city,
            region=request.region,
            country=request.country,
            created=now,
            updated=now,
        ),
        user_code,
        device_code,
    )
internal_update(device_update: OAuthDeviceInternalUpdate) -> Tuple[OAuthDeviceSchema, Optional[str], Optional[str]]

Update an authorized device from an internal device update model.

Parameters:

Name Type Description Default
device_update OAuthDeviceInternalUpdate

The internal device update model.

required

Returns:

Type Description
OAuthDeviceSchema

The updated OAuthDeviceSchema and the new user code and device

Optional[str]

code, if they were generated.

Source code in src/zenml/zen_stores/schemas/device_schemas.py
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
def internal_update(
    self, device_update: OAuthDeviceInternalUpdate
) -> Tuple["OAuthDeviceSchema", Optional[str], Optional[str]]:
    """Update an authorized device from an internal device update model.

    Args:
        device_update: The internal device update model.

    Returns:
        The updated `OAuthDeviceSchema` and the new user code and device
        code, if they were generated.
    """
    now = utc_now()
    user_code: Optional[str] = None
    device_code: Optional[str] = None

    # This call also takes care of setting fields that have the same
    # name in the internal model and the schema.
    self.update(device_update)

    if device_update.expires_in is not None:
        if device_update.expires_in <= 0:
            self.expires = None
        else:
            self.expires = now + timedelta(
                seconds=device_update.expires_in
            )
    if device_update.update_last_login:
        self.last_login = now
    if device_update.generate_new_codes:
        user_code = self._generate_user_code()
        device_code = self._generate_device_code()
        self.user_code = self._get_hashed_code(user_code)
        self.device_code = self._get_hashed_code(device_code)
    self.updated = now
    return self, user_code, device_code
to_internal_model(include_metadata: bool = False, include_resources: bool = False) -> OAuthDeviceInternalResponse

Convert a device schema to an internal device response model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False

Returns:

Type Description
OAuthDeviceInternalResponse

The converted internal device response model.

Source code in src/zenml/zen_stores/schemas/device_schemas.py
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
def to_internal_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
) -> OAuthDeviceInternalResponse:
    """Convert a device schema to an internal device response model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.

    Returns:
        The converted internal device response model.
    """
    device_model = self.to_model(
        include_metadata=include_metadata,
        include_resources=include_resources,
    )
    return OAuthDeviceInternalResponse(
        id=device_model.id,
        body=device_model.body,
        metadata=device_model.metadata,
        user_code=self.user_code,
        device_code=self.device_code,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> OAuthDeviceResponse

Convert a device schema to a device response model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
OAuthDeviceResponse

The converted device response model.

Source code in src/zenml/zen_stores/schemas/device_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> OAuthDeviceResponse:
    """Convert a device schema to a device response model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The converted device response model.
    """
    metadata = None
    if include_metadata:
        metadata = OAuthDeviceResponseMetadata(
            python_version=self.python_version,
            zenml_version=self.zenml_version,
            city=self.city,
            region=self.region,
            country=self.country,
            failed_auth_attempts=self.failed_auth_attempts,
            last_login=self.last_login,
        )

    body = OAuthDeviceResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        client_id=self.client_id,
        expires=self.expires,
        trusted_device=self.trusted_device,
        status=OAuthDeviceStatus(self.status),
        os=self.os,
        ip_address=self.ip_address,
        hostname=self.hostname,
    )
    return OAuthDeviceResponse(
        id=self.id,
        body=body,
        metadata=metadata,
    )
update(device_update: OAuthDeviceUpdate) -> OAuthDeviceSchema

Update an authorized device from a device update model.

Parameters:

Name Type Description Default
device_update OAuthDeviceUpdate

The device update model.

required

Returns:

Type Description
OAuthDeviceSchema

The updated OAuthDeviceSchema.

Source code in src/zenml/zen_stores/schemas/device_schemas.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def update(self, device_update: OAuthDeviceUpdate) -> "OAuthDeviceSchema":
    """Update an authorized device from a device update model.

    Args:
        device_update: The device update model.

    Returns:
        The updated `OAuthDeviceSchema`.
    """
    for field, value in device_update.model_dump(
        exclude_none=True
    ).items():
        if hasattr(self, field):
            setattr(self, field, value)

    if device_update.locked is True:
        self.status = OAuthDeviceStatus.LOCKED.value
    elif device_update.locked is False:
        self.status = OAuthDeviceStatus.ACTIVE.value

    self.updated = utc_now()
    return self
Functions
event_source_schemas

SQL Model Implementations for event sources.

Classes
EventSourceSchema

Bases: NamedSchema

SQL Model for tag.

Functions
from_request(request: EventSourceRequest) -> EventSourceSchema classmethod

Convert an EventSourceRequest to an EventSourceSchema.

Parameters:

Name Type Description Default
request EventSourceRequest

The request model to convert.

required

Returns:

Type Description
EventSourceSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/event_source_schemas.py
 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
@classmethod
def from_request(cls, request: EventSourceRequest) -> "EventSourceSchema":
    """Convert an `EventSourceRequest` to an `EventSourceSchema`.

    Args:
        request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        project_id=request.project,
        user_id=request.user,
        flavor=request.flavor,
        plugin_subtype=request.plugin_subtype,
        name=request.name,
        description=request.description,
        configuration=base64.b64encode(
            json.dumps(
                request.configuration,
                sort_keys=False,
                default=pydantic_encoder,
            ).encode("utf-8")
        ),
        is_active=True,  # Makes no sense to create an inactive event source
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> EventSourceResponse

Convert an EventSourceSchema to an EventSourceResponse.

Parameters:

Name Type Description Default
include_metadata bool

Flag deciding whether to include the output model(s) metadata fields in the response.

False
include_resources bool

Flag deciding whether to include the output model(s) metadata fields in the response.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
EventSourceResponse

The created EventSourceResponse.

Source code in src/zenml/zen_stores/schemas/event_source_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> EventSourceResponse:
    """Convert an `EventSourceSchema` to an `EventSourceResponse`.

    Args:
        include_metadata: Flag deciding whether to include the output model(s)
            metadata fields in the response.
        include_resources: Flag deciding whether to include the output model(s)
            metadata fields in the response.
        **kwargs: Keyword arguments to allow schema specific logic

    Returns:
        The created `EventSourceResponse`.
    """
    from zenml.models import TriggerResponse

    body = EventSourceResponseBody(
        created=self.created,
        updated=self.updated,
        user=self.user.to_model() if self.user else None,
        flavor=self.flavor,
        plugin_subtype=self.plugin_subtype,
        is_active=self.is_active,
    )
    resources = None
    if include_resources:
        triggers = cast(
            Page[TriggerResponse],
            get_page_from_list(
                items_list=self.triggers,
                response_model=TriggerResponse,
                include_resources=include_resources,
                include_metadata=include_metadata,
            ),
        )
        resources = EventSourceResponseResources(
            triggers=triggers,
        )
    metadata = None
    if include_metadata:
        metadata = EventSourceResponseMetadata(
            project=self.project.to_model(),
            description=self.description,
            configuration=json.loads(
                base64.b64decode(self.configuration).decode()
            ),
        )
    return EventSourceResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(update: EventSourceUpdate) -> EventSourceSchema

Updates a EventSourceSchema from a EventSourceUpdate.

Parameters:

Name Type Description Default
update EventSourceUpdate

The EventSourceUpdate to update from.

required

Returns:

Type Description
EventSourceSchema

The updated EventSourceSchema.

Source code in src/zenml/zen_stores/schemas/event_source_schemas.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def update(self, update: EventSourceUpdate) -> "EventSourceSchema":
    """Updates a `EventSourceSchema` from a `EventSourceUpdate`.

    Args:
        update: The `EventSourceUpdate` to update from.

    Returns:
        The updated `EventSourceSchema`.
    """
    for field, value in update.model_dump(
        exclude_unset=True, exclude_none=True
    ).items():
        if field == "configuration":
            self.configuration = base64.b64encode(
                json.dumps(
                    update.configuration, default=pydantic_encoder
                ).encode("utf-8")
            )
        else:
            setattr(self, field, value)
    self.updated = utc_now()
    return self
Functions
flavor_schemas

SQL Model Implementations for Flavors.

Classes
FlavorSchema

Bases: NamedSchema

SQL Model for flavors.

Attributes:

Name Type Description
type str

The type of the flavor.

source str

The source of the flavor.

config_schema str

The config schema of the flavor.

integration Optional[str]

The integration associated with the flavor.

Functions
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> FlavorResponse

Converts a flavor schema to a flavor model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
FlavorResponse

The flavor model.

Source code in src/zenml/zen_stores/schemas/flavor_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "FlavorResponse":
    """Converts a flavor schema to a flavor model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The flavor model.
    """
    body = FlavorResponseBody(
        user=self.user.to_model() if self.user else None,
        type=StackComponentType(self.type),
        integration=self.integration,
        source=self.source,
        logo_url=self.logo_url,
        is_custom=self.is_custom,
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        metadata = FlavorResponseMetadata(
            config_schema=json.loads(self.config_schema),
            connector_type=self.connector_type,
            connector_resource_type=self.connector_resource_type,
            connector_resource_id_attr=self.connector_resource_id_attr,
            docs_url=self.docs_url,
            sdk_docs_url=self.sdk_docs_url,
        )
    return FlavorResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(flavor_update: FlavorUpdate) -> FlavorSchema

Update a FlavorSchema from a FlavorUpdate.

Parameters:

Name Type Description Default
flavor_update FlavorUpdate

The FlavorUpdate from which to update the schema.

required

Returns:

Type Description
FlavorSchema

The updated FlavorSchema.

Source code in src/zenml/zen_stores/schemas/flavor_schemas.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def update(
    self,
    flavor_update: "FlavorUpdate",
) -> "FlavorSchema":
    """Update a `FlavorSchema` from a `FlavorUpdate`.

    Args:
        flavor_update: The `FlavorUpdate` from which to update the schema.

    Returns:
        The updated `FlavorSchema`.
    """
    for field, value in flavor_update.model_dump(
        exclude_unset=True, exclude={"user"}
    ).items():
        if field == "config_schema":
            setattr(self, field, json.dumps(value))
        elif field == "type":
            setattr(self, field, value.value)
        else:
            setattr(self, field, value)

    self.updated = utc_now()
    return self
Functions
logs_schemas

SQLModel implementation of pipeline logs tables.

Classes
LogsSchema

Bases: BaseSchema

SQL Model for logs.

Functions
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> LogsResponse

Convert a LogsSchema to a LogsResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
LogsResponse

The created LogsResponse.

Source code in src/zenml/zen_stores/schemas/logs_schemas.py
 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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "LogsResponse":
    """Convert a `LogsSchema` to a `LogsResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `LogsResponse`.
    """
    body = LogsResponseBody(
        uri=self.uri,
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        metadata = LogsResponseMetadata(
            step_run_id=self.step_run_id,
            pipeline_run_id=self.pipeline_run_id,
            artifact_store_id=self.artifact_store_id,
        )
    return LogsResponse(
        id=self.id,
        body=body,
        metadata=metadata,
    )
Functions
model_schemas

SQLModel implementation of model tables.

Classes
ModelSchema

Bases: NamedSchema

SQL Model for model.

Attributes
latest_version: Optional[ModelVersionSchema] property

Fetch the latest version for this model.

Raises:

Type Description
RuntimeError

If no session for the schema exists.

Returns:

Type Description
Optional[ModelVersionSchema]

The latest version for this model.

Functions
from_request(model_request: ModelRequest) -> ModelSchema classmethod

Convert an ModelRequest to an ModelSchema.

Parameters:

Name Type Description Default
model_request ModelRequest

The request model to convert.

required

Returns:

Type Description
ModelSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
@classmethod
def from_request(cls, model_request: ModelRequest) -> "ModelSchema":
    """Convert an `ModelRequest` to an `ModelSchema`.

    Args:
        model_request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=model_request.name,
        project_id=model_request.project,
        user_id=model_request.user,
        license=model_request.license,
        description=model_request.description,
        audience=model_request.audience,
        use_cases=model_request.use_cases,
        limitations=model_request.limitations,
        trade_offs=model_request.trade_offs,
        ethics=model_request.ethics,
        save_models_to_registry=model_request.save_models_to_registry,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ModelResponse

Convert an ModelSchema to an ModelResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ModelResponse

The created ModelResponse.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ModelResponse:
    """Convert an `ModelSchema` to an `ModelResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `ModelResponse`.
    """
    tags = [tag.to_model() for tag in self.tags]

    if latest_version := self.latest_version:
        latest_version_name = latest_version.name
        latest_version_id = latest_version.id
    else:
        latest_version_name = None
        latest_version_id = None

    metadata = None
    if include_metadata:
        metadata = ModelResponseMetadata(
            project=self.project.to_model(),
            license=self.license,
            description=self.description,
            audience=self.audience,
            use_cases=self.use_cases,
            limitations=self.limitations,
            trade_offs=self.trade_offs,
            ethics=self.ethics,
            save_models_to_registry=self.save_models_to_registry,
        )

    body = ModelResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        tags=tags,
        latest_version_name=latest_version_name,
        latest_version_id=latest_version_id,
    )

    return ModelResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(model_update: ModelUpdate) -> ModelSchema

Updates a ModelSchema from a ModelUpdate.

Parameters:

Name Type Description Default
model_update ModelUpdate

The ModelUpdate to update from.

required

Returns:

Type Description
ModelSchema

The updated ModelSchema.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def update(
    self,
    model_update: ModelUpdate,
) -> "ModelSchema":
    """Updates a `ModelSchema` from a `ModelUpdate`.

    Args:
        model_update: The `ModelUpdate` to update from.

    Returns:
        The updated `ModelSchema`.
    """
    for field, value in model_update.model_dump(
        exclude_unset=True, exclude_none=True
    ).items():
        if field in ["add_tags", "remove_tags"]:
            # Tags are handled separately
            continue
        setattr(self, field, value)
    self.updated = utc_now()
    return self
ModelVersionArtifactSchema

Bases: BaseSchema

SQL Model for linking of Model Versions and Artifacts M:M.

Functions
from_request(model_version_artifact_request: ModelVersionArtifactRequest) -> ModelVersionArtifactSchema classmethod

Convert an ModelVersionArtifactRequest to a ModelVersionArtifactSchema.

Parameters:

Name Type Description Default
model_version_artifact_request ModelVersionArtifactRequest

The request link to convert.

required

Returns:

Type Description
ModelVersionArtifactSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
@classmethod
def from_request(
    cls,
    model_version_artifact_request: ModelVersionArtifactRequest,
) -> "ModelVersionArtifactSchema":
    """Convert an `ModelVersionArtifactRequest` to a `ModelVersionArtifactSchema`.

    Args:
        model_version_artifact_request: The request link to convert.

    Returns:
        The converted schema.
    """
    return cls(
        model_version_id=model_version_artifact_request.model_version,
        artifact_version_id=model_version_artifact_request.artifact_version,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ModelVersionArtifactResponse

Convert an ModelVersionArtifactSchema to an ModelVersionArtifactResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ModelVersionArtifactResponse

The created ModelVersionArtifactResponseModel.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ModelVersionArtifactResponse:
    """Convert an `ModelVersionArtifactSchema` to an `ModelVersionArtifactResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `ModelVersionArtifactResponseModel`.
    """
    return ModelVersionArtifactResponse(
        id=self.id,
        body=ModelVersionArtifactResponseBody(
            created=self.created,
            updated=self.updated,
            model_version=self.model_version_id,
            artifact_version=self.artifact_version.to_model(),
        ),
        metadata=BaseResponseMetadata() if include_metadata else None,
    )
ModelVersionPipelineRunSchema

Bases: BaseSchema

SQL Model for linking of Model Versions and Pipeline Runs M:M.

Functions
from_request(model_version_pipeline_run_request: ModelVersionPipelineRunRequest) -> ModelVersionPipelineRunSchema classmethod

Convert an ModelVersionPipelineRunRequest to an ModelVersionPipelineRunSchema.

Parameters:

Name Type Description Default
model_version_pipeline_run_request ModelVersionPipelineRunRequest

The request link to convert.

required

Returns:

Type Description
ModelVersionPipelineRunSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
@classmethod
def from_request(
    cls,
    model_version_pipeline_run_request: ModelVersionPipelineRunRequest,
) -> "ModelVersionPipelineRunSchema":
    """Convert an `ModelVersionPipelineRunRequest` to an `ModelVersionPipelineRunSchema`.

    Args:
        model_version_pipeline_run_request: The request link to convert.

    Returns:
        The converted schema.
    """
    return cls(
        model_version_id=model_version_pipeline_run_request.model_version,
        pipeline_run_id=model_version_pipeline_run_request.pipeline_run,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ModelVersionPipelineRunResponse

Convert an ModelVersionPipelineRunSchema to an ModelVersionPipelineRunResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ModelVersionPipelineRunResponse

The created ModelVersionPipelineRunResponse.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ModelVersionPipelineRunResponse:
    """Convert an `ModelVersionPipelineRunSchema` to an `ModelVersionPipelineRunResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `ModelVersionPipelineRunResponse`.
    """
    return ModelVersionPipelineRunResponse(
        id=self.id,
        body=ModelVersionPipelineRunResponseBody(
            created=self.created,
            updated=self.updated,
            model_version=self.model_version_id,
            pipeline_run=self.pipeline_run.to_model(),
        ),
        metadata=BaseResponseMetadata() if include_metadata else None,
    )
ModelVersionSchema

Bases: NamedSchema, RunMetadataInterface

SQL Model for model version.

Functions
from_request(model_version_request: ModelVersionRequest, model_version_number: int, producer_run_id: Optional[UUID] = None) -> ModelVersionSchema classmethod

Convert an ModelVersionRequest to an ModelVersionSchema.

Parameters:

Name Type Description Default
model_version_request ModelVersionRequest

The request model version to convert.

required
model_version_number int

The model version number.

required
producer_run_id Optional[UUID]

The ID of the producer run.

None

Returns:

Type Description
ModelVersionSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
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
@classmethod
def from_request(
    cls,
    model_version_request: ModelVersionRequest,
    model_version_number: int,
    producer_run_id: Optional[UUID] = None,
) -> "ModelVersionSchema":
    """Convert an `ModelVersionRequest` to an `ModelVersionSchema`.

    Args:
        model_version_request: The request model version to convert.
        model_version_number: The model version number.
        producer_run_id: The ID of the producer run.

    Returns:
        The converted schema.
    """
    id_ = uuid4()
    is_numeric = str(model_version_number) == model_version_request.name

    return cls(
        id=id_,
        project_id=model_version_request.project,
        user_id=model_version_request.user,
        model_id=model_version_request.model,
        name=model_version_request.name,
        number=model_version_number,
        description=model_version_request.description,
        stage=model_version_request.stage,
        producer_run_id_if_numeric=producer_run_id
        if (producer_run_id and is_numeric)
        else id_,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ModelVersionResponse

Convert an ModelVersionSchema to an ModelVersionResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ModelVersionResponse

The created ModelVersionResponse.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ModelVersionResponse:
    """Convert an `ModelVersionSchema` to an `ModelVersionResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `ModelVersionResponse`.
    """
    from zenml.models import ServiceResponse

    # Construct {name: {version: id}} dicts for all linked artifacts
    model_artifact_ids: Dict[str, Dict[str, UUID]] = {}
    deployment_artifact_ids: Dict[str, Dict[str, UUID]] = {}
    data_artifact_ids: Dict[str, Dict[str, UUID]] = {}
    for artifact_link in self.artifact_links:
        if not artifact_link.artifact_version:
            continue
        artifact_name = artifact_link.artifact_version.artifact.name
        artifact_version = str(artifact_link.artifact_version.version)
        artifact_version_id = artifact_link.artifact_version.id
        if artifact_link.artifact_version.type == ArtifactType.MODEL.value:
            model_artifact_ids.setdefault(artifact_name, {}).update(
                {str(artifact_version): artifact_version_id}
            )
        elif (
            artifact_link.artifact_version.type
            == ArtifactType.SERVICE.value
        ):
            deployment_artifact_ids.setdefault(artifact_name, {}).update(
                {str(artifact_version): artifact_version_id}
            )
        else:
            data_artifact_ids.setdefault(artifact_name, {}).update(
                {str(artifact_version): artifact_version_id}
            )

    # Construct {name: id} dict for all linked pipeline runs
    pipeline_run_ids: Dict[str, UUID] = {}
    for pipeline_run_link in self.pipeline_run_links:
        if not pipeline_run_link.pipeline_run:
            continue
        pipeline_run = pipeline_run_link.pipeline_run
        pipeline_run_ids[pipeline_run.name] = pipeline_run.id

    metadata = None
    if include_metadata:
        metadata = ModelVersionResponseMetadata(
            project=self.project.to_model(),
            description=self.description,
            run_metadata=self.fetch_metadata(),
        )

    resources = None
    if include_resources:
        services = cast(
            Page[ServiceResponse],
            get_page_from_list(
                items_list=self.services,
                response_model=ServiceResponse,
                include_resources=include_resources,
                include_metadata=include_metadata,
            ),
        )
        resources = ModelVersionResponseResources(
            services=services,
        )

    body = ModelVersionResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        stage=self.stage,
        number=self.number,
        model=self.model.to_model(),
        model_artifact_ids=model_artifact_ids,
        data_artifact_ids=data_artifact_ids,
        deployment_artifact_ids=deployment_artifact_ids,
        pipeline_run_ids=pipeline_run_ids,
        tags=[tag.to_model() for tag in self.tags],
    )

    return ModelVersionResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(target_stage: Optional[str] = None, target_name: Optional[str] = None, target_description: Optional[str] = None) -> ModelVersionSchema

Updates a ModelVersionSchema to a target stage.

Parameters:

Name Type Description Default
target_stage Optional[str]

The stage to be updated.

None
target_name Optional[str]

The version name to be updated.

None
target_description Optional[str]

The version description to be updated.

None

Returns:

Type Description
ModelVersionSchema

The updated ModelVersionSchema.

Source code in src/zenml/zen_stores/schemas/model_schemas.py
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
def update(
    self,
    target_stage: Optional[str] = None,
    target_name: Optional[str] = None,
    target_description: Optional[str] = None,
) -> "ModelVersionSchema":
    """Updates a `ModelVersionSchema` to a target stage.

    Args:
        target_stage: The stage to be updated.
        target_name: The version name to be updated.
        target_description: The version description to be updated.

    Returns:
        The updated `ModelVersionSchema`.
    """
    if target_stage is not None:
        self.stage = target_stage
    if target_name is not None:
        self.name = target_name
    if target_description is not None:
        self.description = target_description
    self.updated = utc_now()
    return self
Functions
pipeline_build_schemas

SQLModel implementation of pipeline build tables.

Classes
PipelineBuildSchema

Bases: BaseSchema

SQL Model for pipeline builds.

Functions
from_request(request: PipelineBuildRequest) -> PipelineBuildSchema classmethod

Convert a PipelineBuildRequest to a PipelineBuildSchema.

Parameters:

Name Type Description Default
request PipelineBuildRequest

The request to convert.

required

Returns:

Type Description
PipelineBuildSchema

The created PipelineBuildSchema.

Source code in src/zenml/zen_stores/schemas/pipeline_build_schemas.py
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
@classmethod
def from_request(
    cls, request: PipelineBuildRequest
) -> "PipelineBuildSchema":
    """Convert a `PipelineBuildRequest` to a `PipelineBuildSchema`.

    Args:
        request: The request to convert.

    Returns:
        The created `PipelineBuildSchema`.
    """
    return cls(
        stack_id=request.stack,
        project_id=request.project,
        user_id=request.user,
        pipeline_id=request.pipeline,
        images=json.dumps(request.images, default=pydantic_encoder),
        is_local=request.is_local,
        contains_code=request.contains_code,
        zenml_version=request.zenml_version,
        python_version=request.python_version,
        checksum=request.checksum,
        stack_checksum=request.stack_checksum,
        duration=request.duration,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> PipelineBuildResponse

Convert a PipelineBuildSchema to a PipelineBuildResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
PipelineBuildResponse

The created PipelineBuildResponse.

Source code in src/zenml/zen_stores/schemas/pipeline_build_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> PipelineBuildResponse:
    """Convert a `PipelineBuildSchema` to a `PipelineBuildResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `PipelineBuildResponse`.
    """
    body = PipelineBuildResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        metadata = PipelineBuildResponseMetadata(
            project=self.project.to_model(),
            pipeline=self.pipeline.to_model() if self.pipeline else None,
            stack=self.stack.to_model() if self.stack else None,
            images=json.loads(self.images),
            zenml_version=self.zenml_version,
            python_version=self.python_version,
            checksum=self.checksum,
            stack_checksum=self.stack_checksum,
            is_local=self.is_local,
            contains_code=self.contains_code,
            duration=self.duration,
        )
    return PipelineBuildResponse(
        id=self.id,
        body=body,
        metadata=metadata,
    )
Functions
pipeline_deployment_schemas

SQLModel implementation of pipeline deployment tables.

Classes
PipelineDeploymentSchema

Bases: BaseSchema

SQL Model for pipeline deployments.

Functions
from_request(request: PipelineDeploymentRequest, code_reference_id: Optional[UUID]) -> PipelineDeploymentSchema classmethod

Convert a PipelineDeploymentRequest to a PipelineDeploymentSchema.

Parameters:

Name Type Description Default
request PipelineDeploymentRequest

The request to convert.

required
code_reference_id Optional[UUID]

Optional ID of the code reference for the deployment.

required

Returns:

Type Description
PipelineDeploymentSchema

The created PipelineDeploymentSchema.

Source code in src/zenml/zen_stores/schemas/pipeline_deployment_schemas.py
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
@classmethod
def from_request(
    cls,
    request: PipelineDeploymentRequest,
    code_reference_id: Optional[UUID],
) -> "PipelineDeploymentSchema":
    """Convert a `PipelineDeploymentRequest` to a `PipelineDeploymentSchema`.

    Args:
        request: The request to convert.
        code_reference_id: Optional ID of the code reference for the
            deployment.

    Returns:
        The created `PipelineDeploymentSchema`.
    """
    return cls(
        stack_id=request.stack,
        project_id=request.project,
        pipeline_id=request.pipeline,
        build_id=request.build,
        user_id=request.user,
        schedule_id=request.schedule,
        template_id=request.template,
        code_reference_id=code_reference_id,
        run_name_template=request.run_name_template,
        pipeline_configuration=request.pipeline_configuration.model_dump_json(),
        step_configurations=json.dumps(
            request.step_configurations,
            sort_keys=False,
            default=pydantic_encoder,
        ),
        client_environment=json.dumps(request.client_environment),
        client_version=request.client_version,
        server_version=request.server_version,
        pipeline_version_hash=request.pipeline_version_hash,
        pipeline_spec=json.dumps(
            request.pipeline_spec.model_dump(mode="json"), sort_keys=True
        )
        if request.pipeline_spec
        else None,
        code_path=request.code_path,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> PipelineDeploymentResponse

Convert a PipelineDeploymentSchema to a PipelineDeploymentResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
PipelineDeploymentResponse

The created PipelineDeploymentResponse.

Source code in src/zenml/zen_stores/schemas/pipeline_deployment_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> PipelineDeploymentResponse:
    """Convert a `PipelineDeploymentSchema` to a `PipelineDeploymentResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `PipelineDeploymentResponse`.
    """
    body = PipelineDeploymentResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        pipeline_configuration = PipelineConfiguration.model_validate_json(
            self.pipeline_configuration
        )
        step_configurations = json.loads(self.step_configurations)
        for s, c in step_configurations.items():
            step_configurations[s] = Step.model_validate(c)

        metadata = PipelineDeploymentResponseMetadata(
            project=self.project.to_model(),
            run_name_template=self.run_name_template,
            pipeline_configuration=pipeline_configuration,
            step_configurations=step_configurations,
            client_environment=json.loads(self.client_environment),
            client_version=self.client_version,
            server_version=self.server_version,
            pipeline=self.pipeline.to_model() if self.pipeline else None,
            stack=self.stack.to_model() if self.stack else None,
            build=self.build.to_model() if self.build else None,
            schedule=self.schedule.to_model() if self.schedule else None,
            code_reference=self.code_reference.to_model()
            if self.code_reference
            else None,
            pipeline_version_hash=self.pipeline_version_hash,
            pipeline_spec=PipelineSpec.model_validate_json(
                self.pipeline_spec
            )
            if self.pipeline_spec
            else None,
            code_path=self.code_path,
            template_id=self.template_id,
        )
    return PipelineDeploymentResponse(
        id=self.id,
        body=body,
        metadata=metadata,
    )
Functions
pipeline_run_schemas

SQLModel implementation of pipeline run tables.

Classes
PipelineRunSchema

Bases: NamedSchema, RunMetadataInterface

SQL Model for pipeline runs.

Functions
fetch_metadata_collection() -> Dict[str, List[RunMetadataEntry]]

Fetches all the metadata entries related to the pipeline run.

Returns:

Type Description
Dict[str, List[RunMetadataEntry]]

a dictionary, where the key is the key of the metadata entry and the values represent the list of entries with this key.

Source code in src/zenml/zen_stores/schemas/pipeline_run_schemas.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def fetch_metadata_collection(self) -> Dict[str, List[RunMetadataEntry]]:
    """Fetches all the metadata entries related to the pipeline run.

    Returns:
        a dictionary, where the key is the key of the metadata entry
            and the values represent the list of entries with this key.
    """
    # Fetch the metadata related to this run
    metadata_collection = super().fetch_metadata_collection()

    # Fetch the metadata related to the steps of this run
    for s in self.step_runs:
        step_metadata = s.fetch_metadata_collection()
        for k, v in step_metadata.items():
            metadata_collection[f"{s.name}::{k}"] = v

    # Fetch the metadata related to the schedule of this run
    if self.deployment is not None:
        if schedule := self.deployment.schedule:
            schedule_metadata = schedule.fetch_metadata_collection()
            for k, v in schedule_metadata.items():
                metadata_collection[f"schedule:{k}"] = v

    return metadata_collection
from_request(request: PipelineRunRequest) -> PipelineRunSchema classmethod

Convert a PipelineRunRequest to a PipelineRunSchema.

Parameters:

Name Type Description Default
request PipelineRunRequest

The request to convert.

required

Returns:

Type Description
PipelineRunSchema

The created PipelineRunSchema.

Source code in src/zenml/zen_stores/schemas/pipeline_run_schemas.py
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
@classmethod
def from_request(
    cls, request: "PipelineRunRequest"
) -> "PipelineRunSchema":
    """Convert a `PipelineRunRequest` to a `PipelineRunSchema`.

    Args:
        request: The request to convert.

    Returns:
        The created `PipelineRunSchema`.
    """
    orchestrator_environment = json.dumps(request.orchestrator_environment)

    return cls(
        project_id=request.project,
        user_id=request.user,
        name=request.name,
        orchestrator_run_id=request.orchestrator_run_id,
        orchestrator_environment=orchestrator_environment,
        start_time=request.start_time,
        status=request.status.value,
        pipeline_id=request.pipeline,
        deployment_id=request.deployment,
        trigger_execution_id=request.trigger_execution_id,
    )
is_placeholder_run() -> bool

Whether the pipeline run is a placeholder run.

Returns:

Type Description
bool

Whether the pipeline run is a placeholder run.

Source code in src/zenml/zen_stores/schemas/pipeline_run_schemas.py
483
484
485
486
487
488
489
490
491
492
def is_placeholder_run(self) -> bool:
    """Whether the pipeline run is a placeholder run.

    Returns:
        Whether the pipeline run is a placeholder run.
    """
    return (
        self.orchestrator_run_id is None
        and self.status == ExecutionStatus.INITIALIZING
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> PipelineRunResponse

Convert a PipelineRunSchema to a PipelineRunResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
PipelineRunResponse

The created PipelineRunResponse.

Raises:

Type Description
RuntimeError

if the model creation fails.

Source code in src/zenml/zen_stores/schemas/pipeline_run_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "PipelineRunResponse":
    """Convert a `PipelineRunSchema` to a `PipelineRunResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `PipelineRunResponse`.

    Raises:
        RuntimeError: if the model creation fails.
    """
    if self.deployment is not None:
        deployment = self.deployment.to_model(include_metadata=True)

        config = deployment.pipeline_configuration
        new_substitutions = config._get_full_substitutions(self.start_time)
        config = config.model_copy(
            update={"substitutions": new_substitutions}
        )
        client_environment = deployment.client_environment

        stack = deployment.stack
        pipeline = deployment.pipeline
        build = deployment.build
        schedule = deployment.schedule
        code_reference = deployment.code_reference

    elif self.pipeline_configuration is not None:
        config = PipelineConfiguration.model_validate_json(
            self.pipeline_configuration
        )
        client_environment = (
            json.loads(self.client_environment)
            if self.client_environment
            else {}
        )

        stack = self.stack.to_model() if self.stack else None
        pipeline = self.pipeline.to_model() if self.pipeline else None
        build = self.build.to_model() if self.build else None
        schedule = self.schedule.to_model() if self.schedule else None
        code_reference = None

    else:
        raise RuntimeError(
            "Pipeline run model creation has failed. Each pipeline run "
            "entry should either have a deployment_id or "
            "pipeline_configuration."
        )

    body = PipelineRunResponseBody(
        user=self.user.to_model() if self.user else None,
        status=ExecutionStatus(self.status),
        stack=stack,
        pipeline=pipeline,
        build=build,
        schedule=schedule,
        code_reference=code_reference,
        trigger_execution=(
            self.trigger_execution.to_model()
            if self.trigger_execution
            else None
        ),
        created=self.created,
        updated=self.updated,
        deployment_id=self.deployment_id,
        model_version_id=self.model_version_id,
    )
    metadata = None
    if include_metadata:
        is_templatable = False
        if (
            self.deployment
            and self.deployment.build
            and not self.deployment.build.is_local
            and self.deployment.build.stack
        ):
            is_templatable = True

        steps = {
            step.name: step.to_model(include_metadata=True)
            for step in self.step_runs
        }

        step_substitutions = {}
        for step_name, step in steps.items():
            step_substitutions[step_name] = step.config.substitutions
            # We fetch the steps hydrated before, but want them unhydrated
            # in the response -> We need to reset the metadata here
            step.metadata = None

        orchestrator_environment = (
            json.loads(self.orchestrator_environment)
            if self.orchestrator_environment
            else {}
        )
        metadata = PipelineRunResponseMetadata(
            project=self.project.to_model(),
            run_metadata=self.fetch_metadata(),
            config=config,
            steps=steps,
            start_time=self.start_time,
            end_time=self.end_time,
            client_environment=client_environment,
            orchestrator_environment=orchestrator_environment,
            orchestrator_run_id=self.orchestrator_run_id,
            code_path=self.deployment.code_path
            if self.deployment
            else None,
            template_id=self.deployment.template_id
            if self.deployment
            else None,
            is_templatable=is_templatable,
            step_substitutions=step_substitutions,
        )

    resources = None
    if include_resources:
        model_version = None
        if self.model_version:
            model_version = self.model_version.to_model()

        resources = PipelineRunResponseResources(
            model_version=model_version,
            tags=[tag.to_model() for tag in self.tags],
        )

    return PipelineRunResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(run_update: PipelineRunUpdate) -> PipelineRunSchema

Update a PipelineRunSchema with a PipelineRunUpdate.

Parameters:

Name Type Description Default
run_update PipelineRunUpdate

The PipelineRunUpdate to update with.

required

Returns:

Type Description
PipelineRunSchema

The updated PipelineRunSchema.

Source code in src/zenml/zen_stores/schemas/pipeline_run_schemas.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
def update(self, run_update: "PipelineRunUpdate") -> "PipelineRunSchema":
    """Update a `PipelineRunSchema` with a `PipelineRunUpdate`.

    Args:
        run_update: The `PipelineRunUpdate` to update with.

    Returns:
        The updated `PipelineRunSchema`.
    """
    if run_update.status:
        self.status = run_update.status.value
        self.end_time = run_update.end_time

    self.updated = utc_now()
    return self
update_placeholder(request: PipelineRunRequest) -> PipelineRunSchema

Update a placeholder run.

Parameters:

Name Type Description Default
request PipelineRunRequest

The pipeline run request which should replace the placeholder.

required

Raises:

Type Description
RuntimeError

If the DB entry does not represent a placeholder run.

ValueError

If the run request does not match the deployment or pipeline ID of the placeholder run.

Returns:

Type Description
PipelineRunSchema

The updated PipelineRunSchema.

Source code in src/zenml/zen_stores/schemas/pipeline_run_schemas.py
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
def update_placeholder(
    self, request: "PipelineRunRequest"
) -> "PipelineRunSchema":
    """Update a placeholder run.

    Args:
        request: The pipeline run request which should replace the
            placeholder.

    Raises:
        RuntimeError: If the DB entry does not represent a placeholder run.
        ValueError: If the run request does not match the deployment or
            pipeline ID of the placeholder run.

    Returns:
        The updated `PipelineRunSchema`.
    """
    if not self.is_placeholder_run():
        raise RuntimeError(
            f"Unable to replace pipeline run {self.id} which is not a "
            "placeholder run."
        )

    if (
        self.deployment_id != request.deployment
        or self.pipeline_id != request.pipeline
    ):
        raise ValueError(
            "Deployment or orchestrator run ID of placeholder run do not "
            "match the IDs of the run request."
        )

    orchestrator_environment = json.dumps(request.orchestrator_environment)

    self.orchestrator_run_id = request.orchestrator_run_id
    self.orchestrator_environment = orchestrator_environment
    self.status = request.status.value

    self.updated = utc_now()

    return self
Functions
pipeline_schemas

SQL Model Implementations for Pipelines and Pipeline Runs.

Classes
PipelineSchema

Bases: NamedSchema

SQL Model for pipelines.

Attributes
latest_run: Optional[PipelineRunSchema] property

Fetch the latest run for this pipeline.

Raises:

Type Description
RuntimeError

If no session for the schema exists.

Returns:

Type Description
Optional[PipelineRunSchema]

The latest run for this pipeline.

Functions
from_request(pipeline_request: PipelineRequest) -> PipelineSchema classmethod

Convert a PipelineRequest to a PipelineSchema.

Parameters:

Name Type Description Default
pipeline_request PipelineRequest

The request model to convert.

required

Returns:

Type Description
PipelineSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/pipeline_schemas.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
@classmethod
def from_request(
    cls,
    pipeline_request: "PipelineRequest",
) -> "PipelineSchema":
    """Convert a `PipelineRequest` to a `PipelineSchema`.

    Args:
        pipeline_request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=pipeline_request.name,
        description=pipeline_request.description,
        project_id=pipeline_request.project,
        user_id=pipeline_request.user,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> PipelineResponse

Convert a PipelineSchema to a PipelineResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
PipelineResponse

The created PipelineResponse.

Source code in src/zenml/zen_stores/schemas/pipeline_schemas.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
191
192
193
194
195
196
197
198
199
200
201
202
203
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "PipelineResponse":
    """Convert a `PipelineSchema` to a `PipelineResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

    Returns:
        The created PipelineResponse.
    """
    latest_run = self.latest_run

    body = PipelineResponseBody(
        user=self.user.to_model() if self.user else None,
        latest_run_id=latest_run.id if latest_run else None,
        latest_run_status=latest_run.status if latest_run else None,
        created=self.created,
        updated=self.updated,
    )

    metadata = None
    if include_metadata:
        metadata = PipelineResponseMetadata(
            project=self.project.to_model(),
            description=self.description,
        )

    resources = None
    if include_resources:
        latest_run_user = latest_run.user if latest_run else None

        resources = PipelineResponseResources(
            latest_run_user=latest_run_user.to_model()
            if latest_run_user
            else None,
            tags=[tag.to_model() for tag in self.tags],
        )

    return PipelineResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(pipeline_update: PipelineUpdate) -> PipelineSchema

Update a PipelineSchema with a PipelineUpdate.

Parameters:

Name Type Description Default
pipeline_update PipelineUpdate

The update model.

required

Returns:

Type Description
PipelineSchema

The updated PipelineSchema.

Source code in src/zenml/zen_stores/schemas/pipeline_schemas.py
205
206
207
208
209
210
211
212
213
214
215
216
def update(self, pipeline_update: "PipelineUpdate") -> "PipelineSchema":
    """Update a `PipelineSchema` with a `PipelineUpdate`.

    Args:
        pipeline_update: The update model.

    Returns:
        The updated `PipelineSchema`.
    """
    self.description = pipeline_update.description
    self.updated = utc_now()
    return self
Functions
project_schemas

SQL Model Implementations for projects.

Classes
ProjectSchema

Bases: NamedSchema

SQL Model for projects.

Functions
from_request(project: ProjectRequest) -> ProjectSchema classmethod

Create a ProjectSchema from a ProjectResponse.

Parameters:

Name Type Description Default
project ProjectRequest

The ProjectResponse from which to create the schema.

required

Returns:

Type Description
ProjectSchema

The created ProjectSchema.

Source code in src/zenml/zen_stores/schemas/project_schemas.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
@classmethod
def from_request(cls, project: ProjectRequest) -> "ProjectSchema":
    """Create a `ProjectSchema` from a `ProjectResponse`.

    Args:
        project: The `ProjectResponse` from which to create the schema.

    Returns:
        The created `ProjectSchema`.
    """
    return cls(
        name=project.name,
        description=project.description,
        display_name=project.display_name,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ProjectResponse

Convert a ProjectSchema to a ProjectResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ProjectResponse

The converted ProjectResponseModel.

Source code in src/zenml/zen_stores/schemas/project_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ProjectResponse:
    """Convert a `ProjectSchema` to a `ProjectResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The converted `ProjectResponseModel`.
    """
    metadata = None
    if include_metadata:
        metadata = ProjectResponseMetadata(
            description=self.description,
        )
    return ProjectResponse(
        id=self.id,
        name=self.name,
        body=ProjectResponseBody(
            display_name=self.display_name,
            created=self.created,
            updated=self.updated,
        ),
        metadata=metadata,
    )
update(project_update: ProjectUpdate) -> ProjectSchema

Update a ProjectSchema from a ProjectUpdate.

Parameters:

Name Type Description Default
project_update ProjectUpdate

The ProjectUpdate from which to update the schema.

required

Returns:

Type Description
ProjectSchema

The updated ProjectSchema.

Source code in src/zenml/zen_stores/schemas/project_schemas.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def update(self, project_update: ProjectUpdate) -> "ProjectSchema":
    """Update a `ProjectSchema` from a `ProjectUpdate`.

    Args:
        project_update: The `ProjectUpdate` from which to update the
            schema.

    Returns:
        The updated `ProjectSchema`.
    """
    for field, value in project_update.model_dump(
        exclude_unset=True
    ).items():
        setattr(self, field, value)

    self.updated = utc_now()
    return self
Functions
run_metadata_schemas

SQLModel implementation of run metadata tables.

Classes
RunMetadataResourceSchema

Bases: SQLModel

Table for linking resources to run metadata entries.

RunMetadataSchema

Bases: BaseSchema

SQL Model for run metadata.

Functions
run_template_schemas

SQLModel implementation of run template tables.

Classes
RunTemplateSchema

Bases: NamedSchema

SQL Model for run templates.

Attributes
latest_run: Optional[PipelineRunSchema] property

Fetch the latest run for this template.

Raises:

Type Description
RuntimeError

If no session for the schema exists.

Returns:

Type Description
Optional[PipelineRunSchema]

The latest run for this template.

Functions
from_request(request: RunTemplateRequest) -> RunTemplateSchema classmethod

Create a schema from a request.

Parameters:

Name Type Description Default
request RunTemplateRequest

The request to convert.

required

Returns:

Type Description
RunTemplateSchema

The created schema.

Source code in src/zenml/zen_stores/schemas/run_template_schemas.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
@classmethod
def from_request(
    cls,
    request: RunTemplateRequest,
) -> "RunTemplateSchema":
    """Create a schema from a request.

    Args:
        request: The request to convert.


    Returns:
        The created schema.
    """
    return cls(
        user_id=request.user,
        project_id=request.project,
        name=request.name,
        description=request.description,
        source_deployment_id=request.source_deployment_id,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> RunTemplateResponse

Convert the schema to a response model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
RunTemplateResponse

Model representing this schema.

Source code in src/zenml/zen_stores/schemas/run_template_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> RunTemplateResponse:
    """Convert the schema to a response model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

    Returns:
        Model representing this schema.
    """
    runnable = False
    if (
        self.source_deployment
        and self.source_deployment.build
        and not self.source_deployment.build.is_local
        and self.source_deployment.build.stack
    ):
        runnable = True

    latest_run = self.latest_run

    body = RunTemplateResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        runnable=runnable,
        latest_run_id=latest_run.id if latest_run else None,
        latest_run_status=latest_run.status if latest_run else None,
    )

    metadata = None
    if include_metadata:
        pipeline_spec = None
        config_template = None
        config_schema = None

        if self.source_deployment:
            from zenml.zen_stores import template_utils

            pipeline_spec = self.source_deployment.to_model(
                include_metadata=True, include_resources=True
            ).pipeline_spec

            if (
                self.source_deployment.build
                and self.source_deployment.build.stack
            ):
                config_template = template_utils.generate_config_template(
                    deployment=self.source_deployment
                )
                config_schema = template_utils.generate_config_schema(
                    deployment=self.source_deployment
                )

        metadata = RunTemplateResponseMetadata(
            project=self.project.to_model(),
            description=self.description,
            pipeline_spec=pipeline_spec,
            config_template=config_template,
            config_schema=config_schema,
        )

    resources = None
    if include_resources:
        if self.source_deployment:
            pipeline = (
                self.source_deployment.pipeline.to_model()
                if self.source_deployment.pipeline
                else None
            )
            build = (
                self.source_deployment.build.to_model()
                if self.source_deployment.build
                else None
            )
            code_reference = (
                self.source_deployment.code_reference.to_model()
                if self.source_deployment.code_reference
                else None
            )
        else:
            pipeline = None
            build = None
            code_reference = None

        resources = RunTemplateResponseResources(
            source_deployment=self.source_deployment.to_model()
            if self.source_deployment
            else None,
            pipeline=pipeline,
            build=build,
            code_reference=code_reference,
            tags=[tag.to_model() for tag in self.tags],
        )

    return RunTemplateResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(update: RunTemplateUpdate) -> RunTemplateSchema

Update the schema.

Parameters:

Name Type Description Default
update RunTemplateUpdate

The update model.

required

Returns:

Type Description
RunTemplateSchema

The updated schema.

Source code in src/zenml/zen_stores/schemas/run_template_schemas.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def update(self, update: RunTemplateUpdate) -> "RunTemplateSchema":
    """Update the schema.

    Args:
        update: The update model.

    Returns:
        The updated schema.
    """
    for field, value in update.model_dump(
        exclude_unset=True, exclude_none=True
    ).items():
        if field in ["add_tags", "remove_tags"]:
            # Tags are handled separately
            continue
        setattr(self, field, value)

    self.updated = utc_now()
    return self
Functions
schedule_schema

SQL Model Implementations for Pipeline Schedules.

Classes
ScheduleSchema

Bases: NamedSchema, RunMetadataInterface

SQL Model for schedules.

Functions
from_request(schedule_request: ScheduleRequest) -> ScheduleSchema classmethod

Create a ScheduleSchema from a ScheduleRequest.

Parameters:

Name Type Description Default
schedule_request ScheduleRequest

The ScheduleRequest to create the schema from.

required

Returns:

Type Description
ScheduleSchema

The created ScheduleSchema.

Source code in src/zenml/zen_stores/schemas/schedule_schema.py
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
@classmethod
def from_request(
    cls, schedule_request: ScheduleRequest
) -> "ScheduleSchema":
    """Create a `ScheduleSchema` from a `ScheduleRequest`.

    Args:
        schedule_request: The `ScheduleRequest` to create the schema from.

    Returns:
        The created `ScheduleSchema`.
    """
    if schedule_request.interval_second is not None:
        interval_second = schedule_request.interval_second.total_seconds()
    else:
        interval_second = None
    return cls(
        name=schedule_request.name,
        project_id=schedule_request.project,
        user_id=schedule_request.user,
        pipeline_id=schedule_request.pipeline_id,
        orchestrator_id=schedule_request.orchestrator_id,
        active=schedule_request.active,
        cron_expression=schedule_request.cron_expression,
        start_time=schedule_request.start_time,
        end_time=schedule_request.end_time,
        interval_second=interval_second,
        catchup=schedule_request.catchup,
        run_once_start_time=schedule_request.run_once_start_time,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ScheduleResponse

Convert a ScheduleSchema to a ScheduleResponseModel.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ScheduleResponse

The created ScheduleResponseModel.

Source code in src/zenml/zen_stores/schemas/schedule_schema.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ScheduleResponse:
    """Convert a `ScheduleSchema` to a `ScheduleResponseModel`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `ScheduleResponseModel`.
    """
    if self.interval_second is not None:
        interval_second = timedelta(seconds=self.interval_second)
    else:
        interval_second = None

    body = ScheduleResponseBody(
        user=self.user.to_model() if self.user else None,
        active=self.active,
        cron_expression=self.cron_expression,
        start_time=self.start_time,
        end_time=self.end_time,
        interval_second=interval_second,
        catchup=self.catchup,
        updated=self.updated,
        created=self.created,
        run_once_start_time=self.run_once_start_time,
    )
    metadata = None
    if include_metadata:
        metadata = ScheduleResponseMetadata(
            project=self.project.to_model(),
            pipeline_id=self.pipeline_id,
            orchestrator_id=self.orchestrator_id,
            run_metadata=self.fetch_metadata(),
        )

    return ScheduleResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(schedule_update: ScheduleUpdate) -> ScheduleSchema

Update a ScheduleSchema from a ScheduleUpdateModel.

Parameters:

Name Type Description Default
schedule_update ScheduleUpdate

The ScheduleUpdateModel to update the schema from.

required

Returns:

Type Description
ScheduleSchema

The updated ScheduleSchema.

Source code in src/zenml/zen_stores/schemas/schedule_schema.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def update(self, schedule_update: ScheduleUpdate) -> "ScheduleSchema":
    """Update a `ScheduleSchema` from a `ScheduleUpdateModel`.

    Args:
        schedule_update: The `ScheduleUpdateModel` to update the schema from.

    Returns:
        The updated `ScheduleSchema`.
    """
    if schedule_update.name is not None:
        self.name = schedule_update.name

    self.updated = utc_now()
    return self
Functions
schema_utils

Utility functions for SQLModel schemas.

Functions
build_foreign_key_field(source: str, target: str, source_column: str, target_column: str, ondelete: str, nullable: bool, **sa_column_kwargs: Any) -> Any

Build a SQLModel foreign key field.

Parameters:

Name Type Description Default
source str

Source table name.

required
target str

Target table name.

required
source_column str

Source column name.

required
target_column str

Target column name.

required
ondelete str

On delete behavior.

required
nullable bool

Whether the field is nullable.

required
**sa_column_kwargs Any

Keyword arguments for the SQLAlchemy column.

{}

Returns:

Type Description
Any

SQLModel foreign key field.

Raises:

Type Description
ValueError

If the ondelete and nullable arguments are not compatible.

Source code in src/zenml/zen_stores/schemas/schema_utils.py
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
def build_foreign_key_field(
    source: str,
    target: str,
    source_column: str,
    target_column: str,
    ondelete: str,
    nullable: bool,
    **sa_column_kwargs: Any,
) -> Any:
    """Build a SQLModel foreign key field.

    Args:
        source: Source table name.
        target: Target table name.
        source_column: Source column name.
        target_column: Target column name.
        ondelete: On delete behavior.
        nullable: Whether the field is nullable.
        **sa_column_kwargs: Keyword arguments for the SQLAlchemy column.

    Returns:
        SQLModel foreign key field.

    Raises:
        ValueError: If the ondelete and nullable arguments are not compatible.
    """
    if not nullable and ondelete == "SET NULL":
        raise ValueError(
            "Cannot set ondelete to SET NULL if the field is not nullable."
        )
    constraint_name = foreign_key_constraint_name(
        source=source,
        target=target,
        source_column=source_column,
    )
    return Field(
        sa_column=Column(
            ForeignKey(
                f"{target}.{target_column}",
                name=constraint_name,
                ondelete=ondelete,
            ),
            nullable=nullable,
            **sa_column_kwargs,
        ),
    )
build_index(table_name: str, column_names: List[str], **kwargs: Any) -> Index

Build an index object.

Parameters:

Name Type Description Default
table_name str

The name of the table for which the index will be created.

required
column_names List[str]

Names of the columns on which the index will be created.

required
**kwargs Any

Additional keyword arguments to pass to the Index.

{}

Returns:

Type Description
Index

The index.

Source code in src/zenml/zen_stores/schemas/schema_utils.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def build_index(
    table_name: str, column_names: List[str], **kwargs: Any
) -> Index:
    """Build an index object.

    Args:
        table_name: The name of the table for which the index will be created.
        column_names: Names of the columns on which the index will be created.
        **kwargs: Additional keyword arguments to pass to the Index.

    Returns:
        The index.
    """
    name = get_index_name(table_name=table_name, column_names=column_names)
    return Index(name, *column_names, **kwargs)
foreign_key_constraint_name(source: str, target: str, source_column: str) -> str

Defines the name of a foreign key constraint.

For simplicity, we use the naming convention used by alembic here: https://alembic.sqlalchemy.org/en/latest/batch.html#dropping-unnamed-or-named-foreign-key-constraints.

Parameters:

Name Type Description Default
source str

Source table name.

required
target str

Target table name.

required
source_column str

Source column name.

required

Returns:

Type Description
str

Name of the foreign key constraint.

Source code in src/zenml/zen_stores/schemas/schema_utils.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def foreign_key_constraint_name(
    source: str, target: str, source_column: str
) -> str:
    """Defines the name of a foreign key constraint.

    For simplicity, we use the naming convention used by alembic here:
    https://alembic.sqlalchemy.org/en/latest/batch.html#dropping-unnamed-or-named-foreign-key-constraints.

    Args:
        source: Source table name.
        target: Target table name.
        source_column: Source column name.

    Returns:
        Name of the foreign key constraint.
    """
    return f"fk_{source}_{source_column}_{target}"
get_index_name(table_name: str, column_names: List[str]) -> str

Get the name for an index.

Parameters:

Name Type Description Default
table_name str

The name of the table for which the index will be created.

required
column_names List[str]

Names of the columns on which the index will be created.

required

Returns:

Type Description
str

The index name.

Source code in src/zenml/zen_stores/schemas/schema_utils.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def get_index_name(table_name: str, column_names: List[str]) -> str:
    """Get the name for an index.

    Args:
        table_name: The name of the table for which the index will be created.
        column_names: Names of the columns on which the index will be created.

    Returns:
        The index name.
    """
    columns = "_".join(column_names)
    # MySQL allows a maximum of 64 characters in identifiers
    return f"ix_{table_name}_{columns}"[:64]
secret_schemas

SQL Model Implementations for Secrets.

Classes
SecretDecodeError

Bases: Exception

Raised when a secret cannot be decoded or decrypted.

SecretSchema

Bases: NamedSchema

SQL Model for secrets.

Attributes:

Name Type Description
name str

The name of the secret.

values Optional[bytes]

The values of the secret.

Functions
from_request(secret: SecretRequest) -> SecretSchema classmethod

Create a SecretSchema from a SecretRequest.

Parameters:

Name Type Description Default
secret SecretRequest

The SecretRequest from which to create the schema.

required

Returns:

Type Description
SecretSchema

The created SecretSchema.

Source code in src/zenml/zen_stores/schemas/secret_schemas.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
@classmethod
def from_request(
    cls,
    secret: SecretRequest,
) -> "SecretSchema":
    """Create a `SecretSchema` from a `SecretRequest`.

    Args:
        secret: The `SecretRequest` from which to create the schema.

    Returns:
        The created `SecretSchema`.
    """
    assert secret.user is not None, "User must be set for secret creation."
    return cls(
        name=secret.name,
        private=secret.private,
        user_id=secret.user,
        # Don't store secret values implicitly in the secret. The
        # SQL secret store will call `store_secret_values` to store the
        # values separately if SQL is used as the secrets store.
        values=None,
    )
get_secret_values(encryption_engine: Optional[AesGcmEngine] = None) -> Dict[str, str]

Get the secret values for this secret.

This method is used by the SQL secrets store to load the secret values from the database.

Parameters:

Name Type Description Default
encryption_engine Optional[AesGcmEngine]

The encryption engine to use to decrypt the secret values. If None, the values will be base64 decoded.

None

Returns:

Type Description
Dict[str, str]

The secret values

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

Source code in src/zenml/zen_stores/schemas/secret_schemas.py
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
def get_secret_values(
    self,
    encryption_engine: Optional[AesGcmEngine] = None,
) -> Dict[str, str]:
    """Get the secret values for this secret.

    This method is used by the SQL secrets store to load the secret values
    from the database.

    Args:
        encryption_engine: The encryption engine to use to decrypt the
            secret values. If None, the values will be base64 decoded.

    Returns:
        The secret values

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
    """
    if not self.values:
        raise KeyError(
            f"Secret values for secret {self.id} have not been stored in "
            f"the SQL secrets store."
        )
    return self._load_secret_values(self.values, encryption_engine)
set_secret_values(secret_values: Dict[str, str], encryption_engine: Optional[AesGcmEngine] = None) -> None

Create a SecretSchema from a SecretRequest.

This method is used by the SQL secrets store to store the secret values in the database.

Parameters:

Name Type Description Default
secret_values Dict[str, str]

The new secret values.

required
encryption_engine Optional[AesGcmEngine]

The encryption engine to use to encrypt the secret values. If None, the values will be base64 encoded.

None
Source code in src/zenml/zen_stores/schemas/secret_schemas.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def set_secret_values(
    self,
    secret_values: Dict[str, str],
    encryption_engine: Optional[AesGcmEngine] = None,
) -> None:
    """Create a `SecretSchema` from a `SecretRequest`.

    This method is used by the SQL secrets store to store the secret values
    in the database.

    Args:
        secret_values: The new secret values.
        encryption_engine: The encryption engine to use to encrypt the
            secret values. If None, the values will be base64 encoded.
    """
    self.values = self._dump_secret_values(
        secret_values, encryption_engine
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> SecretResponse

Converts a secret schema to a secret model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
SecretResponse

The secret model.

Source code in src/zenml/zen_stores/schemas/secret_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> SecretResponse:
    """Converts a secret schema to a secret model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The secret model.
    """
    metadata = None
    if include_metadata:
        metadata = SecretResponseMetadata()

    # Don't load the secret values implicitly in the secret. The
    # SQL secret store will call `get_secret_values` to load the
    # values separately if SQL is used as the secrets store.
    body = SecretResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        private=self.private,
    )
    return SecretResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(secret_update: SecretUpdate) -> SecretSchema

Update a SecretSchema from a SecretUpdate.

Parameters:

Name Type Description Default
secret_update SecretUpdate

The SecretUpdate from which to update the schema.

required

Returns:

Type Description
SecretSchema

The updated SecretSchema.

Source code in src/zenml/zen_stores/schemas/secret_schemas.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def update(
    self,
    secret_update: SecretUpdate,
) -> "SecretSchema":
    """Update a `SecretSchema` from a `SecretUpdate`.

    Args:
        secret_update: The `SecretUpdate` from which to update the schema.

    Returns:
        The updated `SecretSchema`.
    """
    # Don't update the secret values implicitly in the secret. The
    # SQL secret store will call `set_secret_values` to update the
    # values separately if SQL is used as the secrets store.
    for field, value in secret_update.model_dump(
        exclude_unset=True, exclude={"user", "values"}
    ).items():
        setattr(self, field, value)

    self.updated = utc_now()
    return self
Functions
server_settings_schemas

SQLModel implementation for the server settings table.

Classes
ServerSettingsSchema

Bases: SQLModel

SQL Model for the server settings.

Functions
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ServerSettingsResponse

Convert an ServerSettingsSchema to an ServerSettingsResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ServerSettingsResponse

The created SettingsResponse.

Source code in src/zenml/zen_stores/schemas/server_settings_schemas.py
 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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ServerSettingsResponse:
    """Convert an `ServerSettingsSchema` to an `ServerSettingsResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

    Returns:
        The created `SettingsResponse`.
    """
    body = ServerSettingsResponseBody(
        server_id=self.id,
        server_name=self.server_name,
        logo_url=self.logo_url,
        enable_analytics=self.enable_analytics,
        display_announcements=self.display_announcements,
        display_updates=self.display_updates,
        active=self.active,
        updated=self.updated,
        last_user_activity=self.last_user_activity,
    )

    metadata = None
    resources = None

    if include_metadata:
        metadata = ServerSettingsResponseMetadata()

    if include_resources:
        resources = ServerSettingsResponseResources()

    return ServerSettingsResponse(
        body=body, metadata=metadata, resources=resources
    )
update(settings_update: ServerSettingsUpdate) -> ServerSettingsSchema

Update a ServerSettingsSchema from a ServerSettingsUpdate.

Parameters:

Name Type Description Default
settings_update ServerSettingsUpdate

The ServerSettingsUpdate from which to update the schema.

required

Returns:

Type Description
ServerSettingsSchema

The updated ServerSettingsSchema.

Source code in src/zenml/zen_stores/schemas/server_settings_schemas.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def update(
    self, settings_update: ServerSettingsUpdate
) -> "ServerSettingsSchema":
    """Update a `ServerSettingsSchema` from a `ServerSettingsUpdate`.

    Args:
        settings_update: The `ServerSettingsUpdate` from which
            to update the schema.

    Returns:
        The updated `ServerSettingsSchema`.
    """
    for field, value in settings_update.model_dump(
        exclude_unset=True
    ).items():
        if hasattr(self, field):
            setattr(self, field, value)

    self.updated = utc_now()

    return self
update_onboarding_state(completed_steps: Set[str]) -> ServerSettingsSchema

Update the onboarding state.

Parameters:

Name Type Description Default
completed_steps Set[str]

Newly completed onboarding steps.

required

Returns:

Type Description
ServerSettingsSchema

The updated schema.

Source code in src/zenml/zen_stores/schemas/server_settings_schemas.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def update_onboarding_state(
    self, completed_steps: Set[str]
) -> "ServerSettingsSchema":
    """Update the onboarding state.

    Args:
        completed_steps: Newly completed onboarding steps.

    Returns:
        The updated schema.
    """
    old_state = set(
        json.loads(self.onboarding_state) if self.onboarding_state else []
    )
    new_state = old_state.union(completed_steps)
    self.onboarding_state = json.dumps(list(new_state))
    self.updated = utc_now()

    return self
Functions
service_connector_schemas

SQL Model Implementations for Service Connectors.

Classes
ServiceConnectorSchema

Bases: NamedSchema

SQL Model for service connectors.

Attributes
labels_dict: Dict[str, str] property

Returns the labels as a dictionary.

Returns:

Type Description
Dict[str, str]

The labels as a dictionary.

resource_types_list: List[str] property

Returns the resource types as a list.

Returns:

Type Description
List[str]

The resource types as a list.

Functions
from_request(connector_request: ServiceConnectorRequest, secret_id: Optional[UUID] = None) -> ServiceConnectorSchema classmethod

Create a ServiceConnectorSchema from a ServiceConnectorRequest.

Parameters:

Name Type Description Default
connector_request ServiceConnectorRequest

The ServiceConnectorRequest from which to create the schema.

required
secret_id Optional[UUID]

The ID of the secret to use for this connector.

None

Returns:

Type Description
ServiceConnectorSchema

The created ServiceConnectorSchema.

Source code in src/zenml/zen_stores/schemas/service_connector_schemas.py
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
@classmethod
def from_request(
    cls,
    connector_request: ServiceConnectorRequest,
    secret_id: Optional[UUID] = None,
) -> "ServiceConnectorSchema":
    """Create a `ServiceConnectorSchema` from a `ServiceConnectorRequest`.

    Args:
        connector_request: The `ServiceConnectorRequest` from which to
            create the schema.
        secret_id: The ID of the secret to use for this connector.

    Returns:
        The created `ServiceConnectorSchema`.
    """
    assert connector_request.user is not None, "User must be set."
    return cls(
        user_id=connector_request.user,
        name=connector_request.name,
        description=connector_request.description,
        connector_type=connector_request.type,
        auth_method=connector_request.auth_method,
        resource_types=base64.b64encode(
            json.dumps(connector_request.resource_types).encode("utf-8")
        ),
        resource_id=connector_request.resource_id,
        supports_instances=connector_request.supports_instances,
        configuration=base64.b64encode(
            json.dumps(connector_request.configuration).encode("utf-8")
        )
        if connector_request.configuration
        else None,
        secret_id=secret_id,
        expires_at=connector_request.expires_at,
        expires_skew_tolerance=connector_request.expires_skew_tolerance,
        expiration_seconds=connector_request.expiration_seconds,
        labels=base64.b64encode(
            json.dumps(connector_request.labels).encode("utf-8")
        )
        if connector_request.labels
        else None,
    )
has_labels(labels: Dict[str, Optional[str]]) -> bool

Checks if the connector has the given labels.

Parameters:

Name Type Description Default
labels Dict[str, Optional[str]]

The labels to check for.

required

Returns:

Type Description
bool

Whether the connector has the given labels.

Source code in src/zenml/zen_stores/schemas/service_connector_schemas.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def has_labels(self, labels: Dict[str, Optional[str]]) -> bool:
    """Checks if the connector has the given labels.

    Args:
        labels: The labels to check for.

    Returns:
        Whether the connector has the given labels.
    """
    return all(
        self.labels_dict.get(key, None) == value
        for key, value in labels.items()
        if value is not None
    ) and all(
        key in self.labels_dict
        for key, value in labels.items()
        if value is None
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ServiceConnectorResponse

Creates a ServiceConnector from a ServiceConnectorSchema.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
ServiceConnectorResponse

A ServiceConnectorModel

Source code in src/zenml/zen_stores/schemas/service_connector_schemas.py
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 to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "ServiceConnectorResponse":
    """Creates a `ServiceConnector` from a `ServiceConnectorSchema`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        A `ServiceConnectorModel`
    """
    body = ServiceConnectorResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        description=self.description,
        connector_type=self.connector_type,
        auth_method=self.auth_method,
        resource_types=self.resource_types_list,
        resource_id=self.resource_id,
        supports_instances=self.supports_instances,
        expires_at=self.expires_at,
        expires_skew_tolerance=self.expires_skew_tolerance,
    )
    metadata = None
    if include_metadata:
        metadata = ServiceConnectorResponseMetadata(
            configuration=json.loads(
                base64.b64decode(self.configuration).decode()
            )
            if self.configuration
            else {},
            secret_id=self.secret_id,
            expiration_seconds=self.expiration_seconds,
            labels=self.labels_dict,
        )
    return ServiceConnectorResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(connector_update: ServiceConnectorUpdate, secret_id: Optional[UUID] = None) -> ServiceConnectorSchema

Updates a ServiceConnectorSchema from a ServiceConnectorUpdate.

Parameters:

Name Type Description Default
connector_update ServiceConnectorUpdate

The ServiceConnectorUpdate to update from.

required
secret_id Optional[UUID]

The ID of the secret to use for this connector.

None

Returns:

Type Description
ServiceConnectorSchema

The updated ServiceConnectorSchema.

Source code in src/zenml/zen_stores/schemas/service_connector_schemas.py
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
def update(
    self,
    connector_update: ServiceConnectorUpdate,
    secret_id: Optional[UUID] = None,
) -> "ServiceConnectorSchema":
    """Updates a `ServiceConnectorSchema` from a `ServiceConnectorUpdate`.

    Args:
        connector_update: The `ServiceConnectorUpdate` to update from.
        secret_id: The ID of the secret to use for this connector.

    Returns:
        The updated `ServiceConnectorSchema`.
    """
    for field, value in connector_update.model_dump(
        exclude_unset=False,
        exclude={"user", "secrets"},
    ).items():
        if value is None:
            if field == "resource_id":
                # The resource ID field in the update is special: if set
                # to None in the update, it triggers the existing resource
                # ID to be cleared.
                self.resource_id = None
            if field == "expiration_seconds":
                # The expiration_seconds field in the update is special:
                # if set to None in the update, it triggers the existing
                # expiration_seconds to be cleared.
                self.expiration_seconds = None
            continue
        if field == "configuration":
            self.configuration = (
                base64.b64encode(
                    json.dumps(connector_update.configuration).encode(
                        "utf-8"
                    )
                )
                if connector_update.configuration
                else None
            )
        elif field == "resource_types":
            self.resource_types = base64.b64encode(
                json.dumps(connector_update.resource_types).encode("utf-8")
            )
        elif field == "labels":
            self.labels = (
                base64.b64encode(
                    json.dumps(connector_update.labels).encode("utf-8")
                )
                if connector_update.labels
                else None
            )
        else:
            setattr(self, field, value)
    self.secret_id = secret_id
    self.updated = utc_now()
    return self
Functions
service_schemas

SQLModel implementation of service table.

Classes
ServiceSchema

Bases: NamedSchema

SQL Model for service.

Functions
from_request(service_request: ServiceRequest) -> ServiceSchema classmethod

Convert a ServiceRequest to a ServiceSchema.

Parameters:

Name Type Description Default
service_request ServiceRequest

The request model to convert.

required

Returns:

Type Description
ServiceSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/service_schemas.py
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
@classmethod
def from_request(
    cls, service_request: "ServiceRequest"
) -> "ServiceSchema":
    """Convert a `ServiceRequest` to a `ServiceSchema`.

    Args:
        service_request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=service_request.name,
        project_id=service_request.project,
        user_id=service_request.user,
        service_source=service_request.service_source,
        service_type=service_request.service_type.model_dump_json(),
        type=service_request.service_type.type,
        flavor=service_request.service_type.flavor,
        admin_state=service_request.admin_state,
        config=dict_to_bytes(service_request.config),
        labels=dict_to_bytes(service_request.labels)
        if service_request.labels
        else None,
        status=dict_to_bytes(service_request.status)
        if service_request.status
        else None,
        endpoint=dict_to_bytes(service_request.endpoint)
        if service_request.endpoint
        else None,
        state=service_request.status.get("state")
        if service_request.status
        else None,
        model_version_id=service_request.model_version_id,
        pipeline_run_id=service_request.pipeline_run_id,
        prediction_url=service_request.prediction_url,
        health_check_url=service_request.health_check_url,
        pipeline_name=service_request.config.get("pipeline_name"),
        pipeline_step_name=service_request.config.get(
            "pipeline_step_name"
        ),
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> ServiceResponse

Convert an ServiceSchema to an ServiceResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether to include metadata in the response.

False
include_resources bool

Whether to include resources in the response.

False
kwargs Any

Additional keyword arguments.

{}

Returns:

Type Description
ServiceResponse

The created ServiceResponse.

Source code in src/zenml/zen_stores/schemas/service_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> ServiceResponse:
    """Convert an `ServiceSchema` to an `ServiceResponse`.

    Args:
        include_metadata: Whether to include metadata in the response.
        include_resources: Whether to include resources in the response.
        kwargs: Additional keyword arguments.

    Returns:
        The created `ServiceResponse`.
    """
    body = ServiceResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        service_type=json.loads(self.service_type),
        labels=json.loads(base64.b64decode(self.labels).decode())
        if self.labels
        else None,
        state=self.state,
    )
    metadata = None
    if include_metadata:
        metadata = ServiceResponseMetadata(
            project=self.project.to_model(),
            service_source=self.service_source,
            config=json.loads(base64.b64decode(self.config).decode()),
            status=json.loads(base64.b64decode(self.status).decode())
            if self.status
            else None,
            endpoint=json.loads(base64.b64decode(self.endpoint).decode())
            if self.endpoint
            else None,
            admin_state=self.admin_state or None,
            prediction_url=self.prediction_url or None,
            health_check_url=self.health_check_url,
        )
    resources = None
    if include_resources:
        resources = ServiceResponseResources(
            model_version=self.model_version.to_model()
            if self.model_version
            else None,
            pipeline_run=self.pipeline_run.to_model()
            if self.pipeline_run
            else None,
        )
    return ServiceResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(update: ServiceUpdate) -> ServiceSchema

Updates a ServiceSchema from a ServiceUpdate.

Parameters:

Name Type Description Default
update ServiceUpdate

The ServiceUpdate to update from.

required

Returns:

Type Description
ServiceSchema

The updated ServiceSchema.

Source code in src/zenml/zen_stores/schemas/service_schemas.py
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
def update(
    self,
    update: ServiceUpdate,
) -> "ServiceSchema":
    """Updates a `ServiceSchema` from a `ServiceUpdate`.

    Args:
        update: The `ServiceUpdate` to update from.

    Returns:
        The updated `ServiceSchema`.
    """
    for field, value in update.model_dump(
        exclude_unset=True, exclude_none=True
    ).items():
        if field == "labels":
            self.labels = (
                dict_to_bytes(update.labels) if update.labels else None
            )
        elif field == "status":
            self.status = (
                dict_to_bytes(update.status) if update.status else None
            )
            self.state = (
                update.status.get("state") if update.status else None
            )
        elif field == "endpoint":
            self.endpoint = (
                dict_to_bytes(update.endpoint) if update.endpoint else None
            )
        else:
            setattr(self, field, value)
    self.updated = utc_now()
    return self
Functions
stack_schemas

SQL Model Implementations for Stacks.

Classes
StackCompositionSchema

Bases: SQLModel

SQL Model for stack definitions.

Join table between Stacks and StackComponents.

StackSchema

Bases: NamedSchema

SQL Model for stacks.

Functions
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> StackResponse

Converts the schema to a model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
StackResponse

The converted model.

Source code in src/zenml/zen_stores/schemas/stack_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "StackResponse":
    """Converts the schema to a model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic

    Returns:
        The converted model.
    """
    body = StackResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        metadata = StackResponseMetadata(
            components={c.type: [c.to_model()] for c in self.components},
            stack_spec_path=self.stack_spec_path,
            labels=json.loads(base64.b64decode(self.labels).decode())
            if self.labels
            else None,
            description=self.description,
        )

    return StackResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update(stack_update: StackUpdate, components: List[StackComponentSchema]) -> StackSchema

Updates a stack schema with a stack update model.

Parameters:

Name Type Description Default
stack_update StackUpdate

StackUpdate to update the stack with.

required
components List[StackComponentSchema]

List of StackComponentSchema to update the stack with.

required

Returns:

Type Description
StackSchema

The updated StackSchema.

Source code in src/zenml/zen_stores/schemas/stack_schemas.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
def update(
    self,
    stack_update: "StackUpdate",
    components: List["StackComponentSchema"],
) -> "StackSchema":
    """Updates a stack schema with a stack update model.

    Args:
        stack_update: `StackUpdate` to update the stack with.
        components: List of `StackComponentSchema` to update the stack with.

    Returns:
        The updated StackSchema.
    """
    for field, value in stack_update.model_dump(
        exclude_unset=True, exclude={"user"}
    ).items():
        if field == "components":
            self.components = components
        elif field == "labels":
            self.labels = base64.b64encode(
                json.dumps(stack_update.labels).encode("utf-8")
            )
        else:
            setattr(self, field, value)

    self.updated = utc_now()
    return self
Functions
step_run_schemas

SQLModel implementation of step run tables.

Classes
StepRunInputArtifactSchema

Bases: SQLModel

SQL Model that defines which artifacts are inputs to which step.

StepRunOutputArtifactSchema

Bases: SQLModel

SQL Model that defines which artifacts are outputs of which step.

StepRunParentsSchema

Bases: SQLModel

SQL Model that defines the order of steps.

StepRunSchema

Bases: NamedSchema, RunMetadataInterface

SQL Model for steps of pipeline runs.

Functions
from_request(request: StepRunRequest, deployment_id: Optional[UUID]) -> StepRunSchema classmethod

Create a step run schema from a step run request model.

Parameters:

Name Type Description Default
request StepRunRequest

The step run request model.

required
deployment_id Optional[UUID]

The deployment ID.

required

Returns:

Type Description
StepRunSchema

The step run schema.

Source code in src/zenml/zen_stores/schemas/step_run_schemas.py
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
@classmethod
def from_request(
    cls, request: StepRunRequest, deployment_id: Optional[UUID]
) -> "StepRunSchema":
    """Create a step run schema from a step run request model.

    Args:
        request: The step run request model.
        deployment_id: The deployment ID.

    Returns:
        The step run schema.
    """
    return cls(
        name=request.name,
        project_id=request.project,
        user_id=request.user,
        start_time=request.start_time,
        end_time=request.end_time,
        status=request.status.value,
        deployment_id=deployment_id,
        original_step_run_id=request.original_step_run_id,
        pipeline_run_id=request.pipeline_run_id,
        docstring=request.docstring,
        cache_key=request.cache_key,
        code_hash=request.code_hash,
        source_code=request.source_code,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> StepRunResponse

Convert a StepRunSchema to a StepRunResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
StepRunResponse

The created StepRunResponse.

Raises:

Type Description
ValueError

In case the step run configuration can not be loaded.

RuntimeError

If the step run schema does not have a deployment_id or a step_configuration.

Source code in src/zenml/zen_stores/schemas/step_run_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> StepRunResponse:
    """Convert a `StepRunSchema` to a `StepRunResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created StepRunResponse.

    Raises:
        ValueError: In case the step run configuration can not be loaded.
        RuntimeError: If the step run schema does not have a deployment_id
            or a step_configuration.
    """
    input_artifacts = {
        artifact.name: StepRunInputResponse(
            input_type=StepRunInputArtifactType(artifact.type),
            **artifact.artifact_version.to_model().model_dump(),
        )
        for artifact in self.input_artifacts
    }

    output_artifacts: Dict[str, List["ArtifactVersionResponse"]] = {}
    for artifact in self.output_artifacts:
        if artifact.name not in output_artifacts:
            output_artifacts[artifact.name] = []
        output_artifacts[artifact.name].append(
            artifact.artifact_version.to_model()
        )

    full_step_config = None
    if self.deployment is not None:
        step_configuration = json.loads(
            self.deployment.step_configurations
        )
        if self.name in step_configuration:
            full_step_config = Step.model_validate(
                step_configuration[self.name]
            )
            new_substitutions = (
                full_step_config.config._get_full_substitutions(
                    PipelineConfiguration.model_validate_json(
                        self.deployment.pipeline_configuration
                    ),
                    self.pipeline_run.start_time,
                )
            )
            full_step_config = full_step_config.model_copy(
                update={
                    "config": full_step_config.config.model_copy(
                        update={"substitutions": new_substitutions}
                    )
                }
            )
        elif not self.step_configuration:
            raise ValueError(
                f"Unable to load the configuration for step `{self.name}` from the"
                f"database. To solve this please delete the pipeline run that this"
                f"step run belongs to. Pipeline Run ID: `{self.pipeline_run_id}`."
            )

    # the step configuration moved into the deployment - the following case is to ensure
    # backwards compatibility
    if full_step_config is None:
        if self.step_configuration:
            full_step_config = Step.model_validate_json(
                self.step_configuration
            )
        else:
            raise RuntimeError(
                "Step run model creation has failed. Each step run entry "
                "should either have a deployment_id or step_configuration."
            )

    body = StepRunResponseBody(
        user=self.user.to_model() if self.user else None,
        status=ExecutionStatus(self.status),
        start_time=self.start_time,
        end_time=self.end_time,
        inputs=input_artifacts,
        outputs=output_artifacts,
        created=self.created,
        updated=self.updated,
        model_version_id=self.model_version_id,
    )
    metadata = None
    if include_metadata:
        metadata = StepRunResponseMetadata(
            project=self.project.to_model(),
            config=full_step_config.config,
            spec=full_step_config.spec,
            cache_key=self.cache_key,
            code_hash=self.code_hash,
            docstring=self.docstring,
            source_code=self.source_code,
            logs=self.logs.to_model() if self.logs else None,
            deployment_id=self.deployment_id,
            pipeline_run_id=self.pipeline_run_id,
            original_step_run_id=self.original_step_run_id,
            parent_step_ids=[p.parent_id for p in self.parents],
            run_metadata=self.fetch_metadata(),
        )

    resources = None
    if include_resources:
        model_version = None
        if self.model_version:
            model_version = self.model_version.to_model()

        resources = StepRunResponseResources(model_version=model_version)

    return StepRunResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(step_update: StepRunUpdate) -> StepRunSchema

Update a step run schema with a step run update model.

Parameters:

Name Type Description Default
step_update StepRunUpdate

The step run update model.

required

Returns:

Type Description
StepRunSchema

The updated step run schema.

Source code in src/zenml/zen_stores/schemas/step_run_schemas.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def update(self, step_update: "StepRunUpdate") -> "StepRunSchema":
    """Update a step run schema with a step run update model.

    Args:
        step_update: The step run update model.

    Returns:
        The updated step run schema.
    """
    for key, value in step_update.model_dump(
        exclude_unset=True, exclude_none=True
    ).items():
        if key == "status":
            self.status = value.value
        if key == "end_time":
            self.end_time = value

    self.updated = utc_now()

    return self
Functions
tag_schemas

SQLModel implementation of tag tables.

Classes
TagResourceSchema

Bases: BaseSchema

SQL Model for tag resource relationship.

Functions
from_request(request: TagResourceRequest) -> TagResourceSchema classmethod

Convert an TagResourceRequest to an TagResourceSchema.

Parameters:

Name Type Description Default
request TagResourceRequest

The request model version to convert.

required

Returns:

Type Description
TagResourceSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/tag_schemas.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
@classmethod
def from_request(cls, request: TagResourceRequest) -> "TagResourceSchema":
    """Convert an `TagResourceRequest` to an `TagResourceSchema`.

    Args:
        request: The request model version to convert.

    Returns:
        The converted schema.
    """
    return cls(
        tag_id=request.tag_id,
        resource_id=request.resource_id,
        resource_type=request.resource_type.value,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> TagResourceResponse

Convert an TagResourceSchema to an TagResourceResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
TagResourceResponse

The created TagResourceResponse.

Source code in src/zenml/zen_stores/schemas/tag_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> TagResourceResponse:
    """Convert an `TagResourceSchema` to an `TagResourceResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `TagResourceResponse`.
    """
    return TagResourceResponse(
        id=self.id,
        body=TagResourceResponseBody(
            tag_id=self.tag_id,
            resource_id=self.resource_id,
            created=self.created,
            updated=self.updated,
            resource_type=TaggableResourceTypes(self.resource_type),
        ),
    )
TagSchema

Bases: NamedSchema

SQL Model for tag.

Functions
from_request(request: TagRequest) -> TagSchema classmethod

Convert an TagRequest to an TagSchema.

Parameters:

Name Type Description Default
request TagRequest

The request model to convert.

required

Returns:

Type Description
TagSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/tag_schemas.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
@classmethod
def from_request(cls, request: TagRequest) -> "TagSchema":
    """Convert an `TagRequest` to an `TagSchema`.

    Args:
        request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=request.name,
        exclusive=request.exclusive,
        color=request.color.value,
        user_id=request.user,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> TagResponse

Convert an TagSchema to an TagResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
TagResponse

The created TagResponse.

Source code in src/zenml/zen_stores/schemas/tag_schemas.py
 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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> TagResponse:
    """Convert an `TagSchema` to an `TagResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The created `TagResponse`.
    """
    metadata = None
    if include_metadata:
        metadata = TagResponseMetadata()
    return TagResponse(
        id=self.id,
        name=self.name,
        body=TagResponseBody(
            user=self.user.to_model() if self.user else None,
            created=self.created,
            updated=self.updated,
            color=ColorVariants(self.color),
            exclusive=self.exclusive,
            tagged_count=len(self.links),
        ),
        metadata=metadata,
    )
update(update: TagUpdate) -> TagSchema

Updates a TagSchema from a TagUpdate.

Parameters:

Name Type Description Default
update TagUpdate

The TagUpdate to update from.

required

Returns:

Type Description
TagSchema

The updated TagSchema.

Source code in src/zenml/zen_stores/schemas/tag_schemas.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def update(self, update: TagUpdate) -> "TagSchema":
    """Updates a `TagSchema` from a `TagUpdate`.

    Args:
        update: The `TagUpdate` to update from.

    Returns:
        The updated `TagSchema`.
    """
    for field, value in update.model_dump(exclude_unset=True).items():
        if field == "color":
            setattr(self, field, value.value)
        else:
            setattr(self, field, value)

    self.updated = utc_now()
    return self
Functions
trigger_schemas

SQL Model Implementations for Triggers.

Classes
TriggerExecutionSchema

Bases: BaseSchema

SQL Model for trigger executions.

Functions
from_request(request: TriggerExecutionRequest) -> TriggerExecutionSchema classmethod

Convert a TriggerExecutionRequest to a TriggerExecutionSchema.

Parameters:

Name Type Description Default
request TriggerExecutionRequest

The request model to convert.

required

Returns:

Type Description
TriggerExecutionSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/trigger_schemas.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
@classmethod
def from_request(
    cls, request: "TriggerExecutionRequest"
) -> "TriggerExecutionSchema":
    """Convert a `TriggerExecutionRequest` to a `TriggerExecutionSchema`.

    Args:
        request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        trigger_id=request.trigger,
        event_metadata=base64.b64encode(
            json.dumps(request.event_metadata).encode("utf-8")
        ),
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> TriggerExecutionResponse

Converts the schema to a model.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
TriggerExecutionResponse

The converted model.

Source code in src/zenml/zen_stores/schemas/trigger_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "TriggerExecutionResponse":
    """Converts the schema to a model.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic


    Returns:
        The converted model.
    """
    body = TriggerExecutionResponseBody(
        created=self.created,
        updated=self.updated,
    )
    metadata = None
    if include_metadata:
        metadata = TriggerExecutionResponseMetadata(
            event_metadata=json.loads(
                base64.b64decode(self.event_metadata).decode()
            )
            if self.event_metadata
            else {},
        )
    resources = None
    if include_resources:
        resources = TriggerExecutionResponseResources(
            trigger=self.trigger.to_model(),
        )

    return TriggerExecutionResponse(
        id=self.id, body=body, metadata=metadata, resources=resources
    )
TriggerSchema

Bases: NamedSchema

SQL Model for triggers.

Functions
from_request(request: TriggerRequest) -> TriggerSchema classmethod

Convert a TriggerRequest to a TriggerSchema.

Parameters:

Name Type Description Default
request TriggerRequest

The request model to convert.

required

Returns:

Type Description
TriggerSchema

The converted schema.

Source code in src/zenml/zen_stores/schemas/trigger_schemas.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
@classmethod
def from_request(cls, request: "TriggerRequest") -> "TriggerSchema":
    """Convert a `TriggerRequest` to a `TriggerSchema`.

    Args:
        request: The request model to convert.

    Returns:
        The converted schema.
    """
    return cls(
        name=request.name,
        project_id=request.project,
        user_id=request.user,
        action_id=request.action_id,
        event_source_id=request.event_source_id,
        event_filter=base64.b64encode(
            json.dumps(
                request.event_filter, default=pydantic_encoder
            ).encode("utf-8")
        ),
        schedule=base64.b64encode(request.schedule.json().encode("utf-8"))
        if request.schedule
        else None,
        description=request.description,
        is_active=True,  # Makes no sense for it to be created inactive
    )
to_model(include_metadata: bool = False, include_resources: bool = False, **kwargs: Any) -> TriggerResponse

Converts the schema to a model.

Parameters:

Name Type Description Default
include_metadata bool

Flag deciding whether to include the output model(s) metadata fields in the response.

False
include_resources bool

Flag deciding whether to include the output model(s) metadata fields in the response.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}

Returns:

Type Description
TriggerResponse

The converted model.

Source code in src/zenml/zen_stores/schemas/trigger_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    **kwargs: Any,
) -> "TriggerResponse":
    """Converts the schema to a model.

    Args:
        include_metadata: Flag deciding whether to include the output model(s)
            metadata fields in the response.
        include_resources: Flag deciding whether to include the output model(s)
            metadata fields in the response.
        **kwargs: Keyword arguments to allow schema specific logic

    Returns:
        The converted model.
    """
    from zenml.models import TriggerExecutionResponse

    body = TriggerResponseBody(
        user=self.user.to_model() if self.user else None,
        created=self.created,
        updated=self.updated,
        action_flavor=self.action.flavor,
        action_subtype=self.action.plugin_subtype,
        event_source_flavor=self.event_source.flavor
        if self.event_source
        else None,
        event_source_subtype=self.event_source.plugin_subtype
        if self.event_source
        else None,
        is_active=self.is_active,
    )
    metadata = None
    if include_metadata:
        metadata = TriggerResponseMetadata(
            project=self.project.to_model(),
            event_filter=json.loads(
                base64.b64decode(self.event_filter).decode()
            ),
            schedule=Schedule.parse_raw(
                base64.b64decode(self.schedule).decode()
            )
            if self.schedule
            else None,
            description=self.description,
        )
    resources = None
    if include_resources:
        executions = cast(
            Page[TriggerExecutionResponse],
            get_page_from_list(
                items_list=self.executions,
                response_model=TriggerExecutionResponse,
                include_resources=False,
                include_metadata=False,
            ),
        )
        resources = TriggerResponseResources(
            action=self.action.to_model(),
            event_source=self.event_source.to_model()
            if self.event_source
            else None,
            executions=executions,
        )
    return TriggerResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
        resources=resources,
    )
update(trigger_update: TriggerUpdate) -> TriggerSchema

Updates a trigger schema with a trigger update model.

Parameters:

Name Type Description Default
trigger_update TriggerUpdate

TriggerUpdate to update the trigger with.

required

Returns:

Type Description
TriggerSchema

The updated TriggerSchema.

Source code in src/zenml/zen_stores/schemas/trigger_schemas.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def update(self, trigger_update: "TriggerUpdate") -> "TriggerSchema":
    """Updates a trigger schema with a trigger update model.

    Args:
        trigger_update: `TriggerUpdate` to update the trigger with.

    Returns:
        The updated TriggerSchema.
    """
    for field, value in trigger_update.model_dump(
        exclude_unset=True,
        exclude_none=True,
    ).items():
        if field == "event_filter":
            self.event_filter = base64.b64encode(
                json.dumps(
                    trigger_update.event_filter, default=pydantic_encoder
                ).encode("utf-8")
            )
        else:
            setattr(self, field, value)

    self.updated = utc_now()
    return self
Functions
user_schemas

SQLModel implementation of user tables.

Classes
UserSchema

Bases: NamedSchema

SQL Model for users.

Functions
from_service_account_request(model: ServiceAccountRequest) -> UserSchema classmethod

Create a UserSchema from a Service Account request.

Parameters:

Name Type Description Default
model ServiceAccountRequest

The ServiceAccountRequest from which to create the schema.

required

Returns:

Type Description
UserSchema

The created UserSchema.

Source code in src/zenml/zen_stores/schemas/user_schemas.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
@classmethod
def from_service_account_request(
    cls, model: ServiceAccountRequest
) -> "UserSchema":
    """Create a `UserSchema` from a Service Account request.

    Args:
        model: The `ServiceAccountRequest` from which to create the
            schema.

    Returns:
        The created `UserSchema`.
    """
    return cls(
        name=model.name,
        description=model.description or "",
        active=model.active,
        is_service_account=True,
        email_opted_in=False,
        full_name="",
        is_admin=False,
    )
from_user_request(model: UserRequest) -> UserSchema classmethod

Create a UserSchema from a UserRequest.

Parameters:

Name Type Description Default
model UserRequest

The UserRequest from which to create the schema.

required

Returns:

Type Description
UserSchema

The created UserSchema.

Source code in src/zenml/zen_stores/schemas/user_schemas.py
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
@classmethod
def from_user_request(cls, model: UserRequest) -> "UserSchema":
    """Create a `UserSchema` from a `UserRequest`.

    Args:
        model: The `UserRequest` from which to create the schema.

    Returns:
        The created `UserSchema`.
    """
    return cls(
        name=model.name,
        full_name=model.full_name,
        active=model.active,
        password=model.create_hashed_password(),
        activation_token=model.create_hashed_activation_token(),
        external_user_id=model.external_user_id,
        email_opted_in=model.email_opted_in,
        email=model.email,
        is_service_account=False,
        is_admin=model.is_admin,
        user_metadata=json.dumps(model.user_metadata)
        if model.user_metadata
        else None,
    )
to_model(include_metadata: bool = False, include_resources: bool = False, include_private: bool = False, **kwargs: Any) -> UserResponse

Convert a UserSchema to a UserResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False
**kwargs Any

Keyword arguments to allow schema specific logic

{}
include_private bool

Whether to include the user private information this is to limit the amount of data one can get about other users.

False

Returns:

Type Description
UserResponse

The converted UserResponse.

Source code in src/zenml/zen_stores/schemas/user_schemas.py
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
def to_model(
    self,
    include_metadata: bool = False,
    include_resources: bool = False,
    include_private: bool = False,
    **kwargs: Any,
) -> UserResponse:
    """Convert a `UserSchema` to a `UserResponse`.

    Args:
        include_metadata: Whether the metadata will be filled.
        include_resources: Whether the resources will be filled.
        **kwargs: Keyword arguments to allow schema specific logic
        include_private: Whether to include the user private information
            this is to limit the amount of data one can get about other
            users.

    Returns:
        The converted `UserResponse`.
    """
    metadata = None
    if include_metadata:
        metadata = UserResponseMetadata(
            email=self.email if include_private else None,
            external_user_id=self.external_user_id,
            user_metadata=json.loads(self.user_metadata)
            if self.user_metadata
            else {},
        )

    return UserResponse(
        id=self.id,
        name=self.name,
        body=UserResponseBody(
            active=self.active,
            full_name=self.full_name,
            email_opted_in=self.email_opted_in,
            is_service_account=self.is_service_account,
            created=self.created,
            updated=self.updated,
            is_admin=self.is_admin,
            default_project_id=self.default_project_id,
        ),
        metadata=metadata,
    )
to_service_account_model(include_metadata: bool = False, include_resources: bool = False) -> ServiceAccountResponse

Convert a UserSchema to a ServiceAccountResponse.

Parameters:

Name Type Description Default
include_metadata bool

Whether the metadata will be filled.

False
include_resources bool

Whether the resources will be filled.

False

Returns:

Type Description
ServiceAccountResponse

The converted ServiceAccountResponse.

Source code in src/zenml/zen_stores/schemas/user_schemas.py
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
def to_service_account_model(
    self, include_metadata: bool = False, include_resources: bool = False
) -> ServiceAccountResponse:
    """Convert a `UserSchema` to a `ServiceAccountResponse`.

    Args:
         include_metadata: Whether the metadata will be filled.
         include_resources: Whether the resources will be filled.

    Returns:
         The converted `ServiceAccountResponse`.
    """
    metadata = None
    if include_metadata:
        metadata = ServiceAccountResponseMetadata(
            description=self.description or "",
        )

    body = ServiceAccountResponseBody(
        created=self.created,
        updated=self.updated,
        active=self.active,
    )

    return ServiceAccountResponse(
        id=self.id,
        name=self.name,
        body=body,
        metadata=metadata,
    )
update_service_account(service_account_update: ServiceAccountUpdate) -> UserSchema

Update a UserSchema from a ServiceAccountUpdate.

Parameters:

Name Type Description Default
service_account_update ServiceAccountUpdate

The ServiceAccountUpdate from which to update the schema.

required

Returns:

Type Description
UserSchema

The updated UserSchema.

Source code in src/zenml/zen_stores/schemas/user_schemas.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def update_service_account(
    self, service_account_update: ServiceAccountUpdate
) -> "UserSchema":
    """Update a `UserSchema` from a `ServiceAccountUpdate`.

    Args:
        service_account_update: The `ServiceAccountUpdate` from which
            to update the schema.

    Returns:
        The updated `UserSchema`.
    """
    for field, value in service_account_update.model_dump(
        exclude_none=True
    ).items():
        setattr(self, field, value)

    self.updated = utc_now()
    return self
update_user(user_update: UserUpdate) -> UserSchema

Update a UserSchema from a UserUpdate.

Parameters:

Name Type Description Default
user_update UserUpdate

The UserUpdate from which to update the schema.

required

Returns:

Type Description
UserSchema

The updated UserSchema.

Source code in src/zenml/zen_stores/schemas/user_schemas.py
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
def update_user(self, user_update: UserUpdate) -> "UserSchema":
    """Update a `UserSchema` from a `UserUpdate`.

    Args:
        user_update: The `UserUpdate` from which to update the schema.

    Returns:
        The updated `UserSchema`.
    """
    for field, value in user_update.model_dump(exclude_unset=True).items():
        if field == "old_password":
            continue

        if field == "password":
            setattr(self, field, user_update.create_hashed_password())
        elif field == "activation_token":
            setattr(
                self, field, user_update.create_hashed_activation_token()
            )
        elif field == "user_metadata":
            if value is not None:
                self.user_metadata = json.dumps(value)
        else:
            setattr(self, field, value)

    self.updated = utc_now()
    return self
Functions
utils

Utils for schemas.

Classes
RunMetadataInterface

The interface for entities with run metadata.

Functions
fetch_metadata() -> Dict[str, MetadataType]

Fetches the latest metadata entry related to the entity.

Returns:

Type Description
Dict[str, MetadataType]

A dictionary, where the key is the key of the metadata entry and the values represent the latest entry with this key.

Source code in src/zenml/zen_stores/schemas/utils.py
101
102
103
104
105
106
107
108
109
110
111
112
def fetch_metadata(self) -> Dict[str, MetadataType]:
    """Fetches the latest metadata entry related to the entity.

    Returns:
        A dictionary, where the key is the key of the metadata entry
            and the values represent the latest entry with this key.
    """
    metadata_collection = self.fetch_metadata_collection()
    return {
        k: sorted(v, key=lambda x: x.created, reverse=True)[0].value
        for k, v in metadata_collection.items()
    }
fetch_metadata_collection() -> Dict[str, List[RunMetadataEntry]]

Fetches all the metadata entries related to the entity.

Returns:

Type Description
Dict[str, List[RunMetadataEntry]]

A dictionary, where the key is the key of the metadata entry and the values represent the list of entries with this key.

Source code in src/zenml/zen_stores/schemas/utils.py
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def fetch_metadata_collection(self) -> Dict[str, List[RunMetadataEntry]]:
    """Fetches all the metadata entries related to the entity.

    Returns:
        A dictionary, where the key is the key of the metadata entry
            and the values represent the list of entries with this key.
    """
    metadata_collection: Dict[str, List[RunMetadataEntry]] = {}

    for rm in self.run_metadata:
        if rm.key not in metadata_collection:
            metadata_collection[rm.key] = []
        metadata_collection[rm.key].append(
            RunMetadataEntry(
                value=json.loads(rm.value),
                created=rm.created,
            )
        )

    return metadata_collection
Functions
get_page_from_list(items_list: List[S], response_model: Type[BaseResponse], size: int = 5, page: int = 1, include_resources: bool = False, include_metadata: bool = False) -> Page[BaseResponse]

Converts list of schemas into page of response models.

Parameters:

Name Type Description Default
items_list List[S]

List of schemas

required
response_model Type[BaseResponse]

Response model

required
size int

Page size

5
page int

Page number

1
include_metadata bool

Whether metadata should be included in response models

False
include_resources bool

Whether resources should be included in response models

False

Returns:

Type Description
Page[BaseResponse]

A page of list items.

Source code in src/zenml/zen_stores/schemas/utils.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def get_page_from_list(
    items_list: List[S],
    response_model: Type[BaseResponse],  # type: ignore[type-arg]
    size: int = 5,
    page: int = 1,
    include_resources: bool = False,
    include_metadata: bool = False,
) -> Page[BaseResponse]:  # type: ignore[type-arg]
    """Converts list of schemas into page of response models.

    Args:
        items_list: List of schemas
        response_model: Response model
        size: Page size
        page: Page number
        include_metadata: Whether metadata should be included in response models
        include_resources: Whether resources should be included in response models

    Returns:
        A page of list items.
    """
    total = len(items_list)
    if total == 0:
        total_pages = 1
    else:
        total_pages = math.ceil(total / size)

    start = (page - 1) * size
    end = start + size

    page_items = [
        item.to_model(
            include_metadata=include_metadata,
            include_resources=include_resources,
        )
        for item in items_list[start:end]
    ]
    return Page[response_model](  # type: ignore[valid-type]
        index=page,
        max_size=size,
        total_pages=total_pages,
        total=total,
        items=page_items,
    )
get_resource_type_name(schema_class: Type[BaseSchema]) -> str

Get the name of a resource from a schema class.

Parameters:

Name Type Description Default
schema_class Type[BaseSchema]

The schema class to get the name of.

required

Returns:

Type Description
str

The name of the resource.

Source code in src/zenml/zen_stores/schemas/utils.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def get_resource_type_name(schema_class: Type[BaseSchema]) -> str:
    """Get the name of a resource from a schema class.

    Args:
        schema_class: The schema class to get the name of.

    Returns:
        The name of the resource.
    """
    entity_name = schema_class.__tablename__
    assert isinstance(entity_name, str)
    # Some entities are plural, some are singular, some have multiple words
    # in their table name connected by underscores (e.g. pipeline_run)
    return entity_name.replace("_", " ").rstrip("s")

secrets_stores

Centralized secrets management.

Modules
aws_secrets_store

AWS Secrets Store implementation.

Classes
AWSSecretsStore(zen_store: BaseZenStore, **kwargs: Any)

Bases: ServiceConnectorSecretsStore

Secrets store implementation that uses the AWS Secrets Manager API.

This secrets store implementation uses the AWS Secrets Manager API to store secrets. It allows a single AWS Secrets Manager region "instance" to be shared with other ZenML deployments as well as other third party users and applications.

Here are some implementation highlights:

  • the name/ID of an AWS secret is derived from the ZenML secret UUID and a zenml prefix in the form zenml/{zenml_secret_uuid}. This clearly identifies a secret as being managed by ZenML in the AWS console.

  • the Secrets Store also uses AWS secret tags to store additional metadata associated with a ZenML secret. The zenml tag in particular is used to identify and group all secrets that belong to the same ZenML deployment.

  • all secret key-values configured in a ZenML secret are stored as a single JSON string value in the AWS secret value.

Source code in src/zenml/zen_stores/secrets_stores/base_secrets_store.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
def __init__(
    self,
    zen_store: "BaseZenStore",
    **kwargs: Any,
) -> None:
    """Create and initialize a secrets store.

    Args:
        zen_store: The ZenML store that owns this secrets store.
        **kwargs: Additional keyword arguments to pass to the Pydantic
            constructor.

    Raises:
        RuntimeError: If the store cannot be initialized.
    """
    super().__init__(**kwargs)
    self._zen_store = zen_store

    try:
        self._initialize()
    except Exception as e:
        raise RuntimeError(
            f"Error initializing {self.type.value} secrets store: {str(e)}"
        ) from e
Functions
delete_secret_values(secret_id: UUID) -> None

Deletes secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret.

required

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

RuntimeError

If the AWS Secrets Manager API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/aws_secrets_store.py
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
def delete_secret_values(self, secret_id: UUID) -> None:
    """Deletes secret values for an existing secret.

    Args:
        secret_id: The ID of the secret.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
        RuntimeError: If the AWS Secrets Manager API returns an unexpected
            error.
    """
    aws_secret_id = self._get_aws_secret_id(secret_id)

    try:
        self.client.delete_secret(
            SecretId=aws_secret_id,
            # We set this to force immediate deletion of the AWS secret
            # instead of waiting for the recovery window to expire.
            ForceDeleteWithoutRecovery=True,
        )
    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            raise KeyError(f"Secret with ID {secret_id} not found")

        if (
            e.response["Error"]["Code"] == "InvalidRequestException"
            and "marked for deletion" in e.response["Error"]["Message"]
        ):
            raise KeyError(f"Secret with ID {secret_id} not found")

        raise RuntimeError(
            f"Error deleting secret with ID {secret_id}: {e}"
        )

    logger.debug(f"Deleted AWS secret: {aws_secret_id}")
get_secret_values(secret_id: UUID) -> Dict[str, str]

Get the secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

ID of the secret.

required

Returns:

Type Description
Dict[str, str]

The secret values.

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

RuntimeError

If the AWS Secrets Manager API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/aws_secrets_store.py
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
def get_secret_values(self, secret_id: UUID) -> Dict[str, str]:
    """Get the secret values for an existing secret.

    Args:
        secret_id: ID of the secret.

    Returns:
        The secret values.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
        RuntimeError: If the AWS Secrets Manager API returns an unexpected
            error.
    """
    aws_secret_id = self._get_aws_secret_id(secret_id)

    try:
        get_secret_value_response = self.client.get_secret_value(
            SecretId=aws_secret_id
        )
        # We need a separate AWS API call to get the AWS secret tags which
        # contain the ZenML secret metadata, since the get_secret_ value API
        # does not return them.
        describe_secret_response = self.client.describe_secret(
            SecretId=aws_secret_id
        )
    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException" or (
            e.response["Error"]["Code"] == "InvalidRequestException"
            and "marked for deletion" in e.response["Error"]["Message"]
        ):
            raise KeyError(
                f"Can't find the secret values for secret ID '{secret_id}' "
                f"in the secrets store back-end: {str(e)}"
            ) from e

        raise RuntimeError(
            f"Error fetching secret with ID {secret_id} {e}"
        )

    # Convert the AWS secret tags to a metadata dictionary.
    metadata: Dict[str, str] = {
        tag["Key"]: tag["Value"]
        for tag in describe_secret_response["Tags"]
    }

    # The _verify_secret_metadata method raises a KeyError if the
    # secret is not valid or does not belong to this server. Here we
    # simply pass the exception up the stack, as if the secret was not found
    # in the first place.
    self._verify_secret_metadata(
        secret_id=secret_id,
        metadata=metadata,
    )

    values = get_secret_value_response["SecretString"]

    logger.debug(f"Fetched AWS secret: {aws_secret_id}")

    secret_values = json.loads(values)

    if not isinstance(secret_values, dict):
        raise RuntimeError(
            f"AWS secret values for secret ID {aws_secret_id} could not be "
            "decoded: expected a dictionary."
        )

    return secret_values
store_secret_values(secret_id: UUID, secret_values: Dict[str, str]) -> None

Store secret values for a new secret.

Parameters:

Name Type Description Default
secret_id UUID

ID of the secret.

required
secret_values Dict[str, str]

Values for the secret.

required

Raises:

Type Description
RuntimeError

If the AWS Secrets Manager API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/aws_secrets_store.py
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
def store_secret_values(
    self,
    secret_id: UUID,
    secret_values: Dict[str, str],
) -> None:
    """Store secret values for a new secret.

    Args:
        secret_id: ID of the secret.
        secret_values: Values for the secret.

    Raises:
        RuntimeError: If the AWS Secrets Manager API returns an unexpected
            error.
    """
    aws_secret_id = self._get_aws_secret_id(secret_id)
    secret_value = json.dumps(secret_values)

    # Convert the ZenML secret metadata to AWS tags
    metadata = self._get_secret_metadata(secret_id=secret_id)
    tags = self._get_aws_secret_tags(metadata)

    try:
        self.client.create_secret(
            Name=aws_secret_id,
            SecretString=secret_value,
            Tags=tags,
        )
    except ClientError as e:
        raise RuntimeError(f"Error creating secret: {e}")

    logger.debug(f"Created AWS secret: {aws_secret_id}")
update_secret_values(secret_id: UUID, secret_values: Dict[str, str]) -> None

Updates secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret to be updated.

required
secret_values Dict[str, str]

The new secret values.

required

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

RuntimeError

If the AWS Secrets Manager API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/aws_secrets_store.py
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
def update_secret_values(
    self,
    secret_id: UUID,
    secret_values: Dict[str, str],
) -> None:
    """Updates secret values for an existing secret.

    Args:
        secret_id: The ID of the secret to be updated.
        secret_values: The new secret values.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
        RuntimeError: If the AWS Secrets Manager API returns an unexpected
            error.
    """
    aws_secret_id = self._get_aws_secret_id(secret_id)
    secret_value = json.dumps(secret_values)

    # Convert the ZenML secret metadata to AWS tags
    metadata = self._get_secret_metadata(secret_id)
    tags = self._get_aws_secret_tags(metadata)

    try:
        # One call to update the secret values
        self.client.put_secret_value(
            SecretId=aws_secret_id,
            SecretString=secret_value,
        )
        # Another call to update the tags
        self.client.tag_resource(
            SecretId=aws_secret_id,
            Tags=tags,
        )
    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            raise KeyError(f"Secret with ID {secret_id} not found")
        raise RuntimeError(f"Error updating secret: {e}")

    logger.debug(f"Updated AWS secret: {aws_secret_id}")
AWSSecretsStoreConfiguration

Bases: ServiceConnectorSecretsStoreConfiguration

AWS secrets store configuration.

Attributes:

Name Type Description
type SecretsStoreType

The type of the store.

Attributes
region: str property

The AWS region to use.

Returns:

Type Description
str

The AWS region to use.

Raises:

Type Description
ValueError

If the region is not configured.

Functions
populate_config(data: Dict[str, Any]) -> Dict[str, Any] classmethod

Populate the connector configuration from legacy attributes.

Parameters:

Name Type Description Default
data Dict[str, Any]

Dict representing user-specified runtime settings.

required

Returns:

Type Description
Dict[str, Any]

Validated settings.

Source code in src/zenml/zen_stores/secrets_stores/aws_secrets_store.py
 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
@model_validator(mode="before")
@classmethod
@before_validator_handler
def populate_config(cls, data: Dict[str, Any]) -> Dict[str, Any]:
    """Populate the connector configuration from legacy attributes.

    Args:
        data: Dict representing user-specified runtime settings.

    Returns:
        Validated settings.
    """
    # Search for legacy attributes and populate the connector configuration
    # from them, if they exist.
    if data.get("region_name"):
        if not data.get("aws_access_key_id") or not data.get(
            "aws_secret_access_key"
        ):
            logger.warning(
                "The `region_name` AWS secrets store attribute is deprecated "
                "and will be removed in a future version of ZenML. Please use "
                "the `auth_method` and `auth_config` attributes instead. "
                "Using an implicit authentication method for AWS Secrets."
            )
            data["auth_method"] = AWSAuthenticationMethods.IMPLICIT
            data["auth_config"] = dict(
                region=data.get("region_name"),
            )
        else:
            logger.warning(
                "The `aws_access_key_id`, `aws_secret_access_key` and "
                "`region_name` AWS secrets store attributes are deprecated and "
                "will be removed in a future version of ZenML. Please use the "
                "`auth_method` and `auth_config` attributes instead."
            )
            data["auth_method"] = AWSAuthenticationMethods.SECRET_KEY
            data["auth_config"] = dict(
                aws_access_key_id=data.get("aws_access_key_id"),
                aws_secret_access_key=data.get("aws_secret_access_key"),
                region=data.get("region_name"),
            )

    return data
Functions
azure_secrets_store

Azure Secrets Store implementation.

Classes
AzureSecretsStore(zen_store: BaseZenStore, **kwargs: Any)

Bases: ServiceConnectorSecretsStore

Secrets store implementation that uses the Azure Key Vault API.

This secrets store implementation uses the Azure Key Vault API to store secrets. It allows a single Azure Key Vault to be shared with other ZenML deployments as well as other third party users and applications.

Here are some implementation highlights:

  • the name/ID of an Azure secret is derived from the ZenML secret UUID and a zenml prefix in the form zenml-{zenml_secret_uuid}. This clearly identifies a secret as being managed by ZenML in the Azure console.

  • the Secrets Store also uses Azure Key Vault secret tags to store metadata associated with a ZenML secret. The zenml tag in particular is used to identify and group all secrets that belong to the same ZenML deployment.

  • all secret key-values configured in a ZenML secret are stored as a single JSON string value in the Azure Key Vault secret value.

Source code in src/zenml/zen_stores/secrets_stores/base_secrets_store.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
def __init__(
    self,
    zen_store: "BaseZenStore",
    **kwargs: Any,
) -> None:
    """Create and initialize a secrets store.

    Args:
        zen_store: The ZenML store that owns this secrets store.
        **kwargs: Additional keyword arguments to pass to the Pydantic
            constructor.

    Raises:
        RuntimeError: If the store cannot be initialized.
    """
    super().__init__(**kwargs)
    self._zen_store = zen_store

    try:
        self._initialize()
    except Exception as e:
        raise RuntimeError(
            f"Error initializing {self.type.value} secrets store: {str(e)}"
        ) from e
Attributes
client: SecretClient property

Initialize and return the Azure Key Vault client.

Returns:

Type Description
SecretClient

The Azure Key Vault client.

Functions
delete_secret_values(secret_id: UUID) -> None

Deletes secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret.

required

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

RuntimeError

if the Azure Key Vault API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/azure_secrets_store.py
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
def delete_secret_values(self, secret_id: UUID) -> None:
    """Deletes secret values for an existing secret.

    Args:
        secret_id: The ID of the secret.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
        RuntimeError: if the Azure Key Vault API returns an unexpected
            error.
    """
    azure_secret_id = self._get_azure_secret_id(secret_id)

    try:
        self.client.begin_delete_secret(
            azure_secret_id,
        ).wait()
    except ResourceNotFoundError:
        raise KeyError(f"Secret with ID {secret_id} not found")
    except HttpResponseError as e:
        raise RuntimeError(
            f"Error deleting secret with ID {secret_id}: {e}"
        )

    logger.debug(f"Deleted Azure secret: {azure_secret_id}")
get_secret_values(secret_id: UUID) -> Dict[str, str]

Get the secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

ID of the secret.

required

Returns:

Type Description
Dict[str, str]

The secret values.

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

RuntimeError

if the Azure Key Vault API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/azure_secrets_store.py
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
def get_secret_values(self, secret_id: UUID) -> Dict[str, str]:
    """Get the secret values for an existing secret.

    Args:
        secret_id: ID of the secret.

    Returns:
        The secret values.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
        RuntimeError: if the Azure Key Vault API returns an unexpected
            error.
    """
    azure_secret_id = self._get_azure_secret_id(secret_id)

    try:
        azure_secret = self.client.get_secret(
            azure_secret_id,
        )
    except ResourceNotFoundError as e:
        raise KeyError(
            f"Can't find the secret values for secret ID '{secret_id}' "
            f"in the secrets store back-end: {str(e)}"
        ) from e
    except HttpResponseError as e:
        raise RuntimeError(
            f"Error fetching secret with ID {secret_id} {e}"
        )

    # The _verify_secret_metadata method raises a KeyError if the
    # secret is not valid or does not belong to this server. Here we
    # simply pass the exception up the stack, as if the secret was not found
    # in the first place.
    assert azure_secret.properties.tags is not None
    self._verify_secret_metadata(
        secret_id=secret_id,
        metadata=azure_secret.properties.tags,
    )

    values = json.loads(azure_secret.value) if azure_secret.value else {}

    if not isinstance(values, dict):
        raise RuntimeError(
            f"Azure Key Vault secret values for secret {azure_secret_id} "
            "could not be retrieved: invalid type for values"
        )

    logger.debug(f"Retrieved Azure secret: {azure_secret_id}")

    return values
store_secret_values(secret_id: UUID, secret_values: Dict[str, str]) -> None

Store secret values for a new secret.

Parameters:

Name Type Description Default
secret_id UUID

ID of the secret.

required
secret_values Dict[str, str]

Values for the secret.

required

Raises:

Type Description
RuntimeError

if the Azure Key Vault API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/azure_secrets_store.py
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
def store_secret_values(
    self,
    secret_id: UUID,
    secret_values: Dict[str, str],
) -> None:
    """Store secret values for a new secret.

    Args:
        secret_id: ID of the secret.
        secret_values: Values for the secret.

    Raises:
        RuntimeError: if the Azure Key Vault API returns an unexpected
            error.
    """
    azure_secret_id = self._get_azure_secret_id(secret_id)
    secret_value = json.dumps(secret_values)

    # Use the ZenML secret metadata as Azure tags
    metadata = self._get_secret_metadata(secret_id=secret_id)

    try:
        self.client.set_secret(
            azure_secret_id,
            secret_value,
            tags=metadata,
            content_type="application/json",
        )
    except HttpResponseError as e:
        raise RuntimeError(f"Error creating secret: {e}")

    logger.debug(f"Created Azure secret: {azure_secret_id}")
update_secret_values(secret_id: UUID, secret_values: Dict[str, str]) -> None

Updates secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret to be updated.

required
secret_values Dict[str, str]

The new secret values.

required

Raises:

Type Description
RuntimeError

if the Azure Key Vault API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/azure_secrets_store.py
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
def update_secret_values(
    self,
    secret_id: UUID,
    secret_values: Dict[str, str],
) -> None:
    """Updates secret values for an existing secret.

    Args:
        secret_id: The ID of the secret to be updated.
        secret_values: The new secret values.

    Raises:
        RuntimeError: if the Azure Key Vault API returns an unexpected
            error.
    """
    azure_secret_id = self._get_azure_secret_id(secret_id)
    secret_value = json.dumps(secret_values)

    # Convert the ZenML secret metadata to Azure tags
    metadata = self._get_secret_metadata(secret_id=secret_id)

    try:
        self.client.set_secret(
            azure_secret_id,
            secret_value,
            tags=metadata,
            content_type="application/json",
        )
    except HttpResponseError as e:
        raise RuntimeError(f"Error updating secret {secret_id}: {e}")

    logger.debug(f"Updated Azure secret: {azure_secret_id}")
AzureSecretsStoreConfiguration

Bases: ServiceConnectorSecretsStoreConfiguration

Azure secrets store configuration.

Attributes:

Name Type Description
type SecretsStoreType

The type of the store.

key_vault_name str

Name of the Azure Key Vault that this secrets store will use to store secrets.

Functions
populate_config(data: Dict[str, Any]) -> Dict[str, Any] classmethod

Populate the connector configuration from legacy attributes.

Parameters:

Name Type Description Default
data Dict[str, Any]

Dict representing user-specified runtime settings.

required

Returns:

Type Description
Dict[str, Any]

Validated settings.

Source code in src/zenml/zen_stores/secrets_stores/azure_secrets_store.py
 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
@model_validator(mode="before")
@classmethod
@before_validator_handler
def populate_config(cls, data: Dict[str, Any]) -> Dict[str, Any]:
    """Populate the connector configuration from legacy attributes.

    Args:
        data: Dict representing user-specified runtime settings.

    Returns:
        Validated settings.
    """
    # Search for legacy attributes and populate the connector configuration
    # from them, if they exist.
    if (
        data.get("azure_client_id")
        and data.get("azure_client_secret")
        and data.get("azure_tenant_id")
    ):
        logger.warning(
            "The `azure_client_id`, `azure_client_secret` and "
            "`azure_tenant_id` attributes are deprecated and will be "
            "removed in a future version or ZenML. Please use the "
            "`auth_method` and `auth_config` attributes instead."
        )
        data["auth_method"] = AzureAuthenticationMethods.SERVICE_PRINCIPAL
        data["auth_config"] = dict(
            client_id=data.get("azure_client_id"),
            client_secret=data.get("azure_client_secret"),
            tenant_id=data.get("azure_tenant_id"),
        )

    return data
Functions
base_secrets_store

Base Secrets Store implementation.

Classes
BaseSecretsStore(zen_store: BaseZenStore, **kwargs: Any)

Bases: BaseModel, SecretsStoreInterface, ABC

Base class for accessing and persisting ZenML secret values.

Attributes:

Name Type Description
config SecretsStoreConfiguration

The configuration of the secret store.

_zen_store Optional[BaseZenStore]

The ZenML store that owns this secrets store.

Create and initialize a secrets store.

Parameters:

Name Type Description Default
zen_store BaseZenStore

The ZenML store that owns this secrets store.

required
**kwargs Any

Additional keyword arguments to pass to the Pydantic constructor.

{}

Raises:

Type Description
RuntimeError

If the store cannot be initialized.

Source code in src/zenml/zen_stores/secrets_stores/base_secrets_store.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
def __init__(
    self,
    zen_store: "BaseZenStore",
    **kwargs: Any,
) -> None:
    """Create and initialize a secrets store.

    Args:
        zen_store: The ZenML store that owns this secrets store.
        **kwargs: Additional keyword arguments to pass to the Pydantic
            constructor.

    Raises:
        RuntimeError: If the store cannot be initialized.
    """
    super().__init__(**kwargs)
    self._zen_store = zen_store

    try:
        self._initialize()
    except Exception as e:
        raise RuntimeError(
            f"Error initializing {self.type.value} secrets store: {str(e)}"
        ) from e
Attributes
type: SecretsStoreType property

The type of the secrets store.

Returns:

Type Description
SecretsStoreType

The type of the secrets store.

zen_store: BaseZenStore property

The ZenML store that owns this secrets store.

Returns:

Type Description
BaseZenStore

The ZenML store that owns this secrets store.

Raises:

Type Description
ValueError

If the store is not initialized.

Functions
convert_config(data: Dict[str, Any]) -> Dict[str, Any] classmethod

Method to infer the correct type of the config and convert.

Parameters:

Name Type Description Default
data Dict[str, Any]

The provided configuration object, can potentially be a generic object

required

Raises:

Type Description
ValueError

If the provided config object's type does not match any of the current implementations.

Returns:

Type Description
Dict[str, Any]

The converted configuration object.

Source code in src/zenml/zen_stores/secrets_stores/base_secrets_store.py
 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
@model_validator(mode="before")
@classmethod
@before_validator_handler
def convert_config(cls, data: Dict[str, Any]) -> Dict[str, Any]:
    """Method to infer the correct type of the config and convert.

    Args:
        data: The provided configuration object, can potentially be a
            generic object

    Raises:
        ValueError: If the provided config object's type does not match
            any of the current implementations.

    Returns:
        The converted configuration object.
    """
    if data["config"].type == SecretsStoreType.SQL:
        from zenml.zen_stores.secrets_stores.sql_secrets_store import (
            SqlSecretsStoreConfiguration,
        )

        data["config"] = SqlSecretsStoreConfiguration(
            **data["config"].model_dump()
        )

    elif data["config"].type == SecretsStoreType.GCP:
        from zenml.zen_stores.secrets_stores.gcp_secrets_store import (
            GCPSecretsStoreConfiguration,
        )

        data["config"] = GCPSecretsStoreConfiguration(
            **data["config"].model_dump()
        )

    elif data["config"].type == SecretsStoreType.AWS:
        from zenml.zen_stores.secrets_stores.aws_secrets_store import (
            AWSSecretsStoreConfiguration,
        )

        data["config"] = AWSSecretsStoreConfiguration(
            **data["config"].model_dump()
        )

    elif data["config"].type == SecretsStoreType.AZURE:
        from zenml.zen_stores.secrets_stores.azure_secrets_store import (
            AzureSecretsStoreConfiguration,
        )

        data["config"] = AzureSecretsStoreConfiguration(
            **data["config"].model_dump()
        )

    elif data["config"].type == SecretsStoreType.HASHICORP:
        from zenml.zen_stores.secrets_stores.hashicorp_secrets_store import (
            HashiCorpVaultSecretsStoreConfiguration,
        )

        data["config"] = HashiCorpVaultSecretsStoreConfiguration(
            **data["config"].model_dump()
        )
    elif (
        data["config"].type == SecretsStoreType.CUSTOM
        or data["config"].type == SecretsStoreType.NONE
    ):
        pass
    else:
        raise ValueError(
            f"Unknown type '{data['config'].type}' for the configuration."
        )

    return data
create_store(config: SecretsStoreConfiguration, **kwargs: Any) -> BaseSecretsStore staticmethod

Create and initialize a secrets store from a secrets store configuration.

Parameters:

Name Type Description Default
config SecretsStoreConfiguration

The secrets store configuration to use.

required
**kwargs Any

Additional keyword arguments to pass to the store class

{}

Returns:

Type Description
BaseSecretsStore

The initialized secrets store.

Source code in src/zenml/zen_stores/secrets_stores/base_secrets_store.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
@staticmethod
def create_store(
    config: SecretsStoreConfiguration,
    **kwargs: Any,
) -> "BaseSecretsStore":
    """Create and initialize a secrets store from a secrets store configuration.

    Args:
        config: The secrets store configuration to use.
        **kwargs: Additional keyword arguments to pass to the store class

    Returns:
        The initialized secrets store.
    """
    logger.debug(
        f"Creating secrets store with type '{config.type.value}'..."
    )
    store_class = BaseSecretsStore.get_store_class(config)
    store = store_class(
        config=config,
        **kwargs,
    )
    return store
get_store_class(store_config: SecretsStoreConfiguration) -> Type[BaseSecretsStore] staticmethod

Returns the class of the given secrets store type.

Parameters:

Name Type Description Default
store_config SecretsStoreConfiguration

The configuration of the secrets store.

required

Returns:

Type Description
Type[BaseSecretsStore]

The class corresponding to the configured secrets store or None if

Type[BaseSecretsStore]

the type is unknown.

Raises:

Type Description
TypeError

If the secrets store type is unsupported.

Source code in src/zenml/zen_stores/secrets_stores/base_secrets_store.py
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
@staticmethod
def get_store_class(
    store_config: SecretsStoreConfiguration,
) -> Type["BaseSecretsStore"]:
    """Returns the class of the given secrets store type.

    Args:
        store_config: The configuration of the secrets store.

    Returns:
        The class corresponding to the configured secrets store or None if
        the type is unknown.

    Raises:
        TypeError: If the secrets store type is unsupported.
    """
    if store_config.type == SecretsStoreType.SQL:
        from zenml.zen_stores.secrets_stores.sql_secrets_store import (
            SqlSecretsStore,
        )

        return SqlSecretsStore

    if store_config.type == SecretsStoreType.AWS:
        from zenml.zen_stores.secrets_stores.aws_secrets_store import (
            AWSSecretsStore,
        )

        return AWSSecretsStore
    elif store_config.type == SecretsStoreType.GCP:
        from zenml.zen_stores.secrets_stores.gcp_secrets_store import (
            GCPSecretsStore,
        )

        return GCPSecretsStore
    elif store_config.type == SecretsStoreType.AZURE:
        from zenml.zen_stores.secrets_stores.azure_secrets_store import (
            AzureSecretsStore,
        )

        return AzureSecretsStore
    elif store_config.type == SecretsStoreType.HASHICORP:
        from zenml.zen_stores.secrets_stores.hashicorp_secrets_store import (
            HashiCorpVaultSecretsStore,
        )

        return HashiCorpVaultSecretsStore
    elif store_config.type != SecretsStoreType.CUSTOM:
        raise TypeError(
            f"No store implementation found for secrets store type "
            f"`{store_config.type.value}`."
        )

    return BaseSecretsStore._load_custom_store_class(store_config)
Functions Modules
gcp_secrets_store

Implementation of the GCP Secrets Store.

Classes
GCPSecretsStore(zen_store: BaseZenStore, **kwargs: Any)

Bases: ServiceConnectorSecretsStore

Secrets store implementation that uses the GCP Secrets Manager API.

Source code in src/zenml/zen_stores/secrets_stores/base_secrets_store.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
def __init__(
    self,
    zen_store: "BaseZenStore",
    **kwargs: Any,
) -> None:
    """Create and initialize a secrets store.

    Args:
        zen_store: The ZenML store that owns this secrets store.
        **kwargs: Additional keyword arguments to pass to the Pydantic
            constructor.

    Raises:
        RuntimeError: If the store cannot be initialized.
    """
    super().__init__(**kwargs)
    self._zen_store = zen_store

    try:
        self._initialize()
    except Exception as e:
        raise RuntimeError(
            f"Error initializing {self.type.value} secrets store: {str(e)}"
        ) from e
Attributes
client: SecretManagerServiceClient property

Initialize and return the GCP Secrets Manager client.

Returns:

Type Description
SecretManagerServiceClient

The GCP Secrets Manager client instance.

parent_name: str property

Construct the GCP parent path to the secret manager.

Returns:

Type Description
str

The parent path to the secret manager

Functions
delete_secret_values(secret_id: UUID) -> None

Deletes secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret.

required

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

RuntimeError

if the GCP Secrets Manager API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/gcp_secrets_store.py
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
def delete_secret_values(self, secret_id: UUID) -> None:
    """Deletes secret values for an existing secret.

    Args:
        secret_id: The ID of the secret.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
        RuntimeError: if the GCP Secrets Manager API returns an unexpected
            error.
    """
    gcp_secret_name = self.client.secret_path(
        self.config.project_id,
        self._get_gcp_secret_name(secret_id=secret_id),
    )

    try:
        self.client.delete_secret(request={"name": gcp_secret_name})
    except google_exceptions.NotFound:
        raise KeyError(f"Secret with ID {secret_id} not found")
    except Exception as e:
        raise RuntimeError(f"Failed to delete secret: {str(e)}") from e

    logger.debug(f"Deleted GCP secret: {gcp_secret_name}")
get_secret_values(secret_id: UUID) -> Dict[str, str]

Get the secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

ID of the secret.

required

Returns:

Type Description
Dict[str, str]

The secret values.

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

RuntimeError

if the GCP Secrets Manager API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/gcp_secrets_store.py
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
def get_secret_values(self, secret_id: UUID) -> Dict[str, str]:
    """Get the secret values for an existing secret.

    Args:
        secret_id: ID of the secret.

    Returns:
        The secret values.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
        RuntimeError: if the GCP Secrets Manager API returns an unexpected
            error.
    """
    gcp_secret_name = self.client.secret_path(
        self.config.project_id,
        self._get_gcp_secret_name(secret_id=secret_id),
    )

    try:
        secret = self.client.get_secret(name=gcp_secret_name)
        secret_version_values = self.client.access_secret_version(
            name=f"{gcp_secret_name}/versions/latest"
        )
    except google_exceptions.NotFound as e:
        raise KeyError(
            f"Can't find the secret values for secret ID '{secret_id}' "
            f"in the secrets store back-end: {str(e)}"
        ) from e
    except Exception as e:
        raise RuntimeError(
            f"Error fetching secret with ID {secret_id} {e}"
        )

    # The GCP secret labels do not really behave like a dictionary: when
    # a key is not found, it does not raise a KeyError, but instead
    # returns an empty string. That's why we make this conversion.
    metadata = dict(secret.labels)

    # The _verify_secret_metadata method raises a KeyError if the
    # secret is not valid or does not belong to this server. Here we
    # simply pass the exception up the stack, as if the secret was not found
    # in the first place.
    self._verify_secret_metadata(
        secret_id=secret_id,
        metadata=metadata,
    )

    secret_values = json.loads(
        secret_version_values.payload.data.decode("UTF-8")
    )

    if not isinstance(secret_values, dict):
        raise RuntimeError(
            f"Google secret values for secret ID {gcp_secret_name} could "
            "not be decoded: expected a dictionary."
        )

    logger.debug(f"Fetched GCP secret: {gcp_secret_name}")

    return secret_values
store_secret_values(secret_id: UUID, secret_values: Dict[str, str]) -> None

Store secret values for a new secret.

Parameters:

Name Type Description Default
secret_id UUID

ID of the secret.

required
secret_values Dict[str, str]

Values for the secret.

required

Raises:

Type Description
RuntimeError

if the GCP Secrets Manager API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/gcp_secrets_store.py
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
def store_secret_values(
    self,
    secret_id: UUID,
    secret_values: Dict[str, str],
) -> None:
    """Store secret values for a new secret.

    Args:
        secret_id: ID of the secret.
        secret_values: Values for the secret.

    Raises:
        RuntimeError: if the GCP Secrets Manager API returns an unexpected
            error.
    """
    secret_value = json.dumps(secret_values)

    labels = self._get_secret_metadata(secret_id=secret_id)

    try:
        gcp_secret = self.client.create_secret(
            request={
                "parent": self.parent_name,
                "secret_id": self._get_gcp_secret_name(secret_id),
                "secret": {
                    "replication": {"automatic": {}},
                    "labels": labels,
                },
            }
        )

        logger.debug(f"Created empty GCP parent secret: {gcp_secret.name}")

        self.client.add_secret_version(
            request={
                "parent": gcp_secret.name,
                "payload": {"data": secret_value.encode()},
            }
        )

        logger.debug(f"Added value to GCP secret {gcp_secret.name}")
    except Exception as e:
        raise RuntimeError(f"Failed to create secret.: {str(e)}") from e

    logger.debug(f"Created GCP secret {gcp_secret.name}")
update_secret_values(secret_id: UUID, secret_values: Dict[str, str]) -> None

Updates secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret to be updated.

required
secret_values Dict[str, str]

The new secret values.

required

Raises:

Type Description
RuntimeError

if the GCP Secrets Manager API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/gcp_secrets_store.py
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
def update_secret_values(
    self,
    secret_id: UUID,
    secret_values: Dict[str, str],
) -> None:
    """Updates secret values for an existing secret.

    Args:
        secret_id: The ID of the secret to be updated.
        secret_values: The new secret values.

    Raises:
        RuntimeError: if the GCP Secrets Manager API returns an unexpected
            error.
    """
    gcp_secret_name = self.client.secret_path(
        self.config.project_id,
        self._get_gcp_secret_name(secret_id=secret_id),
    )

    # Convert the ZenML secret metadata to GCP labels
    metadata = self._get_secret_metadata(secret_id)

    try:
        # Update the secret metadata
        update_secret = {
            "name": gcp_secret_name,
            "labels": metadata,
        }
        update_mask = {"paths": ["labels"]}
        gcp_updated_secret = self.client.update_secret(
            request={
                "secret": update_secret,
                "update_mask": update_mask,
            }
        )
        # Add a new secret version
        secret_value = json.dumps(secret_values)
        self.client.add_secret_version(
            request={
                "parent": gcp_updated_secret.name,
                "payload": {"data": secret_value.encode()},
            }
        )
    except Exception as e:
        raise RuntimeError(f"Error updating secret: {e}") from e

    logger.debug(f"Updated GCP secret: {gcp_secret_name}")
GCPSecretsStoreConfiguration

Bases: ServiceConnectorSecretsStoreConfiguration

GCP secrets store configuration.

Attributes:

Name Type Description
type SecretsStoreType

The type of the store.

Attributes
project_id: str property

Get the GCP project ID.

Returns:

Type Description
str

The GCP project ID.

Raises:

Type Description
ValueError

If the project ID is not set.

Functions
populate_config(data: Dict[str, Any]) -> Dict[str, Any] classmethod

Populate the connector configuration from legacy attributes.

Parameters:

Name Type Description Default
data Dict[str, Any]

Dict representing user-specified runtime settings.

required

Returns:

Type Description
Dict[str, Any]

Validated settings.

Source code in src/zenml/zen_stores/secrets_stores/gcp_secrets_store.py
 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
@model_validator(mode="before")
@classmethod
@before_validator_handler
def populate_config(cls, data: Dict[str, Any]) -> Dict[str, Any]:
    """Populate the connector configuration from legacy attributes.

    Args:
        data: Dict representing user-specified runtime settings.

    Returns:
        Validated settings.
    """
    # Search for legacy attributes and populate the connector configuration
    # from them, if they exist.
    if data.get("project_id"):
        if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"):
            logger.warning(
                "The `project_id` GCP secrets store attribute is "
                "deprecated and will be removed in a future version of ZenML. "
                "Please use the `auth_method` and `auth_config` attributes "
                "instead. Using an implicit GCP authentication to access "
                "the GCP Secrets Manager API."
            )
            data["auth_method"] = GCPAuthenticationMethods.IMPLICIT
            data["auth_config"] = dict(
                project_id=data.get("project_id"),
            )
        else:
            logger.warning(
                "The `project_id` GCP secrets store attribute and the "
                "`GOOGLE_APPLICATION_CREDENTIALS` environment variable are "
                "deprecated and will be removed in a future version of ZenML. "
                "Please use the `auth_method` and `auth_config` attributes "
                "instead."
            )
            data["auth_method"] = GCPAuthenticationMethods.SERVICE_ACCOUNT
            data["auth_config"] = dict(
                project_id=data.get("project_id"),
            )
            # Load the service account credentials from the file
            with open(os.environ["GOOGLE_APPLICATION_CREDENTIALS"]) as f:
                data["auth_config"]["service_account_json"] = f.read()

    return data
Functions
hashicorp_secrets_store

HashiCorp Vault Secrets Store implementation.

Classes
HashiCorpVaultSecretsStore(zen_store: BaseZenStore, **kwargs: Any)

Bases: BaseSecretsStore

Secrets store implementation that uses the HashiCorp Vault API.

This secrets store implementation uses the HashiCorp Vault API to store secrets. It allows a single HashiCorp Vault server to be shared with other ZenML deployments as well as other third party users and applications.

Here are some implementation highlights:

  • the name/ID of an HashiCorp Vault secret is derived from the ZenML secret UUID and a zenml prefix in the form zenml/{zenml_secret_uuid}. This clearly identifies a secret as being managed by ZenML in the HashiCorp Vault server.

  • given that HashiCorp Vault secrets do not support attaching arbitrary metadata in the form of label or tags, we store the entire ZenML secret metadata alongside the secret values in the HashiCorp Vault secret value.

Attributes:

Name Type Description
config HashiCorpVaultSecretsStoreConfiguration

The configuration of the HashiCorp Vault secrets store.

TYPE SecretsStoreType

The type of the store.

CONFIG_TYPE Type[SecretsStoreConfiguration]

The type of the store configuration.

Source code in src/zenml/zen_stores/secrets_stores/base_secrets_store.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
def __init__(
    self,
    zen_store: "BaseZenStore",
    **kwargs: Any,
) -> None:
    """Create and initialize a secrets store.

    Args:
        zen_store: The ZenML store that owns this secrets store.
        **kwargs: Additional keyword arguments to pass to the Pydantic
            constructor.

    Raises:
        RuntimeError: If the store cannot be initialized.
    """
    super().__init__(**kwargs)
    self._zen_store = zen_store

    try:
        self._initialize()
    except Exception as e:
        raise RuntimeError(
            f"Error initializing {self.type.value} secrets store: {str(e)}"
        ) from e
Attributes
client: hvac.Client property

Initialize and return the HashiCorp Vault client.

Returns:

Type Description
Client

The HashiCorp Vault client.

Functions
delete_secret_values(secret_id: UUID) -> None

Deletes secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret.

required

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

RuntimeError

If the HashiCorp Vault API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/hashicorp_secrets_store.py
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
def delete_secret_values(self, secret_id: UUID) -> None:
    """Deletes secret values for an existing secret.

    Args:
        secret_id: The ID of the secret.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
        RuntimeError: If the HashiCorp Vault API returns an unexpected
            error.
    """
    vault_secret_id = self._get_vault_secret_id(secret_id)

    try:
        self.client.secrets.kv.v2.delete_metadata_and_all_versions(
            path=vault_secret_id,
        )
    except InvalidPath:
        raise KeyError(f"Secret with ID {secret_id} does not exist.")
    except VaultError as e:
        raise RuntimeError(
            f"Error deleting secret with ID {secret_id}: {e}"
        )

    logger.debug(f"Deleted HashiCorp Vault secret: {vault_secret_id}")
get_secret_values(secret_id: UUID) -> Dict[str, str]

Get the secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

ID of the secret.

required

Returns:

Type Description
Dict[str, str]

The secret values.

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

RuntimeError

If the HashiCorp Vault API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/hashicorp_secrets_store.py
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
def get_secret_values(self, secret_id: UUID) -> Dict[str, str]:
    """Get the secret values for an existing secret.

    Args:
        secret_id: ID of the secret.

    Returns:
        The secret values.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
        RuntimeError: If the HashiCorp Vault API returns an unexpected
            error.
    """
    vault_secret_id = self._get_vault_secret_id(secret_id)

    try:
        vault_secret = (
            self.client.secrets.kv.v2.read_secret(
                path=vault_secret_id,
            )
            .get("data", {})
            .get("data", {})
        )
    except InvalidPath as e:
        raise KeyError(
            f"Can't find the secret values for secret ID '{secret_id}' "
            f"in the secrets store back-end: {str(e)}"
        ) from e
    except VaultError as e:
        raise RuntimeError(
            f"Error fetching secret with ID {secret_id} {e}"
        )

    try:
        metadata = vault_secret[ZENML_VAULT_SECRET_METADATA_KEY]
        values = vault_secret[ZENML_VAULT_SECRET_VALUES_KEY]
    except (KeyError, ValueError) as e:
        raise KeyError(
            f"Secret could not be retrieved: missing required metadata: {e}"
        )

    if not isinstance(values, dict) or not isinstance(metadata, dict):
        raise RuntimeError(
            f"HashiCorp Vault secret values for secret {vault_secret_id} "
            "could not be retrieved: invalid type for metadata or values"
        )

    # The _verify_secret_metadata method raises a KeyError if the
    # secret is not valid or does not belong to this server. Here we
    # simply pass the exception up the stack, as if the secret was not found
    # in the first place.
    self._verify_secret_metadata(
        secret_id=secret_id,
        metadata=metadata,
    )

    logger.debug(f"Fetched HashiCorp Vault secret: {vault_secret_id}")

    return values
store_secret_values(secret_id: UUID, secret_values: Dict[str, str]) -> None

Store secret values for a new secret.

Parameters:

Name Type Description Default
secret_id UUID

ID of the secret.

required
secret_values Dict[str, str]

Values for the secret.

required

Raises:

Type Description
RuntimeError

If the HashiCorp Vault API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/hashicorp_secrets_store.py
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
def store_secret_values(
    self,
    secret_id: UUID,
    secret_values: Dict[str, str],
) -> None:
    """Store secret values for a new secret.

    Args:
        secret_id: ID of the secret.
        secret_values: Values for the secret.

    Raises:
        RuntimeError: If the HashiCorp Vault API returns an unexpected
            error.
    """
    vault_secret_id = self._get_vault_secret_id(secret_id)

    metadata = self._get_secret_metadata(secret_id=secret_id)

    try:
        self.client.secrets.kv.v2.create_or_update_secret(
            path=vault_secret_id,
            # Store the ZenML secret metadata alongside the secret values
            secret={
                ZENML_VAULT_SECRET_VALUES_KEY: secret_values,
                ZENML_VAULT_SECRET_METADATA_KEY: metadata,
            },
            # Do not allow overwriting an existing secret
            cas=0,
        )
    except VaultError as e:
        raise RuntimeError(f"Error creating secret: {e}")

    logger.debug(f"Created HashiCorp Vault secret: {vault_secret_id}")
update_secret_values(secret_id: UUID, secret_values: Dict[str, str]) -> None

Updates secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret to be updated.

required
secret_values Dict[str, str]

The new secret values.

required

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

RuntimeError

If the HashiCorp Vault API returns an unexpected error.

Source code in src/zenml/zen_stores/secrets_stores/hashicorp_secrets_store.py
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
def update_secret_values(
    self,
    secret_id: UUID,
    secret_values: Dict[str, str],
) -> None:
    """Updates secret values for an existing secret.

    Args:
        secret_id: The ID of the secret to be updated.
        secret_values: The new secret values.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
        RuntimeError: If the HashiCorp Vault API returns an unexpected
            error.
    """
    vault_secret_id = self._get_vault_secret_id(secret_id)

    # Convert the ZenML secret metadata to HashiCorp Vault tags
    metadata = self._get_secret_metadata(secret_id=secret_id)

    try:
        self.client.secrets.kv.v2.create_or_update_secret(
            path=vault_secret_id,
            # Store the ZenML secret metadata alongside the secret values
            secret={
                ZENML_VAULT_SECRET_VALUES_KEY: secret_values,
                ZENML_VAULT_SECRET_METADATA_KEY: metadata,
            },
        )
    except InvalidPath:
        raise KeyError(f"Secret with ID {secret_id} does not exist.")
    except VaultError as e:
        raise RuntimeError(f"Error updating secret {secret_id}: {e}")

    logger.debug(f"Updated HashiCorp Vault secret: {vault_secret_id}")
HashiCorpVaultSecretsStoreConfiguration

Bases: SecretsStoreConfiguration

HashiCorp Vault secrets store configuration.

Attributes:

Name Type Description
type SecretsStoreType

The type of the store.

vault_addr str

The url of the Vault server. If not set, the value will be loaded from the VAULT_ADDR environment variable, if configured.

vault_token Optional[PlainSerializedSecretStr]

The token used to authenticate with the Vault server. If not set, the token will be loaded from the VAULT_TOKEN environment variable or from the ~/.vault-token file, if configured.

vault_namespace Optional[str]

The Vault Enterprise namespace.

mount_point Optional[str]

The mount point to use for all secrets.

max_versions int

The maximum number of secret versions to keep.

Functions
secrets_store_interface

ZenML secrets store interface.

Classes
SecretsStoreInterface

Bases: ABC

ZenML secrets store interface.

All ZenML secrets stores must implement the methods in this interface.

Functions
delete_secret_values(secret_id: UUID) -> None abstractmethod

Deletes secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret.

required

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

Source code in src/zenml/zen_stores/secrets_stores/secrets_store_interface.py
88
89
90
91
92
93
94
95
96
97
98
@abstractmethod
def delete_secret_values(self, secret_id: UUID) -> None:
    """Deletes secret values for an existing secret.

    Args:
        secret_id: The ID of the secret.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
    """
get_secret_values(secret_id: UUID) -> Dict[str, str] abstractmethod

Get the secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

ID of the secret.

required

Returns:

Type Description
Dict[str, str]

The secret values.

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

Source code in src/zenml/zen_stores/secrets_stores/secrets_store_interface.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
@abstractmethod
def get_secret_values(self, secret_id: UUID) -> Dict[str, str]:
    """Get the secret values for an existing secret.

    Args:
        secret_id: ID of the secret.

    Returns:
        The secret values.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
    """
store_secret_values(secret_id: UUID, secret_values: Dict[str, str]) -> None abstractmethod

Store secret values for a new secret.

Parameters:

Name Type Description Default
secret_id UUID

ID of the secret.

required
secret_values Dict[str, str]

Values for the secret.

required
Source code in src/zenml/zen_stores/secrets_stores/secrets_store_interface.py
43
44
45
46
47
48
49
50
51
52
53
54
@abstractmethod
def store_secret_values(
    self,
    secret_id: UUID,
    secret_values: Dict[str, str],
) -> None:
    """Store secret values for a new secret.

    Args:
        secret_id: ID of the secret.
        secret_values: Values for the secret.
    """
update_secret_values(secret_id: UUID, secret_values: Dict[str, str]) -> None abstractmethod

Updates secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret to be updated.

required
secret_values Dict[str, str]

The new secret values.

required

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

Source code in src/zenml/zen_stores/secrets_stores/secrets_store_interface.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
@abstractmethod
def update_secret_values(
    self,
    secret_id: UUID,
    secret_values: Dict[str, str],
) -> None:
    """Updates secret values for an existing secret.

    Args:
        secret_id: The ID of the secret to be updated.
        secret_values: The new secret values.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
    """
service_connector_secrets_store

Base secrets store class used for all secrets stores that use a service connector.

Classes
ServiceConnectorSecretsStore(zen_store: BaseZenStore, **kwargs: Any)

Bases: BaseSecretsStore

Base secrets store class for service connector-based secrets stores.

All secrets store implementations that use a Service Connector to authenticate and connect to the secrets store back-end should inherit from this class and:

  • implement the _initialize_client_from_connector method
  • use a configuration class that inherits from ServiceConnectorSecretsStoreConfiguration
  • set the SERVICE_CONNECTOR_TYPE to the service connector type used to connect to the secrets store back-end
  • set the SERVICE_CONNECTOR_RESOURCE_TYPE to the resource type used to connect to the secrets store back-end
Source code in src/zenml/zen_stores/secrets_stores/base_secrets_store.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
def __init__(
    self,
    zen_store: "BaseZenStore",
    **kwargs: Any,
) -> None:
    """Create and initialize a secrets store.

    Args:
        zen_store: The ZenML store that owns this secrets store.
        **kwargs: Additional keyword arguments to pass to the Pydantic
            constructor.

    Raises:
        RuntimeError: If the store cannot be initialized.
    """
    super().__init__(**kwargs)
    self._zen_store = zen_store

    try:
        self._initialize()
    except Exception as e:
        raise RuntimeError(
            f"Error initializing {self.type.value} secrets store: {str(e)}"
        ) from e
Attributes
client: Any property

Get the secrets store API client.

Returns:

Type Description
Any

The secrets store API client instance.

lock: Lock property

Get the lock used to treat the client initialization as a critical section.

Returns:

Type Description
Lock

The lock instance.

ServiceConnectorSecretsStoreConfiguration

Bases: SecretsStoreConfiguration

Base configuration for secrets stores that use a service connector.

Attributes:

Name Type Description
auth_method str

The service connector authentication method to use.

auth_config Dict[str, Any]

The service connector authentication configuration.

Functions
validate_auth_config(data: Dict[str, Any]) -> Dict[str, Any] classmethod

Convert the authentication configuration if given in JSON format.

Parameters:

Name Type Description Default
data Dict[str, Any]

The configuration values.

required

Returns:

Type Description
Dict[str, Any]

The validated configuration values.

Raises:

Type Description
ValueError

If the authentication configuration is not a valid JSON object.

Source code in src/zenml/zen_stores/secrets_stores/service_connector_secrets_store.py
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
@model_validator(mode="before")
@classmethod
@before_validator_handler
def validate_auth_config(cls, data: Dict[str, Any]) -> Dict[str, Any]:
    """Convert the authentication configuration if given in JSON format.

    Args:
        data: The configuration values.

    Returns:
        The validated configuration values.

    Raises:
        ValueError: If the authentication configuration is not a valid
            JSON object.
    """
    if isinstance(data.get("auth_config"), str):
        try:
            data["auth_config"] = json.loads(data["auth_config"])
        except json.JSONDecodeError as e:
            raise ValueError(
                f"The authentication configuration is not a valid JSON "
                f"object: {e}"
            )
    return data
Functions
sql_secrets_store

SQL Secrets Store implementation.

Classes
SqlSecretsStore(zen_store: BaseZenStore, **kwargs: Any)

Bases: BaseSecretsStore

Secrets store implementation that uses the SQL ZenML store as a backend.

This secrets store piggybacks on the SQL ZenML store. It uses the same database and configuration as the SQL ZenML store.

Attributes:

Name Type Description
config SqlSecretsStoreConfiguration

The configuration of the SQL secrets store.

TYPE SecretsStoreType

The type of the store.

CONFIG_TYPE Type[SecretsStoreConfiguration]

The type of the store configuration.

Create and initialize the SQL secrets store.

Parameters:

Name Type Description Default
zen_store BaseZenStore

The ZenML store that owns this SQL secrets store.

required
**kwargs Any

Additional keyword arguments to pass to the Pydantic constructor.

{}

Raises:

Type Description
IllegalOperationError

If the ZenML store to which this secrets store belongs is not a SQL ZenML store.

Source code in src/zenml/zen_stores/secrets_stores/sql_secrets_store.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def __init__(
    self,
    zen_store: "BaseZenStore",
    **kwargs: Any,
) -> None:
    """Create and initialize the SQL secrets store.

    Args:
        zen_store: The ZenML store that owns this SQL secrets store.
        **kwargs: Additional keyword arguments to pass to the Pydantic
            constructor.

    Raises:
        IllegalOperationError: If the ZenML store to which this secrets
            store belongs is not a SQL ZenML store.
    """
    from zenml.zen_stores.sql_zen_store import SqlZenStore

    if not isinstance(zen_store, SqlZenStore):
        raise IllegalOperationError(
            "The SQL secrets store can only be used with the SQL ZenML "
            "store."
        )
    super().__init__(zen_store, **kwargs)
Attributes
engine: Engine property

The SQLAlchemy engine.

Returns:

Type Description
Engine

The SQLAlchemy engine.

zen_store: SqlZenStore property

The ZenML store that this SQL secrets store is using as a back-end.

Returns:

Type Description
SqlZenStore

The ZenML store that this SQL secrets store is using as a back-end.

Raises:

Type Description
ValueError

If the store is not initialized.

Functions
delete_secret_values(secret_id: UUID) -> None

Deletes secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret.

required

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

Source code in src/zenml/zen_stores/secrets_stores/sql_secrets_store.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
def delete_secret_values(self, secret_id: UUID) -> None:
    """Deletes secret values for an existing secret.

    Args:
        secret_id: The ID of the secret.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
    """
    with Session(self.engine) as session:
        try:
            secret_in_db = session.exec(
                select(SecretSchema).where(SecretSchema.id == secret_id)
            ).one()
            secret_in_db.values = None
            session.commit()
        except NoResultFound:
            raise KeyError(f"Secret with ID {secret_id} not found.")
get_secret_values(secret_id: UUID) -> Dict[str, str]

Get the secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

ID of the secret.

required

Returns:

Type Description
Dict[str, str]

The secret values.

Raises:

Type Description
KeyError

if no secret values for the given ID are stored in the secrets store.

Source code in src/zenml/zen_stores/secrets_stores/sql_secrets_store.py
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
def get_secret_values(self, secret_id: UUID) -> Dict[str, str]:
    """Get the secret values for an existing secret.

    Args:
        secret_id: ID of the secret.

    Returns:
        The secret values.

    Raises:
        KeyError: if no secret values for the given ID are stored in the
            secrets store.
    """
    with Session(self.engine) as session:
        secret_in_db = session.exec(
            select(SecretSchema).where(SecretSchema.id == secret_id)
        ).first()
        if secret_in_db is None:
            raise KeyError(f"Secret with ID {secret_id} not found.")
        try:
            return secret_in_db.get_secret_values(
                encryption_engine=self._encryption_engine,
            )
        except SecretDecodeError:
            raise KeyError(
                f"Secret values for secret {secret_id} could not be "
                f"decoded. This can happen if encryption has "
                f"been enabled/disabled or if the encryption key has been "
                "reconfigured without proper secrets migration."
            )
store_secret_values(secret_id: UUID, secret_values: Dict[str, str]) -> None

Store secret values for a new secret.

The secret is already created in the database by the SQL Zen store, this method only stores the secret values.

Parameters:

Name Type Description Default
secret_id UUID

ID of the secret.

required
secret_values Dict[str, str]

Values for the secret.

required

Raises:

Type Description
KeyError

if a secret for the given ID is not found.

Source code in src/zenml/zen_stores/secrets_stores/sql_secrets_store.py
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
def store_secret_values(
    self,
    secret_id: UUID,
    secret_values: Dict[str, str],
) -> None:
    """Store secret values for a new secret.

    The secret is already created in the database by the SQL Zen store, this
    method only stores the secret values.

    Args:
        secret_id: ID of the secret.
        secret_values: Values for the secret.

    Raises:
        KeyError: if a secret for the given ID is not found.
    """
    with Session(self.engine) as session:
        secret_in_db = session.exec(
            select(SecretSchema).where(SecretSchema.id == secret_id)
        ).first()
        if secret_in_db is None:
            raise KeyError(f"Secret with ID {secret_id} not found.")
        secret_in_db.set_secret_values(
            secret_values=secret_values,
            encryption_engine=self._encryption_engine,
        )
        session.add(secret_in_db)
        session.commit()
update_secret_values(secret_id: UUID, secret_values: Dict[str, str]) -> None

Updates secret values for an existing secret.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret to be updated.

required
secret_values Dict[str, str]

The new secret values.

required
Source code in src/zenml/zen_stores/secrets_stores/sql_secrets_store.py
235
236
237
238
239
240
241
242
243
244
245
246
def update_secret_values(
    self,
    secret_id: UUID,
    secret_values: Dict[str, str],
) -> None:
    """Updates secret values for an existing secret.

    Args:
        secret_id: The ID of the secret to be updated.
        secret_values: The new secret values.
    """
    self.store_secret_values(secret_id, secret_values)
SqlSecretsStoreConfiguration

Bases: SecretsStoreConfiguration

SQL secrets store configuration.

Attributes:

Name Type Description
type SecretsStoreType

The type of the store.

encryption_key Optional[PlainSerializedSecretStr]

The encryption key to use for the SQL secrets store. If not set, the passwords will not be encrypted in the database.

Functions

sql_zen_store

SQL Zen Store implementation.

Classes
SQLDatabaseDriver

Bases: StrEnum

SQL database drivers supported by the SQL ZenML store.

SqlZenStore(skip_default_registrations: bool = False, **kwargs: Any)

Bases: BaseZenStore

Store Implementation that uses SQL database backend.

Attributes:

Name Type Description
config SqlZenStoreConfiguration

The configuration of the SQL ZenML store.

skip_migrations bool

Whether to skip migrations when initializing the store.

TYPE StoreType

The type of the store.

CONFIG_TYPE Type[StoreConfiguration]

The type of the store configuration.

_engine Optional[Engine]

The SQLAlchemy engine.

Source code in src/zenml/zen_stores/base_zen_store.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def __init__(
    self,
    skip_default_registrations: bool = False,
    **kwargs: Any,
) -> None:
    """Create and initialize a store.

    Args:
        skip_default_registrations: If `True`, the creation of the default
            stack and user in the store will be skipped.
        **kwargs: Additional keyword arguments to pass to the Pydantic
            constructor.
    """
    super().__init__(**kwargs)

    self._initialize()

    if not skip_default_registrations:
        logger.debug("Initializing database")
        self._initialize_database()
    else:
        logger.debug("Skipping database initialization")
Attributes
alembic: Alembic property

The Alembic wrapper.

Returns:

Type Description
Alembic

The Alembic wrapper.

Raises:

Type Description
ValueError

If the store is not initialized.

backup_secrets_store: Optional[BaseSecretsStore] property

The backup secrets store associated with this store.

Returns:

Type Description
Optional[BaseSecretsStore]

The backup secrets store associated with this store.

engine: Engine property

The SQLAlchemy engine.

Returns:

Type Description
Engine

The SQLAlchemy engine.

Raises:

Type Description
ValueError

If the store is not initialized.

migration_utils: MigrationUtils property

The migration utils.

Returns:

Type Description
MigrationUtils

The migration utils.

Raises:

Type Description
ValueError

If the store is not initialized.

secrets_store: BaseSecretsStore property

The secrets store associated with this store.

Returns:

Type Description
BaseSecretsStore

The secrets store associated with this store.

Raises:

Type Description
SecretsStoreNotConfiguredError

If no secrets store is configured.

Functions
activate_server(request: ServerActivationRequest) -> Optional[UserResponse]

Activate the server and optionally create the default admin user.

Parameters:

Name Type Description Default
request ServerActivationRequest

The server activation request.

required

Returns:

Type Description
Optional[UserResponse]

The default admin user that was created, if any.

Raises:

Type Description
IllegalOperationError

If the server is already active.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def activate_server(
    self, request: ServerActivationRequest
) -> Optional[UserResponse]:
    """Activate the server and optionally create the default admin user.

    Args:
        request: The server activation request.

    Returns:
        The default admin user that was created, if any.

    Raises:
        IllegalOperationError: If the server is already active.
    """
    with Session(self.engine) as session:
        settings = self._get_server_settings(session=session)

        if settings.active:
            # The server can only be activated once
            raise IllegalOperationError("The server is already active.")

        settings.update(request)
        settings.active = True
        session.add(settings)
        session.commit()

    # Update the server settings to reflect the activation
    self.update_server_settings(request)

    if request.admin_username and request.admin_password is not None:
        # Create the default admin user
        return self.create_user(
            UserRequest(
                name=request.admin_username,
                active=True,
                password=request.admin_password,
                is_admin=True,
            )
        )

    return None
backup_database(strategy: Optional[DatabaseBackupStrategy] = None, location: Optional[str] = None, overwrite: bool = False) -> Tuple[str, Any]

Backup the database.

Parameters:

Name Type Description Default
strategy Optional[DatabaseBackupStrategy]

Custom backup strategy to use. If not set, the backup strategy from the store configuration will be used.

None
location Optional[str]

Custom target location to backup the database to. If not set, the configured backup location will be used. Depending on the backup strategy, this can be a file path or a database name.

None
overwrite bool

Whether to overwrite an existing backup if it exists. If set to False, the existing backup will be reused.

False

Returns:

Type Description
str

The location where the database was backed up to and an accompanying

Any

user-friendly message that describes the backup location, or None

Tuple[str, Any]

if no backup was created (i.e. because the backup already exists).

Raises:

Type Description
ValueError

If the backup database name is not set when the backup database is requested or if the backup strategy is invalid.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def backup_database(
    self,
    strategy: Optional[DatabaseBackupStrategy] = None,
    location: Optional[str] = None,
    overwrite: bool = False,
) -> Tuple[str, Any]:
    """Backup the database.

    Args:
        strategy: Custom backup strategy to use. If not set, the backup
            strategy from the store configuration will be used.
        location: Custom target location to backup the database to. If not
            set, the configured backup location will be used. Depending on
            the backup strategy, this can be a file path or a database name.
        overwrite: Whether to overwrite an existing backup if it exists.
            If set to False, the existing backup will be reused.

    Returns:
        The location where the database was backed up to and an accompanying
        user-friendly message that describes the backup location, or None
        if no backup was created (i.e. because the backup already exists).

    Raises:
        ValueError: If the backup database name is not set when the backup
            database is requested or if the backup strategy is invalid.
    """
    strategy = strategy or self.config.backup_strategy

    if (
        strategy == DatabaseBackupStrategy.DUMP_FILE
        or self.config.driver == SQLDatabaseDriver.SQLITE
    ):
        dump_file = location or self._get_db_backup_file_path()

        if not overwrite and os.path.isfile(dump_file):
            logger.warning(
                f"A previous backup file already exists at '{dump_file}'. "
                "Reusing the existing backup."
            )
        else:
            self.migration_utils.backup_database_to_file(
                dump_file=dump_file
            )
        return f"the '{dump_file}' backup file", dump_file
    elif strategy == DatabaseBackupStrategy.DATABASE:
        backup_db_name = location or self.config.backup_database
        if not backup_db_name:
            raise ValueError(
                "The backup database name must be set in the store "
                "configuration to use the backup database strategy."
            )

        if not overwrite and self.migration_utils.database_exists(
            backup_db_name
        ):
            logger.warning(
                "A previous backup database already exists at "
                f"'{backup_db_name}'. Reusing the existing backup."
            )
        else:
            self.migration_utils.backup_database_to_db(
                backup_db_name=backup_db_name
            )
        return f"the '{backup_db_name}' backup database", backup_db_name
    elif strategy == DatabaseBackupStrategy.IN_MEMORY:
        return (
            "memory",
            self.migration_utils.backup_database_to_memory(),
        )

    else:
        raise ValueError(f"Invalid backup strategy: {strategy}.")
backup_secrets(ignore_errors: bool = True, delete_secrets: bool = False) -> None

Backs up all secrets to the configured backup secrets store.

Parameters:

Name Type Description Default
ignore_errors bool

Whether to ignore individual errors during the backup process and attempt to backup all secrets.

True
delete_secrets bool

Whether to delete the secrets that have been successfully backed up from the primary secrets store. Setting this flag effectively moves all secrets from the primary secrets store to the backup secrets store.

False
noqa: DAR401

Raises: BackupSecretsStoreNotConfiguredError: if no backup secrets store is configured.

Source code in src/zenml/zen_stores/sql_zen_store.py
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
def backup_secrets(
    self, ignore_errors: bool = True, delete_secrets: bool = False
) -> None:
    """Backs up all secrets to the configured backup secrets store.

    Args:
        ignore_errors: Whether to ignore individual errors during the backup
            process and attempt to backup all secrets.
        delete_secrets: Whether to delete the secrets that have been
            successfully backed up from the primary secrets store. Setting
            this flag effectively moves all secrets from the primary secrets
            store to the backup secrets store.

    # noqa: DAR401
    Raises:
        BackupSecretsStoreNotConfiguredError: if no backup secrets store is
            configured.
    """
    if not self.backup_secrets_store:
        raise BackupSecretsStoreNotConfiguredError(
            "Unable to backup secrets: No backup secrets store is "
            "configured."
        )

    with Session(self.engine) as session:
        secrets_in_db = session.exec(select(SecretSchema)).all()

    for secret in secrets_in_db:
        try:
            values = self._get_secret_values(
                secret_id=secret.id, use_backup=False
            )
        except Exception:
            logger.exception(
                f"Failed to get secret values for secret with ID "
                f"{secret.id}."
            )
            if ignore_errors:
                continue
            raise

        try:
            self._backup_secret_values(secret_id=secret.id, values=values)
        except Exception:
            logger.exception(
                f"Failed to backup secret with ID {secret.id}. "
            )
            if ignore_errors:
                continue
            raise

        if delete_secrets:
            try:
                self._delete_secret_values(
                    secret_id=secret.id, delete_backup=False
                )
            except Exception:
                logger.exception(
                    f"Failed to delete secret with ID {secret.id} from the "
                    f"primary secrets store after backing it up to the "
                    f"backup secrets store."
                )
                if ignore_errors:
                    continue
                raise
batch_create_artifact_versions(artifact_versions: List[ArtifactVersionRequest]) -> List[ArtifactVersionResponse]

Creates a batch of artifact versions.

Parameters:

Name Type Description Default
artifact_versions List[ArtifactVersionRequest]

The artifact versions to create.

required

Returns:

Type Description
List[ArtifactVersionResponse]

The created artifact versions.

Source code in src/zenml/zen_stores/sql_zen_store.py
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
def batch_create_artifact_versions(
    self, artifact_versions: List[ArtifactVersionRequest]
) -> List[ArtifactVersionResponse]:
    """Creates a batch of artifact versions.

    Args:
        artifact_versions: The artifact versions to create.

    Returns:
        The created artifact versions.
    """
    return [
        self.create_artifact_version(artifact_version)
        for artifact_version in artifact_versions
    ]
batch_create_tag_resource(tag_resources: List[TagResourceRequest]) -> List[TagResourceResponse]

Create a batch of tag resource relationships.

Parameters:

Name Type Description Default
tag_resources List[TagResourceRequest]

The tag resource relationships to be created.

required

Returns:

Type Description
List[TagResourceResponse]

The newly created tag resource relationships.

Source code in src/zenml/zen_stores/sql_zen_store.py
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
def batch_create_tag_resource(
    self, tag_resources: List[TagResourceRequest]
) -> List[TagResourceResponse]:
    """Create a batch of tag resource relationships.

    Args:
        tag_resources: The tag resource relationships to be created.

    Returns:
        The newly created tag resource relationships.
    """
    with Session(self.engine) as session:
        resources: List[
            Tuple[TagSchema, TaggableResourceTypes, BaseSchema]
        ] = []
        for tag_resource in tag_resources:
            resource_schema = self._get_schema_from_resource_type(
                tag_resource.resource_type
            )
            resource = self._get_schema_by_id(
                resource_id=tag_resource.resource_id,
                schema_class=resource_schema,
                session=session,
            )
            tag_schema = self._get_tag_schema(
                tag_name_or_id=tag_resource.tag_id,
                session=session,
            )
            resources.append(
                (
                    tag_schema,
                    tag_resource.resource_type,
                    resource,
                )
            )
        return [
            r.to_model()
            for r in self._create_tag_resource_schemas(
                tag_resources=resources, session=session
            )
        ]
batch_delete_tag_resource(tag_resources: List[TagResourceRequest]) -> None

Delete a batch of tag resource relationships.

Parameters:

Name Type Description Default
tag_resources List[TagResourceRequest]

The tag resource relationships to be deleted.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
def batch_delete_tag_resource(
    self, tag_resources: List[TagResourceRequest]
) -> None:
    """Delete a batch of tag resource relationships.

    Args:
        tag_resources: The tag resource relationships to be deleted.
    """
    with Session(self.engine) as session:
        self._delete_tag_resource_schemas(
            tag_resources=tag_resources,
            session=session,
        )
cleanup_database_backup(strategy: Optional[DatabaseBackupStrategy] = None, location: Optional[Any] = None) -> None

Delete the database backup.

Parameters:

Name Type Description Default
strategy Optional[DatabaseBackupStrategy]

Custom backup strategy to use. If not set, the backup strategy from the store configuration will be used.

None
location Optional[Any]

Custom target location to delete the database backup from. If not set, the configured backup location will be used. Depending on the backup strategy, this can be a file path or a database name.

None

Raises:

Type Description
ValueError

If the backup database name is not set when the backup database is requested.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def cleanup_database_backup(
    self,
    strategy: Optional[DatabaseBackupStrategy] = None,
    location: Optional[Any] = None,
) -> None:
    """Delete the database backup.

    Args:
        strategy: Custom backup strategy to use. If not set, the backup
            strategy from the store configuration will be used.
        location: Custom target location to delete the database backup
            from. If not set, the configured backup location will be used.
            Depending on the backup strategy, this can be a file path or a
            database name.

    Raises:
        ValueError: If the backup database name is not set when the backup
            database is requested.
    """
    strategy = strategy or self.config.backup_strategy

    if (
        strategy == DatabaseBackupStrategy.DUMP_FILE
        or self.config.driver == SQLDatabaseDriver.SQLITE
    ):
        dump_file = location or self._get_db_backup_file_path()
        if dump_file is not None and os.path.isfile(dump_file):
            try:
                os.remove(dump_file)
            except OSError:
                logger.warning(
                    f"Failed to cleanup database dump file {dump_file}."
                )
            else:
                logger.info(
                    f"Successfully cleaned up database dump file "
                    f"{dump_file}."
                )
    elif strategy == DatabaseBackupStrategy.DATABASE:
        backup_db_name = location or self.config.backup_database

        if not backup_db_name:
            raise ValueError(
                "The backup database name must be set in the store "
                "configuration to use the backup database strategy."
            )
        if self.migration_utils.database_exists(backup_db_name):
            # Drop the backup database
            self.migration_utils.drop_database(
                database=backup_db_name,
            )
            logger.info(
                f"Successfully cleaned up backup database "
                f"{backup_db_name}."
            )
count_pipelines(filter_model: PipelineFilter) -> int

Count all pipelines.

Parameters:

Name Type Description Default
filter_model PipelineFilter

The filter model to use for counting pipelines.

required

Returns:

Type Description
int

The number of pipelines.

Source code in src/zenml/zen_stores/sql_zen_store.py
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
def count_pipelines(self, filter_model: PipelineFilter) -> int:
    """Count all pipelines.

    Args:
        filter_model: The filter model to use for counting pipelines.

    Returns:
        The number of pipelines.
    """
    return self._count_entity(
        schema=PipelineSchema, filter_model=filter_model
    )
count_projects(filter_model: Optional[ProjectFilter] = None) -> int

Count all projects.

Parameters:

Name Type Description Default
filter_model Optional[ProjectFilter]

The filter model to use for counting projects.

None

Returns:

Type Description
int

The number of projects.

Source code in src/zenml/zen_stores/sql_zen_store.py
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
def count_projects(
    self, filter_model: Optional[ProjectFilter] = None
) -> int:
    """Count all projects.

    Args:
        filter_model: The filter model to use for counting projects.

    Returns:
        The number of projects.
    """
    return self._count_entity(
        schema=ProjectSchema, filter_model=filter_model
    )
count_runs(filter_model: PipelineRunFilter) -> int

Count all pipeline runs.

Parameters:

Name Type Description Default
filter_model PipelineRunFilter

The filter model to filter the runs.

required

Returns:

Type Description
int

The number of pipeline runs.

Source code in src/zenml/zen_stores/sql_zen_store.py
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
def count_runs(self, filter_model: PipelineRunFilter) -> int:
    """Count all pipeline runs.

    Args:
        filter_model: The filter model to filter the runs.

    Returns:
        The number of pipeline runs.
    """
    return self._count_entity(
        schema=PipelineRunSchema, filter_model=filter_model
    )
count_stack_components(filter_model: Optional[ComponentFilter] = None) -> int

Count all components.

Parameters:

Name Type Description Default
filter_model Optional[ComponentFilter]

The filter model to use for counting components.

None

Returns:

Type Description
int

The number of components.

Source code in src/zenml/zen_stores/sql_zen_store.py
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
def count_stack_components(
    self, filter_model: Optional[ComponentFilter] = None
) -> int:
    """Count all components.

    Args:
        filter_model: The filter model to use for counting components.

    Returns:
        The number of components.
    """
    return self._count_entity(
        schema=StackComponentSchema, filter_model=filter_model
    )
count_stacks(filter_model: Optional[StackFilter]) -> int

Count all stacks.

Parameters:

Name Type Description Default
filter_model Optional[StackFilter]

The filter model to filter the stacks.

required

Returns:

Type Description
int

The number of stacks.

Source code in src/zenml/zen_stores/sql_zen_store.py
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
def count_stacks(self, filter_model: Optional[StackFilter]) -> int:
    """Count all stacks.

    Args:
        filter_model: The filter model to filter the stacks.

    Returns:
        The number of stacks.
    """
    return self._count_entity(
        schema=StackSchema, filter_model=filter_model
    )
create_action(action: ActionRequest) -> ActionResponse

Create an action.

Parameters:

Name Type Description Default
action ActionRequest

The action to create.

required

Returns:

Type Description
ActionResponse

The created action.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def create_action(self, action: ActionRequest) -> ActionResponse:
    """Create an action.

    Args:
        action: The action to create.

    Returns:
        The created action.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(request_model=action, session=session)

        self._verify_name_uniqueness(
            resource=action,
            schema=ActionSchema,
            session=session,
        )

        # Verify that the given service account exists
        self._get_account_schema(
            account_name_or_id=action.service_account_id,
            session=session,
            service_account=True,
        )

        new_action = ActionSchema.from_request(action)
        session.add(new_action)
        session.commit()
        session.refresh(new_action)

        return new_action.to_model(
            include_metadata=True, include_resources=True
        )
create_api_key(service_account_id: UUID, api_key: APIKeyRequest) -> APIKeyResponse

Create a new API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to create the API key.

required
api_key APIKeyRequest

The API key to create.

required

Returns:

Type Description
APIKeyResponse

The created API key.

Raises:

Type Description
EntityExistsError

If an API key with the same name is already configured for the same service account.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def create_api_key(
    self, service_account_id: UUID, api_key: APIKeyRequest
) -> APIKeyResponse:
    """Create a new API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to
            create the API key.
        api_key: The API key to create.

    Returns:
        The created API key.

    Raises:
        EntityExistsError: If an API key with the same name is already
            configured for the same service account.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(request_model=api_key, session=session)

        # Fetch the service account
        service_account = self._get_account_schema(
            service_account_id, session=session, service_account=True
        )

        # Check if a key with the same name already exists for the same
        # service account
        try:
            self._get_api_key(
                service_account_id=service_account.id,
                api_key_name_or_id=api_key.name,
                session=session,
            )
            raise EntityExistsError(
                f"Unable to register API key with name '{api_key.name}': "
                "Found an existing API key with the same name configured "
                f"for the same '{service_account.name}' service account."
            )
        except KeyError:
            pass

        new_api_key, key_value = APIKeySchema.from_request(
            service_account_id=service_account.id,
            request=api_key,
        )
        session.add(new_api_key)
        session.commit()

        api_key_model = new_api_key.to_model(
            include_metadata=True, include_resources=True
        )
        api_key_model.set_key(key_value)
        return api_key_model
create_artifact(artifact: ArtifactRequest) -> ArtifactResponse

Creates a new artifact.

Parameters:

Name Type Description Default
artifact ArtifactRequest

The artifact to create.

required

Returns:

Type Description
ArtifactResponse

The newly created artifact.

Source code in src/zenml/zen_stores/sql_zen_store.py
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
def create_artifact(self, artifact: ArtifactRequest) -> ArtifactResponse:
    """Creates a new artifact.

    Args:
        artifact: The artifact to create.

    Returns:
        The newly created artifact.
    """
    validate_name(artifact)
    with Session(self.engine) as session:
        self._set_request_user_id(request_model=artifact, session=session)

        # Check if an artifact with the given name already exists
        self._verify_name_uniqueness(
            resource=artifact,
            schema=ArtifactSchema,
            session=session,
        )

        # Create the artifact.
        artifact_schema = ArtifactSchema.from_request(artifact)

        session.add(artifact_schema)
        session.commit()

        # Save tags of the artifact.
        self._attach_tags_to_resources(
            tags=artifact.tags,
            resources=artifact_schema,
            session=session,
        )
        session.refresh(artifact_schema)

        return artifact_schema.to_model(
            include_metadata=True, include_resources=True
        )
create_artifact_version(artifact_version: ArtifactVersionRequest) -> ArtifactVersionResponse

Create an artifact version.

Parameters:

Name Type Description Default
artifact_version ArtifactVersionRequest

The artifact version to create.

required

Raises:

Type Description
EntityExistsError

If an artifact version with the same name already exists.

EntityCreationError

If the artifact version creation failed.

Returns:

Type Description
ArtifactVersionResponse

The created artifact version.

Source code in src/zenml/zen_stores/sql_zen_store.py
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
def create_artifact_version(
    self, artifact_version: ArtifactVersionRequest
) -> ArtifactVersionResponse:
    """Create an artifact version.

    Args:
        artifact_version: The artifact version to create.

    Raises:
        EntityExistsError: If an artifact version with the same name
            already exists.
        EntityCreationError: If the artifact version creation failed.

    Returns:
        The created artifact version.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(
            request_model=artifact_version, session=session
        )

        self._get_reference_schema_by_id(
            resource=artifact_version,
            reference_schema=StackComponentSchema,
            reference_id=artifact_version.artifact_store_id,
            session=session,
            reference_type="artifact store",
        )

        if artifact_name := artifact_version.artifact_name:
            artifact_schema = self._get_or_create_artifact_for_name(
                name=artifact_name,
                project_id=artifact_version.project,
                has_custom_name=artifact_version.has_custom_name,
                session=session,
            )
            artifact_version.artifact_id = artifact_schema.id

        assert artifact_version.artifact_id

        artifact_version_schema: Optional[ArtifactVersionSchema] = None

        if artifact_version.version is None:
            # No explicit version in the request -> We will try to
            # auto-increment the numeric version of the artifact version
            remaining_tries = MAX_RETRIES_FOR_VERSIONED_ENTITY_CREATION
            while remaining_tries > 0:
                remaining_tries -= 1
                try:
                    artifact_version.version = str(
                        self._get_next_numeric_version_for_artifact(
                            session=session,
                            artifact_id=artifact_version.artifact_id,
                        )
                    )

                    artifact_version_schema = (
                        ArtifactVersionSchema.from_request(
                            artifact_version
                        )
                    )
                    session.add(artifact_version_schema)
                    session.commit()
                except IntegrityError:
                    # We have to rollback the failed session first in order
                    # to continue using it
                    session.rollback()
                    if remaining_tries == 0:
                        raise EntityCreationError(
                            f"Failed to create version for artifact "
                            f"{artifact_schema.name}. This is most likely "
                            "caused by multiple parallel requests that try "
                            "to create versions for this artifact in the "
                            "database."
                        )
                    else:
                        attempt = (
                            MAX_RETRIES_FOR_VERSIONED_ENTITY_CREATION
                            - remaining_tries
                        )
                        sleep_duration = exponential_backoff_with_jitter(
                            attempt=attempt
                        )

                        logger.debug(
                            "Failed to create artifact version %s "
                            "(version %s) due to an integrity error. "
                            "Retrying in %f seconds.",
                            artifact_schema.name,
                            artifact_version.version,
                            sleep_duration,
                        )
                        time.sleep(sleep_duration)
                else:
                    break
        else:
            # An explicit version was specified for the artifact version.
            # We don't do any incrementing and fail immediately if the
            # version already exists.
            try:
                artifact_version_schema = (
                    ArtifactVersionSchema.from_request(artifact_version)
                )
                session.add(artifact_version_schema)
                session.commit()
            except IntegrityError:
                # We have to rollback the failed session first in order
                # to continue using it
                session.rollback()
                raise EntityExistsError(
                    f"Unable to create artifact version "
                    f"{artifact_schema.name} (version "
                    f"{artifact_version.version}): An artifact with the "
                    "same name and version already exists."
                )

        assert artifact_version_schema is not None

        # Save visualizations of the artifact
        if artifact_version.visualizations:
            for vis in artifact_version.visualizations:
                vis_schema = ArtifactVisualizationSchema.from_model(
                    artifact_visualization_request=vis,
                    artifact_version_id=artifact_version_schema.id,
                )
                session.add(vis_schema)

        # Save tags of the artifact
        self._attach_tags_to_resources(
            tags=artifact_version.tags,
            resources=artifact_version_schema,
            session=session,
        )

        # Save metadata of the artifact
        if artifact_version.metadata:
            values: Dict[str, "MetadataType"] = {}
            types: Dict[str, "MetadataTypeEnum"] = {}
            for key, value in artifact_version.metadata.items():
                # Skip metadata that is too large to be stored in the DB.
                if len(json.dumps(value)) > TEXT_FIELD_MAX_LENGTH:
                    logger.warning(
                        f"Metadata value for key '{key}' is too large to be "
                        "stored in the database. Skipping."
                    )
                    continue
                # Skip metadata that is not of a supported type.
                try:
                    metadata_type = get_metadata_type(value)
                except ValueError as e:
                    logger.warning(
                        f"Metadata value for key '{key}' is not of a "
                        f"supported type. Skipping. Full error: {e}"
                    )
                    continue
                values[key] = value
                types[key] = metadata_type
            self.create_run_metadata(
                RunMetadataRequest(
                    project=artifact_version.project,
                    resources=[
                        RunMetadataResource(
                            id=artifact_version_schema.id,
                            type=MetadataResourceTypes.ARTIFACT_VERSION,
                        )
                    ],
                    values=values,
                    types=types,
                )
            )

        session.commit()
        session.refresh(artifact_version_schema)

        return artifact_version_schema.to_model(
            include_metadata=True, include_resources=True
        )
create_authorized_device(device: OAuthDeviceInternalRequest) -> OAuthDeviceInternalResponse

Creates a new OAuth 2.0 authorized device.

Parameters:

Name Type Description Default
device OAuthDeviceInternalRequest

The device to be created.

required

Returns:

Type Description
OAuthDeviceInternalResponse

The newly created device.

Raises:

Type Description
EntityExistsError

If a device for the same client ID already exists.

Source code in src/zenml/zen_stores/sql_zen_store.py
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
def create_authorized_device(
    self, device: OAuthDeviceInternalRequest
) -> OAuthDeviceInternalResponse:
    """Creates a new OAuth 2.0 authorized device.

    Args:
        device: The device to be created.

    Returns:
        The newly created device.

    Raises:
        EntityExistsError: If a device for the same client ID already
            exists.
    """
    with Session(self.engine) as session:
        existing_device = session.exec(
            select(OAuthDeviceSchema).where(
                # We search for a device with the same client ID
                # because the client ID is the one that is used to
                # identify the device
                OAuthDeviceSchema.client_id == device.client_id
            )
        ).first()
        if existing_device is not None:
            raise EntityExistsError(
                f"Unable to create device with client ID "
                f"'{device.client_id}': A device with this client ID "
                "already exists."
            )

        (
            new_device,
            user_code,
            device_code,
        ) = OAuthDeviceSchema.from_request(device)
        session.add(new_device)
        session.commit()
        session.refresh(new_device)

        device_model = new_device.to_internal_model(
            include_metadata=True, include_resources=True
        )
        # Replace the hashed user code with the original user code
        device_model.user_code = user_code
        # Replace the hashed device code with the original device code
        device_model.device_code = device_code

        return device_model
create_build(build: PipelineBuildRequest) -> PipelineBuildResponse

Creates a new build.

Parameters:

Name Type Description Default
build PipelineBuildRequest

The build to create.

required

Returns:

Type Description
PipelineBuildResponse

The newly created build.

Source code in src/zenml/zen_stores/sql_zen_store.py
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
def create_build(
    self,
    build: PipelineBuildRequest,
) -> PipelineBuildResponse:
    """Creates a new build.

    Args:
        build: The build to create.

    Returns:
        The newly created build.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(request_model=build, session=session)
        self._get_reference_schema_by_id(
            resource=build,
            reference_schema=StackSchema,
            reference_id=build.stack,
            session=session,
        )

        self._get_reference_schema_by_id(
            resource=build,
            reference_schema=PipelineSchema,
            reference_id=build.pipeline,
            session=session,
        )

        new_build = PipelineBuildSchema.from_request(build)
        session.add(new_build)
        session.commit()
        session.refresh(new_build)

        return new_build.to_model(
            include_metadata=True, include_resources=True
        )
create_code_repository(code_repository: CodeRepositoryRequest) -> CodeRepositoryResponse

Creates a new code repository.

Parameters:

Name Type Description Default
code_repository CodeRepositoryRequest

Code repository to be created.

required

Returns:

Type Description
CodeRepositoryResponse

The newly created code repository.

Source code in src/zenml/zen_stores/sql_zen_store.py
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
@track_decorator(AnalyticsEvent.REGISTERED_CODE_REPOSITORY)
def create_code_repository(
    self, code_repository: CodeRepositoryRequest
) -> CodeRepositoryResponse:
    """Creates a new code repository.

    Args:
        code_repository: Code repository to be created.

    Returns:
        The newly created code repository.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(
            request_model=code_repository, session=session
        )

        self._verify_name_uniqueness(
            resource=code_repository,
            schema=CodeRepositorySchema,
            session=session,
        )

        new_repo = CodeRepositorySchema.from_request(code_repository)
        session.add(new_repo)
        session.commit()
        session.refresh(new_repo)

        return new_repo.to_model(
            include_metadata=True, include_resources=True
        )
create_deployment(deployment: PipelineDeploymentRequest) -> PipelineDeploymentResponse

Creates a new deployment.

Parameters:

Name Type Description Default
deployment PipelineDeploymentRequest

The deployment to create.

required

Returns:

Type Description
PipelineDeploymentResponse

The newly created deployment.

Source code in src/zenml/zen_stores/sql_zen_store.py
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
def create_deployment(
    self,
    deployment: PipelineDeploymentRequest,
) -> PipelineDeploymentResponse:
    """Creates a new deployment.

    Args:
        deployment: The deployment to create.

    Returns:
        The newly created deployment.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(
            request_model=deployment, session=session
        )
        self._get_reference_schema_by_id(
            resource=deployment,
            reference_schema=StackSchema,
            reference_id=deployment.stack,
            session=session,
        )

        self._get_reference_schema_by_id(
            resource=deployment,
            reference_schema=PipelineSchema,
            reference_id=deployment.pipeline,
            session=session,
        )

        self._get_reference_schema_by_id(
            resource=deployment,
            reference_schema=PipelineBuildSchema,
            reference_id=deployment.build,
            session=session,
        )

        self._get_reference_schema_by_id(
            resource=deployment,
            reference_schema=ScheduleSchema,
            reference_id=deployment.schedule,
            session=session,
        )

        if deployment.code_reference:
            self._get_reference_schema_by_id(
                resource=deployment,
                reference_schema=CodeRepositorySchema,
                reference_id=deployment.code_reference.code_repository,
                session=session,
            )

        self._get_reference_schema_by_id(
            resource=deployment,
            reference_schema=RunTemplateSchema,
            reference_id=deployment.template,
            session=session,
        )

        code_reference_id = self._create_or_reuse_code_reference(
            session=session,
            project_id=deployment.project,
            code_reference=deployment.code_reference,
        )

        new_deployment = PipelineDeploymentSchema.from_request(
            deployment, code_reference_id=code_reference_id
        )
        session.add(new_deployment)
        session.commit()
        session.refresh(new_deployment)

        return new_deployment.to_model(
            include_metadata=True, include_resources=True
        )
create_event_source(event_source: EventSourceRequest) -> EventSourceResponse

Create an event_source.

Parameters:

Name Type Description Default
event_source EventSourceRequest

The event_source to create.

required

Returns:

Type Description
EventSourceResponse

The created event_source.

Source code in src/zenml/zen_stores/sql_zen_store.py
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
def create_event_source(
    self, event_source: EventSourceRequest
) -> EventSourceResponse:
    """Create an event_source.

    Args:
        event_source: The event_source to create.

    Returns:
        The created event_source.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(
            request_model=event_source, session=session
        )

        self._verify_name_uniqueness(
            resource=event_source,
            schema=EventSourceSchema,
            session=session,
        )

        new_event_source = EventSourceSchema.from_request(event_source)
        session.add(new_event_source)
        session.commit()
        session.refresh(new_event_source)

        return new_event_source.to_model(
            include_metadata=True, include_resources=True
        )
create_flavor(flavor: FlavorRequest) -> FlavorResponse

Creates a new stack component flavor.

Parameters:

Name Type Description Default
flavor FlavorRequest

The stack component flavor to create.

required

Returns:

Type Description
FlavorResponse

The newly created flavor.

Raises:

Type Description
EntityExistsError

If a flavor with the same name and type is already owned by this user.

ValueError

In case the config_schema string exceeds the max length.

Source code in src/zenml/zen_stores/sql_zen_store.py
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
@track_decorator(AnalyticsEvent.CREATED_FLAVOR)
def create_flavor(self, flavor: FlavorRequest) -> FlavorResponse:
    """Creates a new stack component flavor.

    Args:
        flavor: The stack component flavor to create.

    Returns:
        The newly created flavor.

    Raises:
        EntityExistsError: If a flavor with the same name and type
            is already owned by this user.
        ValueError: In case the config_schema string exceeds the max length.
    """
    with Session(self.engine) as session:
        if flavor.is_custom is False:
            # Set the user to None for built-in flavors
            flavor.user = None
        else:
            self._set_request_user_id(
                request_model=flavor, session=session
            )
        # Check if flavor with the same domain key (name, type) already
        # exists
        existing_flavor = session.exec(
            select(FlavorSchema)
            .where(FlavorSchema.name == flavor.name)
            .where(FlavorSchema.type == flavor.type)
        ).first()

        if existing_flavor is not None:
            raise EntityExistsError(
                f"Unable to register '{flavor.type.value}' flavor "
                f"with name '{flavor.name}' and type '{flavor.type}': "
                "Found an existing flavor with the same name and type."
            )

        config_schema = json.dumps(flavor.config_schema)

        if len(config_schema) > TEXT_FIELD_MAX_LENGTH:
            raise ValueError(
                "Json representation of configuration schema"
                "exceeds max length."
            )

        else:
            new_flavor = FlavorSchema(
                name=flavor.name,
                type=flavor.type,
                source=flavor.source,
                config_schema=config_schema,
                integration=flavor.integration,
                connector_type=flavor.connector_type,
                connector_resource_type=flavor.connector_resource_type,
                connector_resource_id_attr=flavor.connector_resource_id_attr,
                user_id=flavor.user,
                logo_url=flavor.logo_url,
                docs_url=flavor.docs_url,
                sdk_docs_url=flavor.sdk_docs_url,
                is_custom=flavor.is_custom,
            )
            session.add(new_flavor)
            session.commit()

            return new_flavor.to_model(
                include_metadata=True, include_resources=True
            )
create_model(model: ModelRequest) -> ModelResponse

Creates a new model.

Parameters:

Name Type Description Default
model ModelRequest

the Model to be created.

required

Returns:

Type Description
ModelResponse

The newly created model.

Raises:

Type Description
EntityExistsError

If a model with the given name already exists.

Source code in src/zenml/zen_stores/sql_zen_store.py
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
@track_decorator(AnalyticsEvent.CREATED_MODEL)
def create_model(self, model: ModelRequest) -> ModelResponse:
    """Creates a new model.

    Args:
        model: the Model to be created.

    Returns:
        The newly created model.

    Raises:
        EntityExistsError: If a model with the given name already exists.
    """
    validate_name(model)
    with Session(self.engine) as session:
        self._set_request_user_id(request_model=model, session=session)

        self._verify_name_uniqueness(
            resource=model,
            schema=ModelSchema,
            session=session,
        )

        model_schema = ModelSchema.from_request(model)
        session.add(model_schema)

        try:
            session.commit()
        except IntegrityError:
            # We have to rollback the failed session first in order
            # to continue using it
            session.rollback()
            raise EntityExistsError(
                f"Unable to create model {model.name}: "
                "A model with this name already exists."
            )

        self._attach_tags_to_resources(
            tags=model.tags,
            resources=model_schema,
            session=session,
        )

        session.refresh(model_schema)

        return model_schema.to_model(
            include_metadata=True, include_resources=True
        )
create_model_version(model_version: ModelVersionRequest) -> ModelVersionResponse

Creates a new model version.

Parameters:

Name Type Description Default
model_version ModelVersionRequest

the Model Version to be created.

required

Returns:

Type Description
ModelVersionResponse

The newly created model version.

Source code in src/zenml/zen_stores/sql_zen_store.py
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
@track_decorator(AnalyticsEvent.CREATED_MODEL_VERSION)
def create_model_version(
    self, model_version: ModelVersionRequest
) -> ModelVersionResponse:
    """Creates a new model version.

    Args:
        model_version: the Model Version to be created.

    Returns:
        The newly created model version.
    """
    return self._create_model_version(model_version=model_version)
create_model_version_artifact_link(model_version_artifact_link: ModelVersionArtifactRequest) -> ModelVersionArtifactResponse

Creates a new model version link.

Parameters:

Name Type Description Default
model_version_artifact_link ModelVersionArtifactRequest

the Model Version to Artifact Link to be created.

required

Returns:

Type Description
ModelVersionArtifactResponse

The newly created model version to artifact link.

Source code in src/zenml/zen_stores/sql_zen_store.py
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
def create_model_version_artifact_link(
    self, model_version_artifact_link: ModelVersionArtifactRequest
) -> ModelVersionArtifactResponse:
    """Creates a new model version link.

    Args:
        model_version_artifact_link: the Model Version to Artifact Link
            to be created.

    Returns:
        The newly created model version to artifact link.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(
            request_model=model_version_artifact_link, session=session
        )

        # If the link already exists, return it
        existing_model_version_artifact_link = session.exec(
            select(ModelVersionArtifactSchema)
            .where(
                ModelVersionArtifactSchema.model_version_id
                == model_version_artifact_link.model_version
            )
            .where(
                ModelVersionArtifactSchema.artifact_version_id
                == model_version_artifact_link.artifact_version,
            )
        ).first()
        if existing_model_version_artifact_link is not None:
            return existing_model_version_artifact_link.to_model()

        model_version_artifact_link_schema = (
            ModelVersionArtifactSchema.from_request(
                model_version_artifact_request=model_version_artifact_link,
            )
        )
        session.add(model_version_artifact_link_schema)
        session.commit()
        return model_version_artifact_link_schema.to_model(
            include_metadata=True, include_resources=True
        )
create_model_version_pipeline_run_link(model_version_pipeline_run_link: ModelVersionPipelineRunRequest) -> ModelVersionPipelineRunResponse

Creates a new model version to pipeline run link.

Parameters:

Name Type Description Default
model_version_pipeline_run_link ModelVersionPipelineRunRequest

the Model Version to Pipeline Run Link to be created.

required

Returns:

Type Description
ModelVersionPipelineRunResponse
  • If Model Version to Pipeline Run Link already exists - returns the existing link.
ModelVersionPipelineRunResponse
  • Otherwise, returns the newly created model version to pipeline run link.
Source code in src/zenml/zen_stores/sql_zen_store.py
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
def create_model_version_pipeline_run_link(
    self,
    model_version_pipeline_run_link: ModelVersionPipelineRunRequest,
) -> ModelVersionPipelineRunResponse:
    """Creates a new model version to pipeline run link.

    Args:
        model_version_pipeline_run_link: the Model Version to Pipeline Run
            Link to be created.

    Returns:
        - If Model Version to Pipeline Run Link already exists - returns
            the existing link.
        - Otherwise, returns the newly created model version to pipeline
            run link.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(
            request_model=model_version_pipeline_run_link, session=session
        )

        # If the link already exists, return it
        existing_model_version_pipeline_run_link = session.exec(
            select(ModelVersionPipelineRunSchema)
            .where(
                ModelVersionPipelineRunSchema.model_version_id
                == model_version_pipeline_run_link.model_version
            )
            .where(
                ModelVersionPipelineRunSchema.pipeline_run_id
                == model_version_pipeline_run_link.pipeline_run,
            )
        ).first()
        if existing_model_version_pipeline_run_link is not None:
            return existing_model_version_pipeline_run_link.to_model()

        # Otherwise, create a new link
        model_version_pipeline_run_link_schema = (
            ModelVersionPipelineRunSchema.from_request(
                model_version_pipeline_run_link
            )
        )
        session.add(model_version_pipeline_run_link_schema)
        session.commit()
        return model_version_pipeline_run_link_schema.to_model(
            include_metadata=True, include_resources=True
        )
create_pipeline(pipeline: PipelineRequest) -> PipelineResponse

Creates a new pipeline.

Parameters:

Name Type Description Default
pipeline PipelineRequest

The pipeline to create.

required

Returns:

Type Description
PipelineResponse

The newly created pipeline.

Raises:

Type Description
EntityExistsError

If an identical pipeline already exists.

Source code in src/zenml/zen_stores/sql_zen_store.py
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
@track_decorator(AnalyticsEvent.CREATE_PIPELINE)
def create_pipeline(
    self,
    pipeline: PipelineRequest,
) -> PipelineResponse:
    """Creates a new pipeline.

    Args:
        pipeline: The pipeline to create.

    Returns:
        The newly created pipeline.

    Raises:
        EntityExistsError: If an identical pipeline already exists.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(request_model=pipeline, session=session)

        new_pipeline = PipelineSchema.from_request(pipeline)

        session.add(new_pipeline)
        try:
            session.commit()
        except IntegrityError:
            # We have to rollback the failed session first in order
            # to continue using it
            session.rollback()
            raise EntityExistsError(
                f"Unable to create pipeline in project "
                f"'{pipeline.project}': A pipeline with the name "
                f"{pipeline.name} already exists."
            )
        session.refresh(new_pipeline)

        self._attach_tags_to_resources(
            tags=pipeline.tags,
            resources=new_pipeline,
            session=session,
        )

        session.refresh(new_pipeline)

        return new_pipeline.to_model(
            include_metadata=True, include_resources=True
        )
create_project(project: ProjectRequest) -> ProjectResponse

Creates a new project.

Parameters:

Name Type Description Default
project ProjectRequest

The project to create.

required

Returns:

Type Description
ProjectResponse

The newly created project.

Source code in src/zenml/zen_stores/sql_zen_store.py
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
@track_decorator(AnalyticsEvent.CREATED_PROJECT)
def create_project(self, project: ProjectRequest) -> ProjectResponse:
    """Creates a new project.

    Args:
        project: The project to create.

    Returns:
        The newly created project.
    """
    with Session(self.engine) as session:
        # Check if project with the given name already exists
        self._verify_name_uniqueness(
            resource=project,
            schema=ProjectSchema,
            session=session,
        )

        # Create the project
        new_project = ProjectSchema.from_request(project)
        session.add(new_project)
        session.commit()

        # Explicitly refresh the new_project schema
        session.refresh(new_project)

        project_model = new_project.to_model(
            include_metadata=True, include_resources=True
        )

        self._update_onboarding_state(
            completed_steps={OnboardingStep.PROJECT_CREATED},
            session=session,
        )

    return project_model
create_run_metadata(run_metadata: RunMetadataRequest) -> None

Creates run metadata.

Parameters:

Name Type Description Default
run_metadata RunMetadataRequest

The run metadata to create.

required

Returns:

Type Description
None

The created run metadata.

Raises:

Type Description
RuntimeError

If the resource type is not supported.

Source code in src/zenml/zen_stores/sql_zen_store.py
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
def create_run_metadata(self, run_metadata: RunMetadataRequest) -> None:
    """Creates run metadata.

    Args:
        run_metadata: The run metadata to create.

    Returns:
        The created run metadata.

    Raises:
        RuntimeError: If the resource type is not supported.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(
            request_model=run_metadata, session=session
        )

        self._get_reference_schema_by_id(
            resource=run_metadata,
            reference_schema=StackComponentSchema,
            reference_id=run_metadata.stack_component_id,
            session=session,
        )

        for resource in run_metadata.resources:
            reference_schema: Type[BaseSchema]
            if resource.type == MetadataResourceTypes.PIPELINE_RUN:
                reference_schema = PipelineRunSchema
            elif resource.type == MetadataResourceTypes.STEP_RUN:
                reference_schema = StepRunSchema
            elif resource.type == MetadataResourceTypes.ARTIFACT_VERSION:
                reference_schema = ArtifactVersionSchema
            elif resource.type == MetadataResourceTypes.MODEL_VERSION:
                reference_schema = ModelVersionSchema
            elif resource.type == MetadataResourceTypes.SCHEDULE:
                reference_schema = ScheduleSchema
            else:
                raise RuntimeError(
                    f"Unknown resource type: {resource.type}"
                )

            self._get_reference_schema_by_id(
                resource=run_metadata,
                reference_schema=reference_schema,
                reference_id=resource.id,
                session=session,
            )

        if run_metadata.resources:
            for key, value in run_metadata.values.items():
                type_ = run_metadata.types[key]

                run_metadata_schema = RunMetadataSchema(
                    project_id=run_metadata.project,
                    user_id=run_metadata.user,
                    stack_component_id=run_metadata.stack_component_id,
                    key=key,
                    value=json.dumps(value),
                    type=type_,
                    publisher_step_id=run_metadata.publisher_step_id,
                )

                session.add(run_metadata_schema)
                session.commit()

                for resource in run_metadata.resources:
                    rm_resource_link = RunMetadataResourceSchema(
                        resource_id=resource.id,
                        resource_type=resource.type.value,
                        run_metadata_id=run_metadata_schema.id,
                    )
                    session.add(rm_resource_link)
                    session.commit()
    return None
create_run_step(step_run: StepRunRequest) -> StepRunResponse

Creates a step run.

Parameters:

Name Type Description Default
step_run StepRunRequest

The step run to create.

required

Returns:

Type Description
StepRunResponse

The created step run.

Raises:

Type Description
EntityExistsError

if the step run already exists.

Source code in src/zenml/zen_stores/sql_zen_store.py
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
def create_run_step(self, step_run: StepRunRequest) -> StepRunResponse:
    """Creates a step run.

    Args:
        step_run: The step run to create.

    Returns:
        The created step run.

    Raises:
        EntityExistsError: if the step run already exists.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(request_model=step_run, session=session)

        # Check if the pipeline run exists
        run = self._get_reference_schema_by_id(
            resource=step_run,
            reference_schema=PipelineRunSchema,
            reference_id=step_run.pipeline_run_id,
            session=session,
        )

        self._get_reference_schema_by_id(
            resource=step_run,
            reference_schema=StepRunSchema,
            reference_id=step_run.original_step_run_id,
            session=session,
            reference_type="original step run",
        )

        step_schema = StepRunSchema.from_request(
            step_run, deployment_id=run.deployment_id
        )
        session.add(step_schema)
        try:
            session.commit()
        except IntegrityError:
            # We have to rollback the failed session first in order
            # to continue using it
            session.rollback()
            raise EntityExistsError(
                f"Unable to create step `{step_run.name}`: A step with "
                f"this name already exists in the pipeline run with ID "
                f"'{step_run.pipeline_run_id}'."
            )

        # Add logs entry for the step if exists
        if step_run.logs is not None:
            self._get_reference_schema_by_id(
                resource=step_run,
                reference_schema=StackComponentSchema,
                reference_id=step_run.logs.artifact_store_id,
                session=session,
                reference_type="logs artifact store",
            )

            log_entry = LogsSchema(
                uri=step_run.logs.uri,
                step_run_id=step_schema.id,
                artifact_store_id=step_run.logs.artifact_store_id,
            )
            session.add(log_entry)

        # If cached, attach metadata of the original step
        if (
            step_run.status == ExecutionStatus.CACHED
            and step_run.original_step_run_id is not None
        ):
            original_metadata_links = session.exec(
                select(RunMetadataResourceSchema)
                .where(
                    RunMetadataResourceSchema.run_metadata_id
                    == RunMetadataSchema.id
                )
                .where(
                    RunMetadataResourceSchema.resource_id
                    == step_run.original_step_run_id
                )
                .where(
                    RunMetadataResourceSchema.resource_type
                    == MetadataResourceTypes.STEP_RUN
                )
                .where(
                    RunMetadataSchema.publisher_step_id
                    == step_run.original_step_run_id
                )
            ).all()

            # Create new links in a batch
            new_links = [
                RunMetadataResourceSchema(
                    resource_id=step_schema.id,
                    resource_type=link.resource_type,
                    run_metadata_id=link.run_metadata_id,
                )
                for link in original_metadata_links
            ]
            # Add all new links in a single operation
            session.add_all(new_links)
            # Commit the changes
            session.commit()
            session.refresh(step_schema)

        # Save parent step IDs into the database.
        for parent_step_id in step_run.parent_step_ids:
            self._set_run_step_parent_step(
                child_step_run=step_schema,
                parent_id=parent_step_id,
                session=session,
            )

        session.commit()
        session.refresh(step_schema)

        step_model = step_schema.to_model(include_metadata=True)

        # Save input artifact IDs into the database.
        for input_name, artifact_version_id in step_run.inputs.items():
            input_type = self._get_step_run_input_type(
                input_name=input_name,
                step_config=step_model.config,
                step_spec=step_model.spec,
            )
            self._set_run_step_input_artifact(
                step_run=step_schema,
                artifact_version_id=artifact_version_id,
                name=input_name,
                input_type=input_type,
                session=session,
            )

        # Save output artifact IDs into the database.
        for name, artifact_version_ids in step_run.outputs.items():
            for artifact_version_id in artifact_version_ids:
                self._set_run_step_output_artifact(
                    step_run=step_schema,
                    artifact_version_id=artifact_version_id,
                    name=name,
                    session=session,
                )

        if step_run.status != ExecutionStatus.RUNNING:
            self._update_pipeline_run_status(
                pipeline_run_id=step_run.pipeline_run_id, session=session
            )

        session.commit()
        session.refresh(step_schema)

        if model_version_id := self._get_or_create_model_version_for_run(
            step_schema
        ):
            step_schema.model_version_id = model_version_id
            session.add(step_schema)
            session.commit()

            self.create_model_version_pipeline_run_link(
                ModelVersionPipelineRunRequest(
                    model_version=model_version_id,
                    pipeline_run=step_schema.pipeline_run_id,
                )
            )
            session.refresh(step_schema)

        return step_schema.to_model(
            include_metadata=True, include_resources=True
        )
create_run_template(template: RunTemplateRequest) -> RunTemplateResponse

Create a new run template.

Parameters:

Name Type Description Default
template RunTemplateRequest

The template to create.

required

Returns:

Type Description
RunTemplateResponse

The newly created template.

Source code in src/zenml/zen_stores/sql_zen_store.py
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
@track_decorator(AnalyticsEvent.CREATED_RUN_TEMPLATE)
def create_run_template(
    self,
    template: RunTemplateRequest,
) -> RunTemplateResponse:
    """Create a new run template.

    Args:
        template: The template to create.

    Returns:
        The newly created template.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(request_model=template, session=session)

        self._verify_name_uniqueness(
            resource=template,
            schema=RunTemplateSchema,
            session=session,
        )

        deployment = self._get_reference_schema_by_id(
            resource=template,
            reference_schema=PipelineDeploymentSchema,
            reference_id=template.source_deployment_id,
            session=session,
        )

        template_utils.validate_deployment_is_templatable(deployment)

        template_schema = RunTemplateSchema.from_request(request=template)

        session.add(template_schema)
        session.commit()
        session.refresh(template_schema)

        self._attach_tags_to_resources(
            tags=template.tags,
            resources=template_schema,
            session=session,
        )

        session.refresh(template_schema)

        return template_schema.to_model(
            include_metadata=True, include_resources=True
        )
create_schedule(schedule: ScheduleRequest) -> ScheduleResponse

Creates a new schedule.

Parameters:

Name Type Description Default
schedule ScheduleRequest

The schedule to create.

required

Returns:

Type Description
ScheduleResponse

The newly created schedule.

Source code in src/zenml/zen_stores/sql_zen_store.py
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
def create_schedule(self, schedule: ScheduleRequest) -> ScheduleResponse:
    """Creates a new schedule.

    Args:
        schedule: The schedule to create.

    Returns:
        The newly created schedule.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(request_model=schedule, session=session)

        self._verify_name_uniqueness(
            resource=schedule,
            schema=ScheduleSchema,
            session=session,
        )

        self._get_reference_schema_by_id(
            resource=schedule,
            reference_schema=StackComponentSchema,
            reference_id=schedule.orchestrator_id,
            session=session,
            reference_type="orchestrator",
        )

        self._get_reference_schema_by_id(
            resource=schedule,
            reference_schema=PipelineSchema,
            reference_id=schedule.pipeline_id,
            session=session,
        )

        new_schedule = ScheduleSchema.from_request(schedule)
        session.add(new_schedule)
        session.commit()
        return new_schedule.to_model(
            include_metadata=True, include_resources=True
        )
create_secret(secret: SecretRequest) -> SecretResponse

Creates a new secret.

The new secret is also validated against the scoping rules enforced in the secrets store:

  • a user cannot own two private secrets with the same name
  • two public secrets cannot have the same name

Parameters:

Name Type Description Default
secret SecretRequest

The secret to create.

required

Returns:

Type Description
SecretResponse

The newly created secret.

Raises:

Type Description
EntityExistsError

If a secret with the same name already exists in the same scope.

Source code in src/zenml/zen_stores/sql_zen_store.py
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
@track_decorator(AnalyticsEvent.CREATED_SECRET)
def create_secret(self, secret: SecretRequest) -> SecretResponse:
    """Creates a new secret.

    The new secret is also validated against the scoping rules enforced in
    the secrets store:

    - a user cannot own two private secrets with the same name
    - two public secrets cannot have the same name

    Args:
        secret: The secret to create.

    Returns:
        The newly created secret.

    Raises:
        EntityExistsError: If a secret with the same name already exists in
            the same scope.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(request_model=secret, session=session)
        assert secret.user is not None
        # Check if a secret with the same name already exists in the same
        # scope.
        secret_exists, msg = self._check_sql_secret_scope(
            session=session,
            secret_name=secret.name,
            private=secret.private,
            user=secret.user,
        )
        if secret_exists:
            raise EntityExistsError(msg)

        new_secret = SecretSchema.from_request(
            secret,
        )
        session.add(new_secret)
        session.commit()

        secret_model = new_secret.to_model(
            include_metadata=True, include_resources=True
        )

    try:
        # Set the secret values in the configured secrets store
        self._set_secret_values(
            secret_id=new_secret.id, values=secret.secret_values
        )
    except:
        # If setting the secret values fails, delete the secret from the
        # database.
        with Session(self.engine) as session:
            session.delete(new_secret)
            session.commit()
        raise

    secret_model.set_secrets(secret.secret_values)
    return secret_model
create_service(service: ServiceRequest) -> ServiceResponse

Create a new service.

Parameters:

Name Type Description Default
service ServiceRequest

The service to create.

required

Returns:

Type Description
ServiceResponse

The newly created service.

Source code in src/zenml/zen_stores/sql_zen_store.py
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
def create_service(self, service: ServiceRequest) -> ServiceResponse:
    """Create a new service.

    Args:
        service: The service to create.

    Returns:
        The newly created service.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(request_model=service, session=session)
        # Check if a service with the given name already exists
        self._fail_if_service_with_config_exists(
            service_request=service,
            session=session,
        )

        self._get_reference_schema_by_id(
            resource=service,
            reference_schema=PipelineRunSchema,
            reference_id=service.pipeline_run_id,
            session=session,
        )

        self._get_reference_schema_by_id(
            resource=service,
            reference_schema=ModelVersionSchema,
            reference_id=service.model_version_id,
            session=session,
        )

        service_schema = ServiceSchema.from_request(service)
        logger.debug("Creating service: %s", service_schema)
        session.add(service_schema)
        session.commit()

        return service_schema.to_model(
            include_metadata=True, include_resources=True
        )
create_service_account(service_account: ServiceAccountRequest) -> ServiceAccountResponse

Creates a new service account.

Parameters:

Name Type Description Default
service_account ServiceAccountRequest

Service account to be created.

required

Returns:

Type Description
ServiceAccountResponse

The newly created service account.

Raises:

Type Description
EntityExistsError

If a user or service account with the given name already exists.

Source code in src/zenml/zen_stores/sql_zen_store.py
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
@track_decorator(AnalyticsEvent.CREATED_SERVICE_ACCOUNT)
def create_service_account(
    self, service_account: ServiceAccountRequest
) -> ServiceAccountResponse:
    """Creates a new service account.

    Args:
        service_account: Service account to be created.

    Returns:
        The newly created service account.

    Raises:
        EntityExistsError: If a user or service account with the given name
            already exists.
    """
    with Session(self.engine) as session:
        # Check if a service account with the given name already
        # exists
        err_msg = (
            f"Unable to create service account with name "
            f"'{service_account.name}': Found existing service "
            "account with this name."
        )
        try:
            self._get_account_schema(
                service_account.name, session=session, service_account=True
            )
            raise EntityExistsError(err_msg)
        except KeyError:
            pass

        # Create the service account
        new_account = UserSchema.from_service_account_request(
            service_account
        )
        session.add(new_account)
        # on commit an IntegrityError may arise we let it bubble up
        session.commit()

        return new_account.to_service_account_model(
            include_metadata=True, include_resources=True
        )
create_service_connector(service_connector: ServiceConnectorRequest) -> ServiceConnectorResponse

Creates a new service connector.

Parameters:

Name Type Description Default
service_connector ServiceConnectorRequest

Service connector to be created.

required

Returns:

Type Description
ServiceConnectorResponse

The newly created service connector.

Raises:

Type Description
Exception

If anything goes wrong during the creation of the service connector.

Source code in src/zenml/zen_stores/sql_zen_store.py
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
@track_decorator(AnalyticsEvent.CREATED_SERVICE_CONNECTOR)
def create_service_connector(
    self, service_connector: ServiceConnectorRequest
) -> ServiceConnectorResponse:
    """Creates a new service connector.

    Args:
        service_connector: Service connector to be created.

    Returns:
        The newly created service connector.

    Raises:
        Exception: If anything goes wrong during the creation of the
            service connector.
    """
    # If the connector type is locally available, we validate the request
    # against the connector type schema before storing it in the database
    if service_connector_registry.is_registered(service_connector.type):
        connector_type = (
            service_connector_registry.get_service_connector_type(
                service_connector.type
            )
        )
        service_connector.validate_and_configure_resources(
            connector_type=connector_type,
            resource_types=service_connector.resource_types,
            resource_id=service_connector.resource_id,
            configuration=service_connector.configuration,
            secrets=service_connector.secrets,
        )

    with Session(self.engine) as session:
        self._set_request_user_id(
            request_model=service_connector, session=session
        )
        assert service_connector.user is not None

        self._verify_name_uniqueness(
            resource=service_connector,
            schema=ServiceConnectorSchema,
            session=session,
        )

        # Create the secret
        secret_id = self._create_connector_secret(
            connector_name=service_connector.name,
            secrets=service_connector.secrets,
        )
        try:
            # Create the service connector
            new_service_connector = ServiceConnectorSchema.from_request(
                service_connector,
                secret_id=secret_id,
            )

            session.add(new_service_connector)
            session.commit()

            session.refresh(new_service_connector)
        except Exception:
            # Delete the secret if it was created
            if secret_id:
                try:
                    self.delete_secret(secret_id)
                except Exception:
                    # Ignore any errors that occur while deleting the
                    # secret
                    pass

            raise

        connector = new_service_connector.to_model(
            include_metadata=True, include_resources=True
        )
        self._populate_connector_type(connector)

        return connector
create_stack(stack: StackRequest) -> StackResponse

Register a full stack.

Parameters:

Name Type Description Default
stack StackRequest

The full stack configuration.

required

Returns:

Type Description
StackResponse

The registered stack.

Raises:

Type Description
ValueError

If the full stack creation fails, due to the corrupted input.

Exception

If the full stack creation fails, due to unforeseen errors.

Source code in src/zenml/zen_stores/sql_zen_store.py
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
@track_decorator(AnalyticsEvent.REGISTERED_STACK)
def create_stack(self, stack: StackRequest) -> StackResponse:
    """Register a full stack.

    Args:
        stack: The full stack configuration.

    Returns:
        The registered stack.

    Raises:
        ValueError: If the full stack creation fails, due to the corrupted
            input.
        Exception: If the full stack creation fails, due to unforeseen
            errors.
    """
    with Session(self.engine) as session:
        if isinstance(stack, DefaultStackRequest):
            # Set the user to None for default stacks
            stack.user = None
        else:
            self._set_request_user_id(request_model=stack, session=session)

        # For clean-up purposes, each created entity is tracked here
        service_connectors_created_ids: List[UUID] = []
        components_created_ids: List[UUID] = []

        try:
            # Validate the name of the new stack
            validate_name(stack)

            if stack.labels is None:
                stack.labels = {}

            # Service Connectors
            service_connectors: List[ServiceConnectorResponse] = []

            orchestrator_components = stack.components[
                StackComponentType.ORCHESTRATOR
            ]
            for orchestrator_component in orchestrator_components:
                if isinstance(orchestrator_component, UUID):
                    orchestrator = self.get_stack_component(
                        orchestrator_component,
                        hydrate=False,
                    )
                    need_to_generate_permanent_tokens = (
                        orchestrator.flavor_name.startswith("vm_")
                    )
                else:
                    need_to_generate_permanent_tokens = (
                        orchestrator_component.flavor.startswith("vm_")
                    )

            for connector_id_or_info in stack.service_connectors:
                # Fetch an existing service connector
                if isinstance(connector_id_or_info, UUID):
                    existing_service_connector = (
                        self.get_service_connector(connector_id_or_info)
                    )
                    if need_to_generate_permanent_tokens:
                        if (
                            existing_service_connector.configuration.get(
                                "generate_temporary_tokens", None
                            )
                            is not False
                        ):
                            connector_config = (
                                existing_service_connector.configuration
                            )
                            connector_config[
                                "generate_temporary_tokens"
                            ] = False
                            self.update_service_connector(
                                existing_service_connector.id,
                                ServiceConnectorUpdate(
                                    configuration=connector_config
                                ),
                            )
                    service_connectors.append(
                        self.get_service_connector(connector_id_or_info)
                    )
                # Create a new service connector
                else:
                    connector_name = stack.name
                    connector_config = connector_id_or_info.configuration
                    connector_config[
                        "generate_temporary_tokens"
                    ] = not need_to_generate_permanent_tokens

                    while True:
                        try:
                            service_connector_request = ServiceConnectorRequest(
                                name=connector_name,
                                connector_type=connector_id_or_info.type,
                                auth_method=connector_id_or_info.auth_method,
                                configuration=connector_config,
                                labels={
                                    k: str(v)
                                    for k, v in stack.labels.items()
                                },
                            )
                            service_connector_response = self.create_service_connector(
                                service_connector=service_connector_request
                            )
                            service_connectors.append(
                                service_connector_response
                            )
                            service_connectors_created_ids.append(
                                service_connector_response.id
                            )
                            break
                        except EntityExistsError:
                            connector_name = (
                                f"{stack.name}-{random_str(4)}".lower()
                            )
                            continue

            # Stack Components
            components_mapping: Dict[StackComponentType, List[UUID]] = {}
            for (
                component_type,
                components,
            ) in stack.components.items():
                for component_info in components:
                    # Fetch an existing component
                    if isinstance(component_info, UUID):
                        component = self.get_stack_component(
                            component_id=component_info
                        )
                    # Create a new component
                    else:
                        flavor_list = self.list_flavors(
                            flavor_filter_model=FlavorFilter(
                                name=component_info.flavor,
                                type=component_type,
                            )
                        )
                        if not len(flavor_list):
                            raise ValueError(
                                f"Flavor '{component_info.flavor}' not found "
                                f"for component type '{component_type}'."
                            )

                        flavor_model = flavor_list[0]

                        component_name = stack.name
                        while True:
                            try:
                                component_request = ComponentRequest(
                                    name=component_name,
                                    type=component_type,
                                    flavor=component_info.flavor,
                                    configuration=component_info.configuration,
                                    labels=stack.labels,
                                )
                                component = self.create_stack_component(
                                    component=component_request
                                )
                                components_created_ids.append(component.id)
                                break
                            except EntityExistsError:
                                component_name = (
                                    f"{stack.name}-{random_str(4)}".lower()
                                )
                                continue

                        if (
                            component_info.service_connector_index
                            is not None
                        ):
                            service_connector = service_connectors[
                                component_info.service_connector_index
                            ]

                            requirements = (
                                flavor_model.connector_requirements
                            )

                            if not requirements:
                                raise ValueError(
                                    f"The '{flavor_model.name}' implementation "
                                    "does not support using a service "
                                    "connector to connect to resources."
                                )

                            if component_info.service_connector_resource_id:
                                resource_id = component_info.service_connector_resource_id
                            else:
                                resource_id = None
                                resource_type = requirements.resource_type
                                if (
                                    requirements.resource_id_attr
                                    is not None
                                ):
                                    resource_id = (
                                        component_info.configuration.get(
                                            requirements.resource_id_attr
                                        )
                                    )

                            satisfied, msg = requirements.is_satisfied_by(
                                connector=service_connector,
                                component=component,
                            )

                            if not satisfied:
                                raise ValueError(
                                    "Please pick a connector that is "
                                    "compatible with the component flavor and "
                                    "try again.."
                                )

                            if not resource_id:
                                if service_connector.resource_id:
                                    resource_id = (
                                        service_connector.resource_id
                                    )
                                elif service_connector.supports_instances:
                                    raise ValueError(
                                        f"Multiple {resource_type} resources "
                                        "are available for the selected "
                                        "connector. Please use a `resource_id` "
                                        "to configure a "
                                        f"{resource_type} resource."
                                    )

                            component_update = ComponentUpdate(
                                connector=service_connector.id,
                                connector_resource_id=resource_id,
                            )
                            self.update_stack_component(
                                component_id=component.id,
                                component_update=component_update,
                            )

                    components_mapping[component_type] = [
                        component.id,
                    ]

            # Stack
            self._verify_name_uniqueness(
                resource=stack,
                schema=StackSchema,
                session=session,
            )

            component_ids = (
                [
                    component_id
                    for list_of_component_ids in components_mapping.values()
                    for component_id in list_of_component_ids
                ]
                if stack.components is not None
                else []
            )
            filters = [
                (StackComponentSchema.id == component_id)
                for component_id in component_ids
            ]

            defined_components = session.exec(
                select(StackComponentSchema).where(or_(*filters))
            ).all()

            new_stack_schema = StackSchema(
                user_id=stack.user,
                stack_spec_path=stack.stack_spec_path,
                name=stack.name,
                description=stack.description,
                components=defined_components,
                labels=base64.b64encode(
                    json.dumps(stack.labels).encode("utf-8")
                ),
            )

            session.add(new_stack_schema)
            session.commit()
            session.refresh(new_stack_schema)

            for defined_component in defined_components:
                if (
                    defined_component.type
                    == StackComponentType.ORCHESTRATOR
                ):
                    if defined_component.flavor not in {
                        "local",
                        "local_docker",
                    }:
                        self._update_onboarding_state(
                            completed_steps={
                                OnboardingStep.STACK_WITH_REMOTE_ORCHESTRATOR_CREATED
                            },
                            session=session,
                        )

            return new_stack_schema.to_model(
                include_metadata=True, include_resources=True
            )

        except Exception:
            for component_id in components_created_ids:
                self.delete_stack_component(component_id=component_id)
            for service_connector_id in service_connectors_created_ids:
                self.delete_service_connector(
                    service_connector_id=service_connector_id
                )
            logger.error(
                "Stack creation has failed. Cleaned up the entities "
                "that are created in the process."
            )
            raise
create_stack_component(component: ComponentRequest) -> ComponentResponse

Create a stack component.

Parameters:

Name Type Description Default
component ComponentRequest

The stack component to create.

required

Returns:

Type Description
ComponentResponse

The created stack component.

Source code in src/zenml/zen_stores/sql_zen_store.py
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
@track_decorator(AnalyticsEvent.REGISTERED_STACK_COMPONENT)
def create_stack_component(
    self,
    component: ComponentRequest,
) -> ComponentResponse:
    """Create a stack component.

    Args:
        component: The stack component to create.

    Returns:
        The created stack component.
    """
    validate_name(component)
    with Session(self.engine) as session:
        if isinstance(component, DefaultComponentRequest):
            # Set the user to None for default components
            component.user = None
        else:
            self._set_request_user_id(
                request_model=component, session=session
            )

        self._fail_if_component_with_name_type_exists(
            name=component.name,
            component_type=component.type,
            session=session,
        )

        is_default_stack_component = (
            component.name == DEFAULT_STACK_AND_COMPONENT_NAME
            and component.type
            in {
                StackComponentType.ORCHESTRATOR,
                StackComponentType.ARTIFACT_STORE,
            }
        )
        # We have to skip the validation of the default components
        # as it creates a loop of initialization.
        if not is_default_stack_component:
            from zenml.stack.utils import validate_stack_component_config

            validate_stack_component_config(
                configuration_dict=component.configuration,
                flavor=component.flavor,
                component_type=component.type,
                zen_store=self,
                validate_custom_flavors=False,
            )

        service_connector = self._get_reference_schema_by_id(
            resource=component,
            reference_schema=ServiceConnectorSchema,
            reference_id=component.connector,
            session=session,
        )

        # warn about skypilot regions, if needed
        # TODO: this sooo does not belong here!
        if component.flavor in {"vm_gcp", "vm_azure"}:
            stack_deployment_class = get_stack_deployment_class(
                StackDeploymentProvider.GCP
                if component.flavor == "vm_gcp"
                else StackDeploymentProvider.AZURE
            )
            skypilot_regions = (
                stack_deployment_class.skypilot_default_regions().values()
            )
            if (
                component.configuration.get("region", None)
                and component.configuration["region"]
                not in skypilot_regions
            ):
                logger.warning(
                    f"Region `{component.configuration['region']}` is "
                    "not enabled in Skypilot by default. Supported regions "
                    f"by default are: {skypilot_regions}. Check the "
                    "Skypilot documentation to learn how to enable "
                    "regions rather than default ones. (If you have "
                    "already extended your configuration - "
                    "simply ignore this warning)"
                )

        # Create the component
        new_component = StackComponentSchema.from_request(
            request=component, service_connector=service_connector
        )

        session.add(new_component)
        session.commit()

        session.refresh(new_component)

        return new_component.to_model(
            include_metadata=True, include_resources=True
        )
create_tag(tag: TagRequest) -> TagResponse

Creates a new tag.

Parameters:

Name Type Description Default
tag TagRequest

the tag to be created.

required

Returns:

Type Description
TagResponse

The newly created tag.

Source code in src/zenml/zen_stores/sql_zen_store.py
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
@track_decorator(AnalyticsEvent.CREATED_TAG)
def create_tag(self, tag: TagRequest) -> TagResponse:
    """Creates a new tag.

    Args:
        tag: the tag to be created.

    Returns:
        The newly created tag.
    """
    with Session(self.engine) as session:
        tag_schema = self._create_tag_schema(tag=tag, session=session)
        return tag_schema.to_model(
            include_metadata=True, include_resources=True
        )
create_tag_resource(tag_resource: TagResourceRequest) -> TagResourceResponse

Creates a new tag resource relationship.

Parameters:

Name Type Description Default
tag_resource TagResourceRequest

the tag resource relationship to be created.

required

Returns:

Type Description
TagResourceResponse

The newly created tag resource relationship.

Source code in src/zenml/zen_stores/sql_zen_store.py
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
def create_tag_resource(
    self, tag_resource: TagResourceRequest
) -> TagResourceResponse:
    """Creates a new tag resource relationship.

    Args:
        tag_resource: the tag resource relationship to be created.

    Returns:
        The newly created tag resource relationship.
    """
    return self.batch_create_tag_resource(tag_resources=[tag_resource])[0]
create_trigger(trigger: TriggerRequest) -> TriggerResponse

Creates a new trigger.

Parameters:

Name Type Description Default
trigger TriggerRequest

Trigger to be created.

required

Returns:

Type Description
TriggerResponse

The newly created trigger.

Source code in src/zenml/zen_stores/sql_zen_store.py
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
@track_decorator(AnalyticsEvent.CREATED_TRIGGER)
def create_trigger(self, trigger: TriggerRequest) -> TriggerResponse:
    """Creates a new trigger.

    Args:
        trigger: Trigger to be created.

    Returns:
        The newly created trigger.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(request_model=trigger, session=session)

        # Verify that the trigger name is unique
        self._verify_name_uniqueness(
            resource=trigger,
            schema=TriggerSchema,
            session=session,
        )

        # Verify that the given action exists
        self._get_reference_schema_by_id(
            resource=trigger,
            reference_schema=ActionSchema,
            reference_id=trigger.action_id,
            session=session,
        )

        self._get_reference_schema_by_id(
            resource=trigger,
            reference_schema=EventSourceSchema,
            reference_id=trigger.event_source_id,
            session=session,
        )

        new_trigger = TriggerSchema.from_request(trigger)
        session.add(new_trigger)
        session.commit()
        session.refresh(new_trigger)

        return new_trigger.to_model(
            include_metadata=True, include_resources=True
        )
create_trigger_execution(trigger_execution: TriggerExecutionRequest) -> TriggerExecutionResponse

Create a trigger execution.

Parameters:

Name Type Description Default
trigger_execution TriggerExecutionRequest

The trigger execution to create.

required

Returns:

Type Description
TriggerExecutionResponse

The created trigger execution.

Source code in src/zenml/zen_stores/sql_zen_store.py
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
def create_trigger_execution(
    self, trigger_execution: TriggerExecutionRequest
) -> TriggerExecutionResponse:
    """Create a trigger execution.

    Args:
        trigger_execution: The trigger execution to create.

    Returns:
        The created trigger execution.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(
            request_model=trigger_execution, session=session
        )
        self._get_reference_schema_by_id(
            resource=trigger_execution,
            reference_schema=TriggerSchema,
            reference_id=trigger_execution.trigger,
            session=session,
        )
        new_execution = TriggerExecutionSchema.from_request(
            trigger_execution
        )
        session.add(new_execution)
        session.commit()
        session.refresh(new_execution)

        return new_execution.to_model(
            include_metadata=True, include_resources=True
        )
create_user(user: UserRequest) -> UserResponse

Creates a new user.

Parameters:

Name Type Description Default
user UserRequest

User to be created.

required

Returns:

Type Description
UserResponse

The newly created user.

Raises:

Type Description
EntityExistsError

If a user or service account with the given name already exists.

Source code in src/zenml/zen_stores/sql_zen_store.py
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
def create_user(self, user: UserRequest) -> UserResponse:
    """Creates a new user.

    Args:
        user: User to be created.

    Returns:
        The newly created user.

    Raises:
        EntityExistsError: If a user or service account with the given name
            already exists.
    """
    with Session(self.engine) as session:
        # Check if a user account with the given name already exists
        err_msg = (
            f"Unable to create user with name '{user.name}': "
            f"Found an existing user account with this name."
        )
        try:
            self._get_account_schema(
                user.name,
                session=session,
                # Filter out service accounts
                service_account=False,
            )
            raise EntityExistsError(err_msg)
        except KeyError:
            pass

        # Create the user
        new_user = UserSchema.from_user_request(user)
        session.add(new_user)
        # on commit an IntegrityError may arise we let it bubble up
        session.commit()

        server_info = self.get_store_info()
        with AnalyticsContext() as context:
            context.user_id = new_user.id

            context.group(
                group_id=server_info.id,
                traits={
                    "server_id": server_info.id,
                    "version": server_info.version,
                    "deployment_type": str(server_info.deployment_type),
                    "database_type": str(server_info.database_type),
                },
            )

        return new_user.to_model(
            include_metadata=True, include_resources=True
        )
delete_action(action_id: UUID) -> None

Delete an action.

Parameters:

Name Type Description Default
action_id UUID

The ID of the action to delete.

required

Raises:

Type Description
IllegalOperationError

If the action can't be deleted because it's used by triggers.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def delete_action(self, action_id: UUID) -> None:
    """Delete an action.

    Args:
        action_id: The ID of the action to delete.

    Raises:
        IllegalOperationError: If the action can't be deleted
            because it's used by triggers.
    """
    with Session(self.engine) as session:
        action = self._get_schema_by_id(
            resource_id=action_id,
            schema_class=ActionSchema,
            session=session,
        )

        # Prevent deletion of action if it is used by a trigger
        if action.triggers:
            raise IllegalOperationError(
                f"Unable to delete action with ID `{action_id}` "
                f"as it is used by {len(action.triggers)} triggers."
            )

        session.delete(action)
        session.commit()
delete_all_model_version_artifact_links(model_version_id: UUID, only_links: bool = True) -> None

Deletes all model version to artifact links.

Parameters:

Name Type Description Default
model_version_id UUID

ID of the model version containing the link.

required
only_links bool

Whether to only delete the link to the artifact.

True
Source code in src/zenml/zen_stores/sql_zen_store.py
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
def delete_all_model_version_artifact_links(
    self,
    model_version_id: UUID,
    only_links: bool = True,
) -> None:
    """Deletes all model version to artifact links.

    Args:
        model_version_id: ID of the model version containing the link.
        only_links: Whether to only delete the link to the artifact.
    """
    with Session(self.engine) as session:
        if not only_links:
            artifact_version_ids = session.execute(
                select(
                    ModelVersionArtifactSchema.artifact_version_id
                ).where(
                    ModelVersionArtifactSchema.model_version_id
                    == model_version_id
                )
            ).fetchall()
            session.execute(
                delete(ArtifactVersionSchema).where(
                    col(ArtifactVersionSchema.id).in_(
                        [a[0] for a in artifact_version_ids]
                    )
                ),
            )
        session.execute(
            delete(ModelVersionArtifactSchema).where(
                ModelVersionArtifactSchema.model_version_id  # type: ignore[arg-type]
                == model_version_id
            )
        )

        session.commit()
delete_api_key(service_account_id: UUID, api_key_name_or_id: Union[str, UUID]) -> None

Delete an API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to delete the API key.

required
api_key_name_or_id Union[str, UUID]

The name or ID of the API key to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
def delete_api_key(
    self,
    service_account_id: UUID,
    api_key_name_or_id: Union[str, UUID],
) -> None:
    """Delete an API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to
            delete the API key.
        api_key_name_or_id: The name or ID of the API key to delete.
    """
    with Session(self.engine) as session:
        api_key = self._get_api_key(
            service_account_id=service_account_id,
            api_key_name_or_id=api_key_name_or_id,
            session=session,
        )

        session.delete(api_key)
        session.commit()
delete_artifact(artifact_id: UUID) -> None

Deletes an artifact.

Parameters:

Name Type Description Default
artifact_id UUID

The ID of the artifact to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
def delete_artifact(self, artifact_id: UUID) -> None:
    """Deletes an artifact.

    Args:
        artifact_id: The ID of the artifact to delete.
    """
    with Session(self.engine) as session:
        existing_artifact = self._get_schema_by_id(
            resource_id=artifact_id,
            schema_class=ArtifactSchema,
            session=session,
        )
        session.delete(existing_artifact)
        session.commit()
delete_artifact_version(artifact_version_id: UUID) -> None

Deletes an artifact version.

Parameters:

Name Type Description Default
artifact_version_id UUID

The ID of the artifact version to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
def delete_artifact_version(self, artifact_version_id: UUID) -> None:
    """Deletes an artifact version.

    Args:
        artifact_version_id: The ID of the artifact version to delete.
    """
    with Session(self.engine) as session:
        artifact_version = self._get_schema_by_id(
            resource_id=artifact_version_id,
            schema_class=ArtifactVersionSchema,
            session=session,
        )
        session.delete(artifact_version)
        session.commit()
delete_authorized_device(device_id: UUID) -> None

Deletes an OAuth 2.0 authorized device.

Parameters:

Name Type Description Default
device_id UUID

The ID of the device to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
def delete_authorized_device(self, device_id: UUID) -> None:
    """Deletes an OAuth 2.0 authorized device.

    Args:
        device_id: The ID of the device to delete.
    """
    with Session(self.engine) as session:
        existing_device = self._get_schema_by_id(
            resource_id=device_id,
            schema_class=OAuthDeviceSchema,
            session=session,
            resource_type="authorized device",
        )

        session.delete(existing_device)
        session.commit()
delete_build(build_id: UUID) -> None

Deletes a build.

Parameters:

Name Type Description Default
build_id UUID

The ID of the build to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
def delete_build(self, build_id: UUID) -> None:
    """Deletes a build.

    Args:
        build_id: The ID of the build to delete.
    """
    with Session(self.engine) as session:
        # Check if build with the given ID exists
        build = self._get_schema_by_id(
            resource_id=build_id,
            schema_class=PipelineBuildSchema,
            session=session,
        )

        session.delete(build)
        session.commit()
delete_code_repository(code_repository_id: UUID) -> None

Deletes a code repository.

Parameters:

Name Type Description Default
code_repository_id UUID

The ID of the code repository to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
def delete_code_repository(self, code_repository_id: UUID) -> None:
    """Deletes a code repository.

    Args:
        code_repository_id: The ID of the code repository to delete.
    """
    with Session(self.engine) as session:
        existing_repo = self._get_schema_by_id(
            resource_id=code_repository_id,
            schema_class=CodeRepositorySchema,
            session=session,
        )

        session.delete(existing_repo)
        session.commit()
delete_deployment(deployment_id: UUID) -> None

Deletes a deployment.

Parameters:

Name Type Description Default
deployment_id UUID

The ID of the deployment to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
def delete_deployment(self, deployment_id: UUID) -> None:
    """Deletes a deployment.

    Args:
        deployment_id: The ID of the deployment to delete.
    """
    with Session(self.engine) as session:
        # Check if build with the given ID exists
        deployment = self._get_schema_by_id(
            resource_id=deployment_id,
            schema_class=PipelineDeploymentSchema,
            session=session,
        )

        session.delete(deployment)
        session.commit()
delete_event_source(event_source_id: UUID) -> None

Delete an event_source.

Parameters:

Name Type Description Default
event_source_id UUID

The ID of the event_source to delete.

required

Raises:

Type Description
IllegalOperationError

If the event source can't be deleted because it's used by triggers.

Source code in src/zenml/zen_stores/sql_zen_store.py
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
def delete_event_source(self, event_source_id: UUID) -> None:
    """Delete an event_source.

    Args:
        event_source_id: The ID of the event_source to delete.

    Raises:
        IllegalOperationError: If the event source can't be deleted
            because it's used by triggers.
    """
    with Session(self.engine) as session:
        event_source = self._get_schema_by_id(
            resource_id=event_source_id,
            schema_class=EventSourceSchema,
            session=session,
        )

        # Prevent deletion of event source if it is used by a trigger
        if event_source.triggers:
            raise IllegalOperationError(
                f"Unable to delete event_source with ID `{event_source_id}`"
                f" as it is used by {len(event_source.triggers)} triggers."
            )

        session.delete(event_source)
        session.commit()
delete_expired_authorized_devices() -> None

Deletes all expired OAuth 2.0 authorized devices.

Source code in src/zenml/zen_stores/sql_zen_store.py
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
def delete_expired_authorized_devices(self) -> None:
    """Deletes all expired OAuth 2.0 authorized devices."""
    with Session(self.engine) as session:
        expired_devices = session.exec(
            select(OAuthDeviceSchema).where(OAuthDeviceSchema.user is None)
        ).all()
        for device in expired_devices:
            # Delete devices that have expired
            if (
                device.expires is not None
                and device.expires < utc_now()
                and device.user_id is None
            ):
                session.delete(device)
        session.commit()
delete_flavor(flavor_id: UUID) -> None

Delete a flavor.

Parameters:

Name Type Description Default
flavor_id UUID

The id of the flavor to delete.

required

Raises:

Type Description
IllegalOperationError

if the flavor is used by a stack component.

Source code in src/zenml/zen_stores/sql_zen_store.py
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
def delete_flavor(self, flavor_id: UUID) -> None:
    """Delete a flavor.

    Args:
        flavor_id: The id of the flavor to delete.

    Raises:
        IllegalOperationError: if the flavor is used by a stack component.
    """
    with Session(self.engine) as session:
        flavor_in_db = self._get_schema_by_id(
            resource_id=flavor_id,
            schema_class=FlavorSchema,
            session=session,
        )
        components_of_flavor = session.exec(
            select(StackComponentSchema).where(
                StackComponentSchema.flavor == flavor_in_db.name
            )
        ).all()
        if len(components_of_flavor) > 0:
            raise IllegalOperationError(
                f"Stack Component `{flavor_in_db.name}` of type "
                f"`{flavor_in_db.type} cannot be "
                f"deleted as it is used by "
                f"{len(components_of_flavor)} "
                f"components. Before deleting this "
                f"flavor, make sure to delete all "
                f"associated components."
            )
        else:
            session.delete(flavor_in_db)
            session.commit()
delete_model(model_id: UUID) -> None

Deletes a model.

Parameters:

Name Type Description Default
model_id UUID

id of the model to be deleted.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
def delete_model(self, model_id: UUID) -> None:
    """Deletes a model.

    Args:
        model_id: id of the model to be deleted.
    """
    with Session(self.engine) as session:
        model = self._get_schema_by_id(
            resource_id=model_id,
            schema_class=ModelSchema,
            session=session,
        )

        session.delete(model)
        session.commit()
delete_model_version(model_version_id: UUID) -> None

Deletes a model version.

Parameters:

Name Type Description Default
model_version_id UUID

name or id of the model version to be deleted.

required

Raises:

Type Description
KeyError

specified ID or name not found.

Source code in src/zenml/zen_stores/sql_zen_store.py
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
def delete_model_version(
    self,
    model_version_id: UUID,
) -> None:
    """Deletes a model version.

    Args:
        model_version_id: name or id of the model version to be deleted.

    Raises:
        KeyError: specified ID or name not found.
    """
    with Session(self.engine) as session:
        query = select(ModelVersionSchema).where(
            ModelVersionSchema.id == model_version_id
        )
        model_version = session.exec(query).first()
        if model_version is None:
            raise KeyError(
                "Unable to delete model version with id "
                f"`{model_version_id}`: "
                "No model version with this id found."
            )
        session.delete(model_version)
        session.commit()
delete_model_version_artifact_link(model_version_id: UUID, model_version_artifact_link_name_or_id: Union[str, UUID]) -> None

Deletes a model version to artifact link.

Parameters:

Name Type Description Default
model_version_id UUID

ID of the model version containing the link.

required
model_version_artifact_link_name_or_id Union[str, UUID]

name or ID of the model version to artifact link to be deleted.

required

Raises:

Type Description
KeyError

specified ID or name not found.

Source code in src/zenml/zen_stores/sql_zen_store.py
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
def delete_model_version_artifact_link(
    self,
    model_version_id: UUID,
    model_version_artifact_link_name_or_id: Union[str, UUID],
) -> None:
    """Deletes a model version to artifact link.

    Args:
        model_version_id: ID of the model version containing the link.
        model_version_artifact_link_name_or_id: name or ID of the model
            version to artifact link to be deleted.

    Raises:
        KeyError: specified ID or name not found.
    """
    with Session(self.engine) as session:
        model_version = self.get_model_version(model_version_id)
        query = select(ModelVersionArtifactSchema).where(
            ModelVersionArtifactSchema.model_version_id == model_version.id
        )
        try:
            UUID(str(model_version_artifact_link_name_or_id))
            query = query.where(
                ModelVersionArtifactSchema.id
                == model_version_artifact_link_name_or_id
            )
        except ValueError:
            query = (
                query.where(
                    ModelVersionArtifactSchema.artifact_version_id
                    == ArtifactVersionSchema.id
                )
                .where(
                    ArtifactVersionSchema.artifact_id == ArtifactSchema.id
                )
                .where(
                    ArtifactSchema.name
                    == model_version_artifact_link_name_or_id
                )
            )

        model_version_artifact_link = session.exec(query).first()
        if model_version_artifact_link is None:
            raise KeyError(
                f"Unable to delete model version link with name or ID "
                f"`{model_version_artifact_link_name_or_id}`: "
                f"No model version link with this name found."
            )

        session.delete(model_version_artifact_link)
        session.commit()
delete_model_version_pipeline_run_link(model_version_id: UUID, model_version_pipeline_run_link_name_or_id: Union[str, UUID]) -> None

Deletes a model version to pipeline run link.

Parameters:

Name Type Description Default
model_version_id UUID

name or ID of the model version containing the link.

required
model_version_pipeline_run_link_name_or_id Union[str, UUID]

name or ID of the model version to pipeline run link to be deleted.

required

Raises:

Type Description
KeyError

specified ID not found.

Source code in src/zenml/zen_stores/sql_zen_store.py
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
def delete_model_version_pipeline_run_link(
    self,
    model_version_id: UUID,
    model_version_pipeline_run_link_name_or_id: Union[str, UUID],
) -> None:
    """Deletes a model version to pipeline run link.

    Args:
        model_version_id: name or ID of the model version containing the
            link.
        model_version_pipeline_run_link_name_or_id: name or ID of the model
            version to pipeline run link to be deleted.

    Raises:
        KeyError: specified ID not found.
    """
    with Session(self.engine) as session:
        model_version = self.get_model_version(
            model_version_id=model_version_id
        )
        query = select(ModelVersionPipelineRunSchema).where(
            ModelVersionPipelineRunSchema.model_version_id
            == model_version.id
        )
        try:
            UUID(str(model_version_pipeline_run_link_name_or_id))
            query = query.where(
                ModelVersionPipelineRunSchema.id
                == model_version_pipeline_run_link_name_or_id
            )
        except ValueError:
            query = query.where(
                ModelVersionPipelineRunSchema.pipeline_run_id
                == PipelineRunSchema.id
            ).where(
                PipelineRunSchema.name
                == model_version_pipeline_run_link_name_or_id
            )

        model_version_pipeline_run_link = session.exec(query).first()
        if model_version_pipeline_run_link is None:
            raise KeyError(
                f"Unable to delete model version link with name "
                f"`{model_version_pipeline_run_link_name_or_id}`: "
                f"No model version link with this name found."
            )

        session.delete(model_version_pipeline_run_link)
        session.commit()
delete_pipeline(pipeline_id: UUID) -> None

Deletes a pipeline.

Parameters:

Name Type Description Default
pipeline_id UUID

The ID of the pipeline to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
def delete_pipeline(self, pipeline_id: UUID) -> None:
    """Deletes a pipeline.

    Args:
        pipeline_id: The ID of the pipeline to delete.
    """
    with Session(self.engine) as session:
        # Check if pipeline with the given ID exists
        pipeline = self._get_schema_by_id(
            resource_id=pipeline_id,
            schema_class=PipelineSchema,
            session=session,
        )

        session.delete(pipeline)
        session.commit()
delete_project(project_name_or_id: Union[str, UUID]) -> None

Deletes a project.

Parameters:

Name Type Description Default
project_name_or_id Union[str, UUID]

Name or ID of the project to delete.

required

Raises:

Type Description
IllegalOperationError

If the project is the default project.

Source code in src/zenml/zen_stores/sql_zen_store.py
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
def delete_project(self, project_name_or_id: Union[str, UUID]) -> None:
    """Deletes a project.

    Args:
        project_name_or_id: Name or ID of the project to delete.

    Raises:
        IllegalOperationError: If the project is the default project.
    """
    with Session(self.engine) as session:
        # Check if project with the given name exists
        project = self._get_schema_by_name_or_id(
            object_name_or_id=project_name_or_id,
            schema_class=ProjectSchema,
            session=session,
        )
        if project.name == self._default_project_name:
            raise IllegalOperationError(
                "The default project cannot be deleted."
            )

        session.delete(project)
        session.commit()
delete_run(run_id: UUID) -> None

Deletes a pipeline run.

Parameters:

Name Type Description Default
run_id UUID

The ID of the pipeline run to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
def delete_run(self, run_id: UUID) -> None:
    """Deletes a pipeline run.

    Args:
        run_id: The ID of the pipeline run to delete.
    """
    with Session(self.engine) as session:
        # Check if pipeline run with the given ID exists
        existing_run = self._get_schema_by_id(
            resource_id=run_id,
            schema_class=PipelineRunSchema,
            session=session,
        )

        # Delete the pipeline run
        session.delete(existing_run)
        session.commit()
delete_run_template(template_id: UUID) -> None

Delete a run template.

Parameters:

Name Type Description Default
template_id UUID

The ID of the template to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
def delete_run_template(self, template_id: UUID) -> None:
    """Delete a run template.

    Args:
        template_id: The ID of the template to delete.
    """
    with Session(self.engine) as session:
        template = self._get_schema_by_id(
            resource_id=template_id,
            schema_class=RunTemplateSchema,
            session=session,
        )

        session.delete(template)
        # We set the reference of all deployments to this template to null
        # manually as we can't have a foreign key there to avoid a cycle
        deployments = session.exec(
            select(PipelineDeploymentSchema).where(
                PipelineDeploymentSchema.template_id == template_id
            )
        ).all()
        for deployment in deployments:
            deployment.template_id = None
            session.add(deployment)

        session.commit()
delete_schedule(schedule_id: UUID) -> None

Deletes a schedule.

Parameters:

Name Type Description Default
schedule_id UUID

The ID of the schedule to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
def delete_schedule(self, schedule_id: UUID) -> None:
    """Deletes a schedule.

    Args:
        schedule_id: The ID of the schedule to delete.
    """
    with Session(self.engine) as session:
        # Check if schedule with the given ID exists
        schedule = self._get_schema_by_id(
            resource_id=schedule_id,
            schema_class=ScheduleSchema,
            session=session,
        )

        # Delete the schedule
        session.delete(schedule)
        session.commit()
delete_secret(secret_id: UUID) -> None

Delete a secret.

Parameters:

Name Type Description Default
secret_id UUID

The id of the secret to delete.

required

Raises:

Type Description
KeyError

if the secret doesn't exist.

Source code in src/zenml/zen_stores/sql_zen_store.py
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
def delete_secret(self, secret_id: UUID) -> None:
    """Delete a secret.

    Args:
        secret_id: The id of the secret to delete.

    Raises:
        KeyError: if the secret doesn't exist.
    """
    with Session(self.engine) as session:
        existing_secret = session.exec(
            select(SecretSchema).where(SecretSchema.id == secret_id)
        ).first()

        if not existing_secret or (
            # Private secrets are only accessible to their owner
            existing_secret.private
            and existing_secret.user.id
            != self._get_active_user(session).id
        ):
            raise KeyError(
                f"Secret with ID {secret_id} not found or is private and "
                "not owned by the current user."
            )

        # Delete the secret values in the configured secrets store
        try:
            self._delete_secret_values(secret_id=secret_id)
        except KeyError:
            # If the secret values don't exist in the secrets store, we don't
            # need to raise an error.
            pass

        secret_in_db = session.exec(
            select(SecretSchema).where(SecretSchema.id == secret_id)
        ).one()
        session.delete(secret_in_db)
        session.commit()
delete_service(service_id: UUID) -> None

Delete a service.

Parameters:

Name Type Description Default
service_id UUID

The ID of the service to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
def delete_service(self, service_id: UUID) -> None:
    """Delete a service.

    Args:
        service_id: The ID of the service to delete.
    """
    with Session(self.engine) as session:
        existing_service = self._get_schema_by_id(
            resource_id=service_id,
            schema_class=ServiceSchema,
            session=session,
        )

        # Delete the service
        session.delete(existing_service)
        session.commit()
delete_service_account(service_account_name_or_id: Union[str, UUID]) -> None

Delete a service account.

Parameters:

Name Type Description Default
service_account_name_or_id Union[str, UUID]

The name or the ID of the service account to delete.

required

Raises:

Type Description
IllegalOperationError

if the service account has already been used to create other resources.

Source code in src/zenml/zen_stores/sql_zen_store.py
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
def delete_service_account(
    self,
    service_account_name_or_id: Union[str, UUID],
) -> None:
    """Delete a service account.

    Args:
        service_account_name_or_id: The name or the ID of the service
            account to delete.

    Raises:
        IllegalOperationError: if the service account has already been used
            to create other resources.
    """
    with Session(self.engine) as session:
        service_account = self._get_account_schema(
            service_account_name_or_id,
            session=session,
            service_account=True,
        )
        # Check if the service account has any resources associated with it
        # and raise an error if it does.
        if self._account_owns_resources(service_account, session=session):
            raise IllegalOperationError(
                "The service account has already been used to create "
                "other resources that it now owns and therefore cannot be "
                "deleted. Please delete all resources owned by the service "
                "account or consider deactivating it instead."
            )

        session.delete(service_account)
        session.commit()
delete_service_connector(service_connector_id: UUID) -> None

Deletes a service connector.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the service connector to delete.

required

Raises:

Type Description
IllegalOperationError

If the service connector is still referenced by one or more stack components.

Source code in src/zenml/zen_stores/sql_zen_store.py
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
def delete_service_connector(self, service_connector_id: UUID) -> None:
    """Deletes a service connector.

    Args:
        service_connector_id: The ID of the service connector to delete.

    Raises:
        IllegalOperationError: If the service connector is still referenced
            by one or more stack components.
    """
    with Session(self.engine) as session:
        service_connector = self._get_schema_by_id(
            resource_id=service_connector_id,
            schema_class=ServiceConnectorSchema,
            session=session,
        )

        if len(service_connector.components) > 0:
            raise IllegalOperationError(
                f"Service connector with ID {service_connector_id} "
                f"cannot be deleted as it is still referenced by "
                f"{len(service_connector.components)} "
                "stack components. Before deleting this service "
                "connector, make sure to remove it from all stack "
                "components."
            )
        else:
            session.delete(service_connector)

        if service_connector.secret_id:
            try:
                self.delete_secret(service_connector.secret_id)
            except KeyError:
                # If the secret doesn't exist anymore, we can ignore
                # this error
                pass

        session.commit()
delete_stack(stack_id: UUID) -> None

Delete a stack.

Parameters:

Name Type Description Default
stack_id UUID

The ID of the stack to delete.

required

Raises:

Type Description
IllegalOperationError

if the stack is a default stack.

Source code in src/zenml/zen_stores/sql_zen_store.py
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
def delete_stack(self, stack_id: UUID) -> None:
    """Delete a stack.

    Args:
        stack_id: The ID of the stack to delete.

    Raises:
        IllegalOperationError: if the stack is a default stack.
    """
    with Session(self.engine) as session:
        stack = self._get_schema_by_id(
            resource_id=stack_id,
            schema_class=StackSchema,
            session=session,
        )
        if stack.name == DEFAULT_STACK_AND_COMPONENT_NAME:
            raise IllegalOperationError(
                "The default stack cannot be deleted."
            )
        session.delete(stack)
        session.commit()
delete_stack_component(component_id: UUID) -> None

Delete a stack component.

Parameters:

Name Type Description Default
component_id UUID

The id of the stack component to delete.

required

Raises:

Type Description
IllegalOperationError

if the stack component is part of one or more stacks, or if it's a default stack component.

Source code in src/zenml/zen_stores/sql_zen_store.py
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
def delete_stack_component(self, component_id: UUID) -> None:
    """Delete a stack component.

    Args:
        component_id: The id of the stack component to delete.

    Raises:
        IllegalOperationError: if the stack component is part of one or
            more stacks, or if it's a default stack component.
    """
    with Session(self.engine) as session:
        stack_component = self._get_schema_by_id(
            resource_id=component_id,
            schema_class=StackComponentSchema,
            session=session,
        )

        if (
            stack_component.name == DEFAULT_STACK_AND_COMPONENT_NAME
            and stack_component.type
            in [
                StackComponentType.ORCHESTRATOR,
                StackComponentType.ARTIFACT_STORE,
            ]
        ):
            raise IllegalOperationError(
                f"The default {stack_component.type} cannot be deleted."
            )

        if len(stack_component.stacks) > 0:
            raise IllegalOperationError(
                f"Stack Component `{stack_component.name}` of type "
                f"`{stack_component.type} cannot be "
                f"deleted as it is part of "
                f"{len(stack_component.stacks)} stacks. "
                f"Before deleting this stack "
                f"component, make sure to remove it "
                f"from all stacks."
            )

        session.delete(stack_component)
        session.commit()
delete_tag(tag_name_or_id: Union[str, UUID]) -> None

Deletes a tag.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

name or id of the tag to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
def delete_tag(
    self,
    tag_name_or_id: Union[str, UUID],
) -> None:
    """Deletes a tag.

    Args:
        tag_name_or_id: name or id of the tag to delete.
    """
    with Session(self.engine) as session:
        tag = self._get_tag_schema(
            tag_name_or_id=tag_name_or_id,
            session=session,
        )
        session.delete(tag)
        session.commit()
delete_tag_resource(tag_resource: TagResourceRequest) -> None

Deletes a tag resource relationship.

Parameters:

Name Type Description Default
tag_resource TagResourceRequest

The tag resource relationship to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
def delete_tag_resource(
    self,
    tag_resource: TagResourceRequest,
) -> None:
    """Deletes a tag resource relationship.

    Args:
        tag_resource: The tag resource relationship to delete.
    """
    self.batch_delete_tag_resource(tag_resources=[tag_resource])
delete_trigger(trigger_id: UUID) -> None

Delete a trigger.

Parameters:

Name Type Description Default
trigger_id UUID

The ID of the trigger to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
def delete_trigger(self, trigger_id: UUID) -> None:
    """Delete a trigger.

    Args:
        trigger_id: The ID of the trigger to delete.
    """
    with Session(self.engine) as session:
        trigger = self._get_schema_by_id(
            resource_id=trigger_id,
            schema_class=TriggerSchema,
            session=session,
        )
        session.delete(trigger)
        session.commit()
delete_trigger_execution(trigger_execution_id: UUID) -> None

Delete a trigger execution.

Parameters:

Name Type Description Default
trigger_execution_id UUID

The ID of the trigger execution to delete.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
def delete_trigger_execution(self, trigger_execution_id: UUID) -> None:
    """Delete a trigger execution.

    Args:
        trigger_execution_id: The ID of the trigger execution to delete.
    """
    with Session(self.engine) as session:
        execution = self._get_schema_by_id(
            resource_id=trigger_execution_id,
            schema_class=TriggerExecutionSchema,
            session=session,
        )

        session.delete(execution)
        session.commit()
delete_user(user_name_or_id: Union[str, UUID]) -> None

Deletes a user.

Parameters:

Name Type Description Default
user_name_or_id Union[str, UUID]

The name or the ID of the user to delete.

required

Raises:

Type Description
IllegalOperationError

If the user is the default user account or if the user already owns resources.

Source code in src/zenml/zen_stores/sql_zen_store.py
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
def delete_user(self, user_name_or_id: Union[str, UUID]) -> None:
    """Deletes a user.

    Args:
        user_name_or_id: The name or the ID of the user to delete.

    Raises:
        IllegalOperationError: If the user is the default user account or
            if the user already owns resources.
    """
    with Session(self.engine) as session:
        user = self._get_account_schema(
            user_name_or_id, session=session, service_account=False
        )
        if user.is_admin:
            # Don't allow the last admin to be deleted
            admin_accounts_count = session.scalar(
                select(func.count(UserSchema.id)).where(  # type: ignore[arg-type]
                    UserSchema.is_admin == True  # noqa: E712
                )
            )
            if admin_accounts_count == 1:
                raise IllegalOperationError(
                    "There has to be at least one admin account configured "
                    "on your system. This is the only admin account and "
                    "therefore it cannot be deleted."
                )
        if self._account_owns_resources(user, session=session):
            raise IllegalOperationError(
                "The user account has already been used to create "
                "other resources that it now owns and therefore cannot be "
                "deleted. Please delete all resources owned by the user "
                "account or consider deactivating it instead."
            )

        session.delete(user)
        session.commit()
entity_exists(entity_id: UUID, schema_class: Type[AnySchema]) -> bool

Check whether an entity exists in the database.

Parameters:

Name Type Description Default
entity_id UUID

The ID of the entity to check.

required
schema_class Type[AnySchema]

The schema class.

required

Returns:

Type Description
bool

If the entity exists.

Source code in src/zenml/zen_stores/sql_zen_store.py
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
def entity_exists(
    self, entity_id: UUID, schema_class: Type[AnySchema]
) -> bool:
    """Check whether an entity exists in the database.

    Args:
        entity_id: The ID of the entity to check.
        schema_class: The schema class.

    Returns:
        If the entity exists.
    """
    with Session(self.engine) as session:
        schema = session.exec(
            select(schema_class.id).where(schema_class.id == entity_id)
        ).first()

        return False if schema is None else True
filter_and_paginate(session: Session, query: Union[Select[Any], SelectOfScalar[Any]], table: Type[AnySchema], filter_model: BaseFilter, custom_schema_to_model_conversion: Optional[Callable[..., AnyResponse]] = None, custom_fetch: Optional[Callable[[Session, Union[Select[Any], SelectOfScalar[Any]], BaseFilter], Sequence[Any]]] = None, hydrate: bool = False) -> Page[AnyResponse] classmethod

Given a query, return a Page instance with a list of filtered Models.

Parameters:

Name Type Description Default
session Session

The SQLModel Session

required
query Union[Select[Any], SelectOfScalar[Any]]

The query to execute

required
table Type[AnySchema]

The table to select from

required
filter_model BaseFilter

The filter to use, including pagination and sorting

required
custom_schema_to_model_conversion Optional[Callable[..., AnyResponse]]

Callable to convert the schema into a model. This is used if the Model contains additional data that is not explicitly stored as a field or relationship on the model.

None
custom_fetch Optional[Callable[[Session, Union[Select[Any], SelectOfScalar[Any]], BaseFilter], Sequence[Any]]]

Custom callable to use to fetch items from the database for a given query. This is used if the items fetched from the database need to be processed differently (e.g. to perform additional filtering). The callable should take a Session, a Select query and a BaseFilterModel filter as arguments and return a List of items.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[AnyResponse]

The Domain Model representation of the DB resource

Raises:

Type Description
ValueError

if the filtered page number is out of bounds.

RuntimeError

if the schema does not have a to_model method.

Source code in src/zenml/zen_stores/sql_zen_store.py
 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
@classmethod
def filter_and_paginate(
    cls,
    session: Session,
    query: Union[Select[Any], SelectOfScalar[Any]],
    table: Type[AnySchema],
    filter_model: BaseFilter,
    custom_schema_to_model_conversion: Optional[
        Callable[..., AnyResponse]
    ] = None,
    custom_fetch: Optional[
        Callable[
            [
                Session,
                Union[Select[Any], SelectOfScalar[Any]],
                BaseFilter,
            ],
            Sequence[Any],
        ]
    ] = None,
    hydrate: bool = False,
) -> Page[AnyResponse]:
    """Given a query, return a Page instance with a list of filtered Models.

    Args:
        session: The SQLModel Session
        query: The query to execute
        table: The table to select from
        filter_model: The filter to use, including pagination and sorting
        custom_schema_to_model_conversion: Callable to convert the schema
            into a model. This is used if the Model contains additional
            data that is not explicitly stored as a field or relationship
            on the model.
        custom_fetch: Custom callable to use to fetch items from the
            database for a given query. This is used if the items fetched
            from the database need to be processed differently (e.g. to
            perform additional filtering). The callable should take a
            `Session`, a `Select` query and a `BaseFilterModel` filter as
            arguments and return a `List` of items.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The Domain Model representation of the DB resource

    Raises:
        ValueError: if the filtered page number is out of bounds.
        RuntimeError: if the schema does not have a `to_model` method.
    """
    query = filter_model.apply_filter(query=query, table=table)
    query = filter_model.apply_sorting(query=query, table=table)
    query = query.distinct()

    # Get the total amount of items in the database for a given query
    custom_fetch_result: Optional[Sequence[Any]] = None
    if custom_fetch:
        custom_fetch_result = custom_fetch(session, query, filter_model)
        total = len(custom_fetch_result)
    else:
        result = session.scalar(
            select(func.count()).select_from(
                query.options(noload("*")).subquery()
            )
        )

        if result:
            total = result
        else:
            total = 0

    # Get the total amount of pages in the database for a given query
    if total == 0:
        total_pages = 1
    else:
        total_pages = math.ceil(total / filter_model.size)

    if filter_model.page > total_pages:
        raise ValueError(
            f"Invalid page {filter_model.page}. The requested page size is "
            f"{filter_model.size} and there are a total of {total} items "
            f"for this query. The maximum page value therefore is "
            f"{total_pages}."
        )

    # Get a page of the actual data
    item_schemas: Sequence[AnySchema]
    if custom_fetch:
        assert custom_fetch_result is not None
        item_schemas = custom_fetch_result
        # select the items in the current page
        item_schemas = item_schemas[
            filter_model.offset : filter_model.offset + filter_model.size
        ]
    else:
        item_schemas = session.exec(
            query.limit(filter_model.size).offset(filter_model.offset)
        ).all()

    # Convert this page of items from schemas to models.
    items: List[AnyResponse] = []
    for schema in item_schemas:
        # If a custom conversion function is provided, use it.
        if custom_schema_to_model_conversion:
            items.append(custom_schema_to_model_conversion(schema))
            continue
        # Otherwise, try to use the `to_model` method of the schema.
        to_model = getattr(schema, "to_model", None)
        if callable(to_model):
            items.append(
                to_model(include_metadata=hydrate, include_resources=True)
            )
            continue
        # If neither of the above work, raise an error.
        raise RuntimeError(
            f"Cannot convert schema `{schema.__class__.__name__}` to model "
            "since it does not have a `to_model` method."
        )

    return Page[Any](
        total=total,
        total_pages=total_pages,
        items=items,
        index=filter_model.page,
        max_size=filter_model.size,
    )
get_action(action_id: UUID, hydrate: bool = True) -> ActionResponse

Get an action by ID.

Parameters:

Name Type Description Default
action_id UUID

The ID of the action to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ActionResponse

The action.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def get_action(
    self,
    action_id: UUID,
    hydrate: bool = True,
) -> ActionResponse:
    """Get an action by ID.

    Args:
        action_id: The ID of the action to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The action.
    """
    with Session(self.engine) as session:
        action = self._get_schema_by_id(
            resource_id=action_id,
            schema_class=ActionSchema,
            session=session,
        )

        return action.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_api_key(service_account_id: UUID, api_key_name_or_id: Union[str, UUID], hydrate: bool = True) -> APIKeyResponse

Get an API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to fetch the API key.

required
api_key_name_or_id Union[str, UUID]

The name or ID of the API key to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
APIKeyResponse

The API key with the given ID.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def get_api_key(
    self,
    service_account_id: UUID,
    api_key_name_or_id: Union[str, UUID],
    hydrate: bool = True,
) -> APIKeyResponse:
    """Get an API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to fetch
            the API key.
        api_key_name_or_id: The name or ID of the API key to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The API key with the given ID.
    """
    with Session(self.engine) as session:
        api_key = self._get_api_key(
            service_account_id=service_account_id,
            api_key_name_or_id=api_key_name_or_id,
            session=session,
        )
        return api_key.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_artifact(artifact_id: UUID, hydrate: bool = True) -> ArtifactResponse

Gets an artifact.

Parameters:

Name Type Description Default
artifact_id UUID

The ID of the artifact to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ArtifactResponse

The artifact.

Source code in src/zenml/zen_stores/sql_zen_store.py
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
def get_artifact(
    self, artifact_id: UUID, hydrate: bool = True
) -> ArtifactResponse:
    """Gets an artifact.

    Args:
        artifact_id: The ID of the artifact to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The artifact.
    """
    with Session(self.engine) as session:
        artifact = self._get_schema_by_id(
            resource_id=artifact_id,
            schema_class=ArtifactSchema,
            session=session,
        )
        return artifact.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_artifact_version(artifact_version_id: UUID, hydrate: bool = True) -> ArtifactVersionResponse

Gets an artifact version.

Parameters:

Name Type Description Default
artifact_version_id UUID

The ID of the artifact version to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ArtifactVersionResponse

The artifact version.

Source code in src/zenml/zen_stores/sql_zen_store.py
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
def get_artifact_version(
    self, artifact_version_id: UUID, hydrate: bool = True
) -> ArtifactVersionResponse:
    """Gets an artifact version.

    Args:
        artifact_version_id: The ID of the artifact version to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The artifact version.
    """
    with Session(self.engine) as session:
        artifact_version = self._get_schema_by_id(
            resource_id=artifact_version_id,
            schema_class=ArtifactVersionSchema,
            session=session,
        )
        return artifact_version.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_artifact_visualization(artifact_visualization_id: UUID, hydrate: bool = True) -> ArtifactVisualizationResponse

Gets an artifact visualization.

Parameters:

Name Type Description Default
artifact_visualization_id UUID

The ID of the artifact visualization to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ArtifactVisualizationResponse

The artifact visualization.

Source code in src/zenml/zen_stores/sql_zen_store.py
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
def get_artifact_visualization(
    self, artifact_visualization_id: UUID, hydrate: bool = True
) -> ArtifactVisualizationResponse:
    """Gets an artifact visualization.

    Args:
        artifact_visualization_id: The ID of the artifact visualization to
            get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The artifact visualization.
    """
    with Session(self.engine) as session:
        artifact_visualization = self._get_schema_by_id(
            resource_id=artifact_visualization_id,
            schema_class=ArtifactVisualizationSchema,
            session=session,
        )
        return artifact_visualization.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_auth_user(user_name_or_id: Union[str, UUID]) -> UserAuthModel

Gets the auth model to a specific user.

Parameters:

Name Type Description Default
user_name_or_id Union[str, UUID]

The name or ID of the user to get.

required

Returns:

Type Description
UserAuthModel

The requested user, if it was found.

Source code in src/zenml/zen_stores/sql_zen_store.py
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
def get_auth_user(
    self, user_name_or_id: Union[str, UUID]
) -> UserAuthModel:
    """Gets the auth model to a specific user.

    Args:
        user_name_or_id: The name or ID of the user to get.

    Returns:
        The requested user, if it was found.
    """
    with Session(self.engine) as session:
        user = self._get_account_schema(
            user_name_or_id, session=session, service_account=False
        )
        return UserAuthModel(
            id=user.id,
            name=user.name,
            full_name=user.full_name,
            email_opted_in=user.email_opted_in,
            active=user.active,
            created=user.created,
            updated=user.updated,
            password=user.password,
            activation_token=user.activation_token,
            is_service_account=False,
        )
get_authorized_device(device_id: UUID, hydrate: bool = True) -> OAuthDeviceResponse

Gets a specific OAuth 2.0 authorized device.

Parameters:

Name Type Description Default
device_id UUID

The ID of the device to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
OAuthDeviceResponse

The requested device, if it was found.

Source code in src/zenml/zen_stores/sql_zen_store.py
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
def get_authorized_device(
    self, device_id: UUID, hydrate: bool = True
) -> OAuthDeviceResponse:
    """Gets a specific OAuth 2.0 authorized device.

    Args:
        device_id: The ID of the device to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested device, if it was found.
    """
    with Session(self.engine) as session:
        device = self._get_schema_by_id(
            resource_id=device_id,
            schema_class=OAuthDeviceSchema,
            session=session,
            resource_type="authorized device",
        )

        return device.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_build(build_id: UUID, hydrate: bool = True) -> PipelineBuildResponse

Get a build with a given ID.

Parameters:

Name Type Description Default
build_id UUID

ID of the build.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineBuildResponse

The build.

Source code in src/zenml/zen_stores/sql_zen_store.py
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
def get_build(
    self, build_id: UUID, hydrate: bool = True
) -> PipelineBuildResponse:
    """Get a build with a given ID.

    Args:
        build_id: ID of the build.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The build.
    """
    with Session(self.engine) as session:
        # Check if build with the given ID exists
        build = self._get_schema_by_id(
            resource_id=build_id,
            schema_class=PipelineBuildSchema,
            session=session,
        )
        return build.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_code_reference(code_reference_id: UUID, hydrate: bool = True) -> CodeReferenceResponse

Gets a code reference.

Parameters:

Name Type Description Default
code_reference_id UUID

The ID of the code reference to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
CodeReferenceResponse

The code reference.

Source code in src/zenml/zen_stores/sql_zen_store.py
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
def get_code_reference(
    self, code_reference_id: UUID, hydrate: bool = True
) -> CodeReferenceResponse:
    """Gets a code reference.

    Args:
        code_reference_id: The ID of the code reference to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The code reference.
    """
    with Session(self.engine) as session:
        code_reference = self._get_schema_by_id(
            resource_id=code_reference_id,
            schema_class=CodeReferenceSchema,
            session=session,
        )
        return code_reference.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_code_repository(code_repository_id: UUID, hydrate: bool = True) -> CodeRepositoryResponse

Gets a specific code repository.

Parameters:

Name Type Description Default
code_repository_id UUID

The ID of the code repository to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
CodeRepositoryResponse

The requested code repository, if it was found.

Source code in src/zenml/zen_stores/sql_zen_store.py
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
def get_code_repository(
    self, code_repository_id: UUID, hydrate: bool = True
) -> CodeRepositoryResponse:
    """Gets a specific code repository.

    Args:
        code_repository_id: The ID of the code repository to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested code repository, if it was found.
    """
    with Session(self.engine) as session:
        repo = self._get_schema_by_id(
            resource_id=code_repository_id,
            schema_class=CodeRepositorySchema,
            session=session,
        )

        return repo.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_deployment(deployment_id: UUID, hydrate: bool = True) -> PipelineDeploymentResponse

Get a deployment with a given ID.

Parameters:

Name Type Description Default
deployment_id UUID

ID of the deployment.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineDeploymentResponse

The deployment.

Source code in src/zenml/zen_stores/sql_zen_store.py
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
def get_deployment(
    self, deployment_id: UUID, hydrate: bool = True
) -> PipelineDeploymentResponse:
    """Get a deployment with a given ID.

    Args:
        deployment_id: ID of the deployment.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The deployment.
    """
    with Session(self.engine) as session:
        # Check if deployment with the given ID exists
        deployment = self._get_schema_by_id(
            resource_id=deployment_id,
            schema_class=PipelineDeploymentSchema,
            session=session,
        )

        return deployment.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_deployment_id() -> UUID

Get the ID of the deployment.

Returns:

Type Description
UUID

The ID of the deployment.

Raises:

Type Description
KeyError

If the deployment ID could not be loaded from the database.

Source code in src/zenml/zen_stores/sql_zen_store.py
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
def get_deployment_id(self) -> UUID:
    """Get the ID of the deployment.

    Returns:
        The ID of the deployment.

    Raises:
        KeyError: If the deployment ID could not be loaded from the
            database.
    """
    # Fetch the deployment ID from the database
    with Session(self.engine) as session:
        identity = session.exec(select(ServerSettingsSchema)).first()

        if identity is None:
            raise KeyError(
                "The deployment ID could not be loaded from the database."
            )
        return identity.id
get_entity_by_id(entity_id: UUID, schema_class: Type[AnySchema]) -> Optional[AnyIdentifiedResponse]

Get an entity by ID.

Parameters:

Name Type Description Default
entity_id UUID

The ID of the entity to get.

required
schema_class Type[AnySchema]

The schema class.

required

Raises:

Type Description
RuntimeError

If the schema to model conversion failed.

Returns:

Type Description
Optional[AnyIdentifiedResponse]

The entity if it exists, None otherwise

Source code in src/zenml/zen_stores/sql_zen_store.py
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
def get_entity_by_id(
    self, entity_id: UUID, schema_class: Type[AnySchema]
) -> Optional[AnyIdentifiedResponse]:
    """Get an entity by ID.

    Args:
        entity_id: The ID of the entity to get.
        schema_class: The schema class.

    Raises:
        RuntimeError: If the schema to model conversion failed.

    Returns:
        The entity if it exists, None otherwise
    """
    with Session(self.engine) as session:
        schema = session.exec(
            select(schema_class).where(schema_class.id == entity_id)
        ).first()

        if not schema:
            return None

        to_model = getattr(schema, "to_model", None)
        if callable(to_model):
            return cast(
                AnyIdentifiedResponse,
                to_model(include_metadata=True, include_resources=True),
            )
        else:
            raise RuntimeError("Unable to convert schema to model.")
get_event_source(event_source_id: UUID, hydrate: bool = True) -> EventSourceResponse

Get an event_source by ID.

Parameters:

Name Type Description Default
event_source_id UUID

The ID of the event_source to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
EventSourceResponse

The event_source.

Source code in src/zenml/zen_stores/sql_zen_store.py
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
def get_event_source(
    self,
    event_source_id: UUID,
    hydrate: bool = True,
) -> EventSourceResponse:
    """Get an event_source by ID.

    Args:
        event_source_id: The ID of the event_source to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The event_source.
    """
    with Session(self.engine) as session:
        event_source = self._get_schema_by_id(
            resource_id=event_source_id,
            schema_class=EventSourceSchema,
            session=session,
        )
        return event_source.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_flavor(flavor_id: UUID, hydrate: bool = True) -> FlavorResponse

Get a flavor by ID.

Parameters:

Name Type Description Default
flavor_id UUID

The ID of the flavor to fetch.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
FlavorResponse

The stack component flavor.

Source code in src/zenml/zen_stores/sql_zen_store.py
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
def get_flavor(
    self, flavor_id: UUID, hydrate: bool = True
) -> FlavorResponse:
    """Get a flavor by ID.

    Args:
        flavor_id: The ID of the flavor to fetch.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The stack component flavor.
    """
    with Session(self.engine) as session:
        flavor_in_db = self._get_schema_by_id(
            resource_id=flavor_id,
            schema_class=FlavorSchema,
            session=session,
        )
        return flavor_in_db.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_internal_api_key(api_key_id: UUID, hydrate: bool = True) -> APIKeyInternalResponse

Get internal details for an API key by its unique ID.

Parameters:

Name Type Description Default
api_key_id UUID

The ID of the API key to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
APIKeyInternalResponse

The internal details for the API key with the given ID.

Raises:

Type Description
KeyError

if the API key doesn't exist.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def get_internal_api_key(
    self, api_key_id: UUID, hydrate: bool = True
) -> APIKeyInternalResponse:
    """Get internal details for an API key by its unique ID.

    Args:
        api_key_id: The ID of the API key to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The internal details for the API key with the given ID.

    Raises:
        KeyError: if the API key doesn't exist.
    """
    with Session(self.engine) as session:
        api_key = session.exec(
            select(APIKeySchema).where(APIKeySchema.id == api_key_id)
        ).first()
        if api_key is None:
            raise KeyError(f"API key with ID {api_key_id} not found.")
        return api_key.to_internal_model(
            include_metadata=hydrate, include_resources=True
        )
get_internal_authorized_device(device_id: Optional[UUID] = None, client_id: Optional[UUID] = None, hydrate: bool = True) -> OAuthDeviceInternalResponse

Gets a specific OAuth 2.0 authorized device for internal use.

Parameters:

Name Type Description Default
client_id Optional[UUID]

The client ID of the device to get.

None
device_id Optional[UUID]

The ID of the device to get.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
OAuthDeviceInternalResponse

The requested device, if it was found.

Raises:

Type Description
KeyError

If no device with the given client ID exists.

ValueError

If neither device ID nor client ID are provided.

Source code in src/zenml/zen_stores/sql_zen_store.py
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
def get_internal_authorized_device(
    self,
    device_id: Optional[UUID] = None,
    client_id: Optional[UUID] = None,
    hydrate: bool = True,
) -> OAuthDeviceInternalResponse:
    """Gets a specific OAuth 2.0 authorized device for internal use.

    Args:
        client_id: The client ID of the device to get.
        device_id: The ID of the device to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested device, if it was found.

    Raises:
        KeyError: If no device with the given client ID exists.
        ValueError: If neither device ID nor client ID are provided.
    """
    with Session(self.engine) as session:
        if device_id is not None:
            device = session.exec(
                select(OAuthDeviceSchema).where(
                    OAuthDeviceSchema.id == device_id
                )
            ).first()
        elif client_id is not None:
            device = session.exec(
                select(OAuthDeviceSchema).where(
                    OAuthDeviceSchema.client_id == client_id
                )
            ).first()
        else:
            raise ValueError(
                "Either device ID or client ID must be provided."
            )
        if device is None:
            raise KeyError(
                f"Unable to get device with client ID {client_id}: No "
                "device with this client ID found."
            )

        return device.to_internal_model(
            include_metadata=hydrate, include_resources=True
        )
get_logs(logs_id: UUID, hydrate: bool = True) -> LogsResponse

Gets logs with the given ID.

Parameters:

Name Type Description Default
logs_id UUID

The ID of the logs to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
LogsResponse

The logs.

Source code in src/zenml/zen_stores/sql_zen_store.py
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
def get_logs(self, logs_id: UUID, hydrate: bool = True) -> LogsResponse:
    """Gets logs with the given ID.

    Args:
        logs_id: The ID of the logs to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The logs.
    """
    with Session(self.engine) as session:
        logs = self._get_schema_by_id(
            resource_id=logs_id,
            schema_class=LogsSchema,
            session=session,
        )
        return logs.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_model(model_id: UUID, hydrate: bool = True) -> ModelResponse

Get an existing model.

Parameters:

Name Type Description Default
model_id UUID

id of the model to be retrieved.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ModelResponse

The model of interest.

Source code in src/zenml/zen_stores/sql_zen_store.py
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
def get_model(
    self,
    model_id: UUID,
    hydrate: bool = True,
) -> ModelResponse:
    """Get an existing model.

    Args:
        model_id: id of the model to be retrieved.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The model of interest.
    """
    with Session(self.engine) as session:
        model = self._get_schema_by_id(
            resource_id=model_id,
            schema_class=ModelSchema,
            session=session,
        )
        return model.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_model_by_name_or_id(model_name_or_id: Union[str, UUID], project: UUID, hydrate: bool = True) -> ModelResponse

Get a model by name or ID.

Parameters:

Name Type Description Default
model_name_or_id Union[str, UUID]

The name or ID of the model to get.

required
project UUID

The project ID of the model to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ModelResponse

The model.

Source code in src/zenml/zen_stores/sql_zen_store.py
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
def get_model_by_name_or_id(
    self,
    model_name_or_id: Union[str, UUID],
    project: UUID,
    hydrate: bool = True,
) -> ModelResponse:
    """Get a model by name or ID.

    Args:
        model_name_or_id: The name or ID of the model to get.
        project: The project ID of the model to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The model.
    """
    with Session(self.engine) as session:
        model = self._get_schema_by_name_or_id(
            object_name_or_id=model_name_or_id,
            schema_class=ModelSchema,
            session=session,
            project_name_or_id=project,
        )

        return model.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_model_version(model_version_id: UUID, hydrate: bool = True) -> ModelVersionResponse

Get an existing model version.

Parameters:

Name Type Description Default
model_version_id UUID

name, id, stage or number of the model version to be retrieved. If skipped - latest is retrieved.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ModelVersionResponse

The model version of interest.

Source code in src/zenml/zen_stores/sql_zen_store.py
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
def get_model_version(
    self, model_version_id: UUID, hydrate: bool = True
) -> ModelVersionResponse:
    """Get an existing model version.

    Args:
        model_version_id: name, id, stage or number of the model version to
            be retrieved. If skipped - latest is retrieved.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The model version of interest.
    """
    with Session(self.engine) as session:
        model_version = self._get_schema_by_id(
            resource_id=model_version_id,
            schema_class=ModelVersionSchema,
            session=session,
        )

        return model_version.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_onboarding_state() -> List[str]

Get the server onboarding state.

Returns:

Type Description
List[str]

The server onboarding state.

Source code in src/zenml/zen_stores/sql_zen_store.py
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
def get_onboarding_state(self) -> List[str]:
    """Get the server onboarding state.

    Returns:
        The server onboarding state.
    """
    with Session(self.engine) as session:
        settings = self._get_server_settings(session=session)
        if settings.onboarding_state:
            self._cached_onboarding_state = set(
                json.loads(settings.onboarding_state)
            )
            return list(self._cached_onboarding_state)
        else:
            return []
get_or_create_run(pipeline_run: PipelineRunRequest, pre_creation_hook: Optional[Callable[[], None]] = None) -> Tuple[PipelineRunResponse, bool]

Gets or creates a pipeline run.

If a run with the same ID or name already exists, it is returned. Otherwise, a new run is created.

Parameters:

Name Type Description Default
pipeline_run PipelineRunRequest

The pipeline run to get or create.

required
pre_creation_hook Optional[Callable[[], None]]

Optional function to run before creating the pipeline run.

None
noqa: DAR401

Raises: EntityExistsError: If a run with the same name already exists. RuntimeError: If the run fetching failed unexpectedly.

Returns:

Type Description
PipelineRunResponse

The pipeline run, and a boolean indicating whether the run was

bool

created or not.

Source code in src/zenml/zen_stores/sql_zen_store.py
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
def get_or_create_run(
    self,
    pipeline_run: PipelineRunRequest,
    pre_creation_hook: Optional[Callable[[], None]] = None,
) -> Tuple[PipelineRunResponse, bool]:
    """Gets or creates a pipeline run.

    If a run with the same ID or name already exists, it is returned.
    Otherwise, a new run is created.

    Args:
        pipeline_run: The pipeline run to get or create.
        pre_creation_hook: Optional function to run before creating the
            pipeline run.

    # noqa: DAR401
    Raises:
        EntityExistsError: If a run with the same name already exists.
        RuntimeError: If the run fetching failed unexpectedly.

    Returns:
        The pipeline run, and a boolean indicating whether the run was
        created or not.
    """
    with Session(self.engine) as session:
        if pipeline_run.orchestrator_run_id:
            try:
                # We first try the most likely case that the run was already
                # created by a previous step in the same pipeline run.
                return (
                    self._get_run_by_orchestrator_run_id(
                        orchestrator_run_id=pipeline_run.orchestrator_run_id,
                        deployment_id=pipeline_run.deployment,
                        session=session,
                    ),
                    False,
                )
            except KeyError:
                pass

        try:
            return (
                self._replace_placeholder_run(
                    pipeline_run=pipeline_run,
                    pre_replacement_hook=pre_creation_hook,
                    session=session,
                ),
                True,
            )
        except KeyError:
            # We were not able to find/replace a placeholder run. This could
            # be due to one of the following three reasons:
            # (1) There never was a placeholder run for the deployment. This
            #     is the case if the user ran the pipeline on a schedule.
            # (2) There was a placeholder run, but a previous pipeline run
            #     already used it. This is the case if users rerun a
            #     pipeline run e.g. from the orchestrator UI, as they will
            #     use the same deployment_id with a new orchestrator_run_id.
            # (3) A step of the same pipeline run already replaced the
            #     placeholder run.
            pass

        try:
            # We now try to create a new run. The following will happen in
            # the three cases described above:
            # (1) The behavior depends on whether we're the first step of
            #     the pipeline run that's trying to create the run. If yes,
            #     the `self._create_run(...)` call will succeed. If no, a
            #     run with the same deployment_id and orchestrator_run_id
            #     already exists and the `self._create_run(...)` call will
            #     fail due to the unique constraint on those columns.
            # (2) Same as (1).
            # (3) A step of the same pipeline run replaced the placeholder
            #     run, which now contains the deployment_id and
            #     orchestrator_run_id of the run that we're trying to
            #     create.
            #     -> The `self._create_run(...)` call will fail due to the
            #     unique constraint on those columns.
            if pre_creation_hook:
                pre_creation_hook()
            return self._create_run(pipeline_run, session=session), True
        except EntityExistsError as create_error:
            if not pipeline_run.orchestrator_run_id:
                raise
            # Creating the run failed because
            # - a run with the same deployment_id and orchestrator_run_id
            #   exists. We now fetch and return that run.
            # - a run with the same name already exists. This could be
            #   either a different run (in which case we want to fail) or a
            #   run created by a step of the same pipeline run (in which
            #   case we want to return it).
            try:
                return (
                    self._get_run_by_orchestrator_run_id(
                        orchestrator_run_id=pipeline_run.orchestrator_run_id,
                        deployment_id=pipeline_run.deployment,
                        session=session,
                    ),
                    False,
                )
            except KeyError:
                # We should only get here if the run creation failed because
                # of a name conflict. We raise the error that happened
                # during creation in any case to forward the error message
                # to the user.
                raise create_error
get_pipeline(pipeline_id: UUID, hydrate: bool = True) -> PipelineResponse

Get a pipeline with a given ID.

Parameters:

Name Type Description Default
pipeline_id UUID

ID of the pipeline.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineResponse

The pipeline.

Source code in src/zenml/zen_stores/sql_zen_store.py
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
def get_pipeline(
    self, pipeline_id: UUID, hydrate: bool = True
) -> PipelineResponse:
    """Get a pipeline with a given ID.

    Args:
        pipeline_id: ID of the pipeline.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The pipeline.
    """
    with Session(self.engine) as session:
        # Check if pipeline with the given ID exists
        pipeline = self._get_schema_by_id(
            resource_id=pipeline_id,
            schema_class=PipelineSchema,
            session=session,
        )
        return pipeline.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_project(project_name_or_id: Union[str, UUID], hydrate: bool = True) -> ProjectResponse

Get an existing project by name or ID.

Parameters:

Name Type Description Default
project_name_or_id Union[str, UUID]

Name or ID of the project to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ProjectResponse

The requested project if one was found.

Source code in src/zenml/zen_stores/sql_zen_store.py
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
def get_project(
    self, project_name_or_id: Union[str, UUID], hydrate: bool = True
) -> ProjectResponse:
    """Get an existing project by name or ID.

    Args:
        project_name_or_id: Name or ID of the project to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested project if one was found.
    """
    with Session(self.engine) as session:
        project = self._get_schema_by_name_or_id(
            object_name_or_id=project_name_or_id,
            schema_class=ProjectSchema,
            session=session,
        )
    return project.to_model(
        include_metadata=hydrate, include_resources=True
    )
get_run(run_id: UUID, hydrate: bool = True) -> PipelineRunResponse

Gets a pipeline run.

Parameters:

Name Type Description Default
run_id UUID

The ID of the pipeline run to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineRunResponse

The pipeline run.

Source code in src/zenml/zen_stores/sql_zen_store.py
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
def get_run(
    self, run_id: UUID, hydrate: bool = True
) -> PipelineRunResponse:
    """Gets a pipeline run.

    Args:
        run_id: The ID of the pipeline run to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The pipeline run.
    """
    with Session(self.engine) as session:
        run = self._get_schema_by_id(
            resource_id=run_id,
            schema_class=PipelineRunSchema,
            session=session,
        )
        return run.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_run_step(step_run_id: UUID, hydrate: bool = True) -> StepRunResponse

Get a step run by ID.

Parameters:

Name Type Description Default
step_run_id UUID

The ID of the step run to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
StepRunResponse

The step run.

Source code in src/zenml/zen_stores/sql_zen_store.py
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
def get_run_step(
    self, step_run_id: UUID, hydrate: bool = True
) -> StepRunResponse:
    """Get a step run by ID.

    Args:
        step_run_id: The ID of the step run to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The step run.
    """
    with Session(self.engine) as session:
        step_run = self._get_schema_by_id(
            resource_id=step_run_id,
            schema_class=StepRunSchema,
            session=session,
        )
        return step_run.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_run_template(template_id: UUID, hydrate: bool = True) -> RunTemplateResponse

Get a run template with a given ID.

Parameters:

Name Type Description Default
template_id UUID

ID of the template.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
RunTemplateResponse

The template.

Source code in src/zenml/zen_stores/sql_zen_store.py
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
def get_run_template(
    self, template_id: UUID, hydrate: bool = True
) -> RunTemplateResponse:
    """Get a run template with a given ID.

    Args:
        template_id: ID of the template.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The template.
    """
    with Session(self.engine) as session:
        template = self._get_schema_by_id(
            resource_id=template_id,
            schema_class=RunTemplateSchema,
            session=session,
        )
        return template.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_schedule(schedule_id: UUID, hydrate: bool = True) -> ScheduleResponse

Get a schedule with a given ID.

Parameters:

Name Type Description Default
schedule_id UUID

ID of the schedule.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ScheduleResponse

The schedule.

Source code in src/zenml/zen_stores/sql_zen_store.py
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
def get_schedule(
    self, schedule_id: UUID, hydrate: bool = True
) -> ScheduleResponse:
    """Get a schedule with a given ID.

    Args:
        schedule_id: ID of the schedule.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The schedule.
    """
    with Session(self.engine) as session:
        # Check if schedule with the given ID exists
        schedule = self._get_schema_by_id(
            resource_id=schedule_id,
            schema_class=ScheduleSchema,
            session=session,
        )
        return schedule.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_secret(secret_id: UUID, hydrate: bool = True) -> SecretResponse

Get a secret by ID.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret to fetch.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
SecretResponse

The secret.

Raises:

Type Description
KeyError

if the secret doesn't exist.

Source code in src/zenml/zen_stores/sql_zen_store.py
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
def get_secret(
    self, secret_id: UUID, hydrate: bool = True
) -> SecretResponse:
    """Get a secret by ID.

    Args:
        secret_id: The ID of the secret to fetch.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The secret.

    Raises:
        KeyError: if the secret doesn't exist.
    """
    with Session(self.engine) as session:
        secret_in_db = session.exec(
            select(SecretSchema).where(SecretSchema.id == secret_id)
        ).first()
        if (
            secret_in_db is None
            # Private secrets are only accessible to their owner
            or secret_in_db.private
            and secret_in_db.user.id != self._get_active_user(session).id
        ):
            raise KeyError(
                f"Secret with ID {secret_id} not found or is private and "
                "not owned by the current user."
            )

        secret_model = secret_in_db.to_model(
            include_metadata=hydrate, include_resources=True
        )

    secret_model.set_secrets(self._get_secret_values(secret_id=secret_id))

    return secret_model
get_server_settings(hydrate: bool = True) -> ServerSettingsResponse

Get the server settings.

Parameters:

Name Type Description Default
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServerSettingsResponse

The server settings.

Source code in src/zenml/zen_stores/sql_zen_store.py
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
def get_server_settings(
    self, hydrate: bool = True
) -> ServerSettingsResponse:
    """Get the server settings.

    Args:
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The server settings.
    """
    with Session(self.engine) as session:
        settings = self._get_server_settings(session=session)
        return settings.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_service(service_id: UUID, hydrate: bool = True) -> ServiceResponse

Get a service.

Parameters:

Name Type Description Default
service_id UUID

The ID of the service to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServiceResponse

The service.

Source code in src/zenml/zen_stores/sql_zen_store.py
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
def get_service(
    self, service_id: UUID, hydrate: bool = True
) -> ServiceResponse:
    """Get a service.

    Args:
        service_id: The ID of the service to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The service.
    """
    with Session(self.engine) as session:
        service = self._get_schema_by_id(
            resource_id=service_id,
            schema_class=ServiceSchema,
            session=session,
        )
        return service.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_service_account(service_account_name_or_id: Union[str, UUID], hydrate: bool = True) -> ServiceAccountResponse

Gets a specific service account.

Raises a KeyError in case a service account with that id does not exist.

Parameters:

Name Type Description Default
service_account_name_or_id Union[str, UUID]

The name or ID of the service account to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServiceAccountResponse

The requested service account, if it was found.

Source code in src/zenml/zen_stores/sql_zen_store.py
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
def get_service_account(
    self,
    service_account_name_or_id: Union[str, UUID],
    hydrate: bool = True,
) -> ServiceAccountResponse:
    """Gets a specific service account.

    Raises a KeyError in case a service account with that id does not exist.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested service account, if it was found.
    """
    with Session(self.engine) as session:
        account = self._get_account_schema(
            service_account_name_or_id,
            session=session,
            service_account=True,
        )

        return account.to_service_account_model(
            include_metadata=hydrate, include_resources=True
        )
get_service_connector(service_connector_id: UUID, hydrate: bool = True) -> ServiceConnectorResponse

Gets a specific service connector.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the service connector to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServiceConnectorResponse

The requested service connector, if it was found.

Source code in src/zenml/zen_stores/sql_zen_store.py
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
def get_service_connector(
    self, service_connector_id: UUID, hydrate: bool = True
) -> ServiceConnectorResponse:
    """Gets a specific service connector.

    Args:
        service_connector_id: The ID of the service connector to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested service connector, if it was found.
    """
    with Session(self.engine) as session:
        service_connector = self._get_schema_by_id(
            resource_id=service_connector_id,
            schema_class=ServiceConnectorSchema,
            session=session,
        )

        connector = service_connector.to_model(
            include_metadata=hydrate, include_resources=True
        )
        self._populate_connector_type(connector)
        return connector
get_service_connector_client(service_connector_id: UUID, resource_type: Optional[str] = None, resource_id: Optional[str] = None) -> ServiceConnectorResponse

Get a service connector client for a service connector and given resource.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the base service connector to use.

required
resource_type Optional[str]

The type of resource to get a client for.

None
resource_id Optional[str]

The ID of the resource to get a client for.

None

Returns:

Type Description
ServiceConnectorResponse

A service connector client that can be used to access the given

ServiceConnectorResponse

resource.

Source code in src/zenml/zen_stores/sql_zen_store.py
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
def get_service_connector_client(
    self,
    service_connector_id: UUID,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
) -> ServiceConnectorResponse:
    """Get a service connector client for a service connector and given resource.

    Args:
        service_connector_id: The ID of the base service connector to use.
        resource_type: The type of resource to get a client for.
        resource_id: The ID of the resource to get a client for.

    Returns:
        A service connector client that can be used to access the given
        resource.
    """
    connector = self.get_service_connector(service_connector_id)

    connector_instance = service_connector_registry.instantiate_connector(
        model=connector
    )

    # Fetch the connector client
    connector_client = connector_instance.get_connector_client(
        resource_type=resource_type,
        resource_id=resource_id,
    )

    # Return the model for the connector client
    connector = connector_client.to_response_model(
        user=connector.user,
        description=connector.description,
        labels=connector.labels,
    )

    self._populate_connector_type(connector)

    return connector
get_service_connector_type(connector_type: str) -> ServiceConnectorTypeModel

Returns the requested service connector type.

Parameters:

Name Type Description Default
connector_type str

the service connector type identifier.

required

Returns:

Type Description
ServiceConnectorTypeModel

The requested service connector type.

Source code in src/zenml/zen_stores/sql_zen_store.py
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
def get_service_connector_type(
    self,
    connector_type: str,
) -> ServiceConnectorTypeModel:
    """Returns the requested service connector type.

    Args:
        connector_type: the service connector type identifier.

    Returns:
        The requested service connector type.
    """
    return service_connector_registry.get_service_connector_type(
        connector_type
    )
get_stack(stack_id: UUID, hydrate: bool = True) -> StackResponse

Get a stack by its unique ID.

Parameters:

Name Type Description Default
stack_id UUID

The ID of the stack to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
StackResponse

The stack with the given ID.

Source code in src/zenml/zen_stores/sql_zen_store.py
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
def get_stack(self, stack_id: UUID, hydrate: bool = True) -> StackResponse:
    """Get a stack by its unique ID.

    Args:
        stack_id: The ID of the stack to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The stack with the given ID.
    """
    with Session(self.engine) as session:
        stack = self._get_schema_by_id(
            resource_id=stack_id,
            schema_class=StackSchema,
            session=session,
        )
        return stack.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_stack_component(component_id: UUID, hydrate: bool = True) -> ComponentResponse

Get a stack component by ID.

Parameters:

Name Type Description Default
component_id UUID

The ID of the stack component to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ComponentResponse

The stack component.

Source code in src/zenml/zen_stores/sql_zen_store.py
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
def get_stack_component(
    self, component_id: UUID, hydrate: bool = True
) -> ComponentResponse:
    """Get a stack component by ID.

    Args:
        component_id: The ID of the stack component to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The stack component.
    """
    with Session(self.engine) as session:
        stack_component = self._get_schema_by_id(
            resource_id=component_id,
            schema_class=StackComponentSchema,
            session=session,
        )

        return stack_component.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_stack_deployment_config(provider: StackDeploymentProvider, stack_name: str, location: Optional[str] = None) -> StackDeploymentConfig

Return the cloud provider console URL and configuration needed to deploy the ZenML stack.

Parameters:

Name Type Description Default
provider StackDeploymentProvider

The stack deployment provider.

required
stack_name str

The name of the stack.

required
location Optional[str]

The location where the stack should be deployed.

None

Raises:

Type Description
NotImplementedError

Stack deployments are not supported by the local ZenML deployment.

Source code in src/zenml/zen_stores/sql_zen_store.py
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
def get_stack_deployment_config(
    self,
    provider: StackDeploymentProvider,
    stack_name: str,
    location: Optional[str] = None,
) -> StackDeploymentConfig:
    """Return the cloud provider console URL and configuration needed to deploy the ZenML stack.

    Args:
        provider: The stack deployment provider.
        stack_name: The name of the stack.
        location: The location where the stack should be deployed.

    Raises:
        NotImplementedError: Stack deployments are not supported by the
            local ZenML deployment.
    """
    raise NotImplementedError(
        "Stack deployments are not supported by local ZenML deployments."
    )
get_stack_deployment_info(provider: StackDeploymentProvider) -> StackDeploymentInfo

Get information about a stack deployment provider.

Parameters:

Name Type Description Default
provider StackDeploymentProvider

The stack deployment provider.

required

Raises:

Type Description
NotImplementedError

Stack deployments are not supported by the local ZenML deployment.

Source code in src/zenml/zen_stores/sql_zen_store.py
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
def get_stack_deployment_info(
    self,
    provider: StackDeploymentProvider,
) -> StackDeploymentInfo:
    """Get information about a stack deployment provider.

    Args:
        provider: The stack deployment provider.

    Raises:
        NotImplementedError: Stack deployments are not supported by the
            local ZenML deployment.
    """
    raise NotImplementedError(
        "Stack deployments are not supported by local ZenML deployments."
    )
get_stack_deployment_stack(provider: StackDeploymentProvider, stack_name: str, location: Optional[str] = None, date_start: Optional[datetime] = None) -> Optional[DeployedStack]

Return a matching ZenML stack that was deployed and registered.

Parameters:

Name Type Description Default
provider StackDeploymentProvider

The stack deployment provider.

required
stack_name str

The name of the stack.

required
location Optional[str]

The location where the stack should be deployed.

None
date_start Optional[datetime]

The date when the deployment started.

None

Raises:

Type Description
NotImplementedError

Stack deployments are not supported by the local ZenML deployment.

Source code in src/zenml/zen_stores/sql_zen_store.py
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
def get_stack_deployment_stack(
    self,
    provider: StackDeploymentProvider,
    stack_name: str,
    location: Optional[str] = None,
    date_start: Optional[datetime] = None,
) -> Optional[DeployedStack]:
    """Return a matching ZenML stack that was deployed and registered.

    Args:
        provider: The stack deployment provider.
        stack_name: The name of the stack.
        location: The location where the stack should be deployed.
        date_start: The date when the deployment started.

    Raises:
        NotImplementedError: Stack deployments are not supported by the
            local ZenML deployment.
    """
    raise NotImplementedError(
        "Stack deployments are not supported by local ZenML deployments."
    )
get_store_info() -> ServerModel

Get information about the store.

Returns:

Type Description
ServerModel

Information about the store.

Source code in src/zenml/zen_stores/sql_zen_store.py
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
def get_store_info(self) -> ServerModel:
    """Get information about the store.

    Returns:
        Information about the store.
    """
    model = super().get_store_info()
    sql_url = make_url(self.config.url)
    model.database_type = ServerDatabaseType(sql_url.drivername)
    settings = self.get_server_settings(hydrate=True)
    # Fetch the deployment ID from the database and use it to replace
    # the one fetched from the global configuration
    model.id = settings.server_id
    model.name = settings.server_name
    model.active = settings.active
    model.last_user_activity = settings.last_user_activity
    model.analytics_enabled = settings.enable_analytics
    return model
get_tag(tag_name_or_id: Union[str, UUID], hydrate: bool = True) -> TagResponse

Get an existing tag.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

name or id of the tag to be retrieved.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
TagResponse

The tag of interest.

Source code in src/zenml/zen_stores/sql_zen_store.py
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
def get_tag(
    self,
    tag_name_or_id: Union[str, UUID],
    hydrate: bool = True,
) -> TagResponse:
    """Get an existing tag.

    Args:
        tag_name_or_id: name or id of the tag to be retrieved.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The tag of interest.
    """
    with Session(self.engine) as session:
        tag = self._get_tag_schema(
            tag_name_or_id=tag_name_or_id,
            session=session,
        )
        return tag.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_trigger(trigger_id: UUID, hydrate: bool = True) -> TriggerResponse

Get a trigger by its unique ID.

Parameters:

Name Type Description Default
trigger_id UUID

The ID of the trigger to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
TriggerResponse

The trigger with the given ID.

Source code in src/zenml/zen_stores/sql_zen_store.py
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
def get_trigger(
    self, trigger_id: UUID, hydrate: bool = True
) -> TriggerResponse:
    """Get a trigger by its unique ID.

    Args:
        trigger_id: The ID of the trigger to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The trigger with the given ID.
    """
    with Session(self.engine) as session:
        trigger = self._get_schema_by_id(
            resource_id=trigger_id,
            schema_class=TriggerSchema,
            session=session,
        )
        return trigger.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_trigger_execution(trigger_execution_id: UUID, hydrate: bool = True) -> TriggerExecutionResponse

Get an trigger execution by ID.

Parameters:

Name Type Description Default
trigger_execution_id UUID

The ID of the trigger execution to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
TriggerExecutionResponse

The trigger execution.

Source code in src/zenml/zen_stores/sql_zen_store.py
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
def get_trigger_execution(
    self,
    trigger_execution_id: UUID,
    hydrate: bool = True,
) -> TriggerExecutionResponse:
    """Get an trigger execution by ID.

    Args:
        trigger_execution_id: The ID of the trigger execution to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The trigger execution.
    """
    with Session(self.engine) as session:
        execution = self._get_schema_by_id(
            resource_id=trigger_execution_id,
            schema_class=TriggerExecutionSchema,
            session=session,
        )
        return execution.to_model(
            include_metadata=hydrate, include_resources=True
        )
get_user(user_name_or_id: Optional[Union[str, UUID]] = None, include_private: bool = False, hydrate: bool = True) -> UserResponse

Gets a specific user, when no id is specified the active user is returned.

noqa: DAR401
noqa: DAR402

Raises a KeyError in case a user with that name or id does not exist.

For backwards-compatibility reasons, this method can also be called to fetch service accounts by their ID.

Parameters:

Name Type Description Default
user_name_or_id Optional[Union[str, UUID]]

The name or ID of the user to get.

None
include_private bool

Whether to include private user information

False
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
UserResponse

The requested user, if it was found.

Raises:

Type Description
KeyError

If the user does not exist.

Source code in src/zenml/zen_stores/sql_zen_store.py
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
def get_user(
    self,
    user_name_or_id: Optional[Union[str, UUID]] = None,
    include_private: bool = False,
    hydrate: bool = True,
) -> UserResponse:
    """Gets a specific user, when no id is specified the active user is returned.

    # noqa: DAR401
    # noqa: DAR402

    Raises a KeyError in case a user with that name or id does not exist.

    For backwards-compatibility reasons, this method can also be called
    to fetch service accounts by their ID.

    Args:
        user_name_or_id: The name or ID of the user to get.
        include_private: Whether to include private user information
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested user, if it was found.

    Raises:
        KeyError: If the user does not exist.
    """
    with Session(self.engine) as session:
        if user_name_or_id is None:
            user_name_or_id = self._get_active_user(session=session).id

        # If a UUID is passed, we also allow fetching service accounts
        # with that ID.
        service_account: Optional[bool] = False
        if uuid_utils.is_valid_uuid(user_name_or_id):
            service_account = None
        user = self._get_account_schema(
            user_name_or_id,
            session=session,
            service_account=service_account,
        )

        return user.to_model(
            include_private=include_private,
            include_metadata=hydrate,
            include_resources=True,
        )
list_actions(action_filter_model: ActionFilter, hydrate: bool = False) -> Page[ActionResponse]

List all actions matching the given filter criteria.

Parameters:

Name Type Description Default
action_filter_model ActionFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ActionResponse]

A page of actions matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def list_actions(
    self,
    action_filter_model: ActionFilter,
    hydrate: bool = False,
) -> Page[ActionResponse]:
    """List all actions matching the given filter criteria.

    Args:
        action_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of actions matching the filter criteria.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=action_filter_model,
            session=session,
        )
        query = select(ActionSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=ActionSchema,
            filter_model=action_filter_model,
            hydrate=hydrate,
        )
list_api_keys(service_account_id: UUID, filter_model: APIKeyFilter, hydrate: bool = False) -> Page[APIKeyResponse]

List all API keys for a service account matching the given filter criteria.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to list the API keys.

required
filter_model APIKeyFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[APIKeyResponse]

A list of all API keys matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def list_api_keys(
    self,
    service_account_id: UUID,
    filter_model: APIKeyFilter,
    hydrate: bool = False,
) -> Page[APIKeyResponse]:
    """List all API keys for a service account matching the given filter criteria.

    Args:
        service_account_id: The ID of the service account for which to list
            the API keys.
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all API keys matching the filter criteria.
    """
    with Session(self.engine) as session:
        # Fetch the service account
        service_account = self._get_account_schema(
            service_account_id, session=session, service_account=True
        )

        filter_model.set_service_account(service_account.id)
        query = select(APIKeySchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=APIKeySchema,
            filter_model=filter_model,
            hydrate=hydrate,
        )
list_artifact_versions(artifact_version_filter_model: ArtifactVersionFilter, hydrate: bool = False) -> Page[ArtifactVersionResponse]

List all artifact versions matching the given filter criteria.

Parameters:

Name Type Description Default
artifact_version_filter_model ArtifactVersionFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ArtifactVersionResponse]

A list of all artifact versions matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
def list_artifact_versions(
    self,
    artifact_version_filter_model: ArtifactVersionFilter,
    hydrate: bool = False,
) -> Page[ArtifactVersionResponse]:
    """List all artifact versions matching the given filter criteria.

    Args:
        artifact_version_filter_model: All filter parameters including
            pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all artifact versions matching the filter criteria.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=artifact_version_filter_model,
            session=session,
        )
        query = select(ArtifactVersionSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=ArtifactVersionSchema,
            filter_model=artifact_version_filter_model,
            hydrate=hydrate,
        )
list_artifacts(filter_model: ArtifactFilter, hydrate: bool = False) -> Page[ArtifactResponse]

List all artifacts matching the given filter criteria.

Parameters:

Name Type Description Default
filter_model ArtifactFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ArtifactResponse]

A list of all artifacts matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
def list_artifacts(
    self, filter_model: ArtifactFilter, hydrate: bool = False
) -> Page[ArtifactResponse]:
    """List all artifacts matching the given filter criteria.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all artifacts matching the filter criteria.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=filter_model,
            session=session,
        )
        query = select(ArtifactSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=ArtifactSchema,
            filter_model=filter_model,
            hydrate=hydrate,
        )
list_authorized_devices(filter_model: OAuthDeviceFilter, hydrate: bool = False) -> Page[OAuthDeviceResponse]

List all OAuth 2.0 authorized devices for a user.

Parameters:

Name Type Description Default
filter_model OAuthDeviceFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[OAuthDeviceResponse]

A page of all matching OAuth 2.0 authorized devices.

Source code in src/zenml/zen_stores/sql_zen_store.py
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
def list_authorized_devices(
    self,
    filter_model: OAuthDeviceFilter,
    hydrate: bool = False,
) -> Page[OAuthDeviceResponse]:
    """List all OAuth 2.0 authorized devices for a user.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all matching OAuth 2.0 authorized devices.
    """
    with Session(self.engine) as session:
        query = select(OAuthDeviceSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=OAuthDeviceSchema,
            filter_model=filter_model,
            hydrate=hydrate,
        )
list_builds(build_filter_model: PipelineBuildFilter, hydrate: bool = False) -> Page[PipelineBuildResponse]

List all builds matching the given filter criteria.

Parameters:

Name Type Description Default
build_filter_model PipelineBuildFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineBuildResponse]

A page of all builds matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
def list_builds(
    self,
    build_filter_model: PipelineBuildFilter,
    hydrate: bool = False,
) -> Page[PipelineBuildResponse]:
    """List all builds matching the given filter criteria.

    Args:
        build_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all builds matching the filter criteria.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=build_filter_model,
            session=session,
        )
        query = select(PipelineBuildSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=PipelineBuildSchema,
            filter_model=build_filter_model,
            hydrate=hydrate,
        )
list_code_repositories(filter_model: CodeRepositoryFilter, hydrate: bool = False) -> Page[CodeRepositoryResponse]

List all code repositories.

Parameters:

Name Type Description Default
filter_model CodeRepositoryFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[CodeRepositoryResponse]

A page of all code repositories.

Source code in src/zenml/zen_stores/sql_zen_store.py
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
def list_code_repositories(
    self,
    filter_model: CodeRepositoryFilter,
    hydrate: bool = False,
) -> Page[CodeRepositoryResponse]:
    """List all code repositories.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all code repositories.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=filter_model,
            session=session,
        )
        query = select(CodeRepositorySchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=CodeRepositorySchema,
            filter_model=filter_model,
            hydrate=hydrate,
        )
list_deployments(deployment_filter_model: PipelineDeploymentFilter, hydrate: bool = False) -> Page[PipelineDeploymentResponse]

List all deployments matching the given filter criteria.

Parameters:

Name Type Description Default
deployment_filter_model PipelineDeploymentFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineDeploymentResponse]

A page of all deployments matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
def list_deployments(
    self,
    deployment_filter_model: PipelineDeploymentFilter,
    hydrate: bool = False,
) -> Page[PipelineDeploymentResponse]:
    """List all deployments matching the given filter criteria.

    Args:
        deployment_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all deployments matching the filter criteria.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=deployment_filter_model,
            session=session,
        )
        query = select(PipelineDeploymentSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=PipelineDeploymentSchema,
            filter_model=deployment_filter_model,
            hydrate=hydrate,
        )
list_event_sources(event_source_filter_model: EventSourceFilter, hydrate: bool = False) -> Page[EventSourceResponse]

List all event_sources matching the given filter criteria.

Parameters:

Name Type Description Default
event_source_filter_model EventSourceFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[EventSourceResponse]

A list of all event_sources matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
def list_event_sources(
    self,
    event_source_filter_model: EventSourceFilter,
    hydrate: bool = False,
) -> Page[EventSourceResponse]:
    """List all event_sources matching the given filter criteria.

    Args:
        event_source_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all event_sources matching the filter criteria.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=event_source_filter_model,
            session=session,
        )
        query = select(EventSourceSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=EventSourceSchema,
            filter_model=event_source_filter_model,
            hydrate=hydrate,
        )
list_flavors(flavor_filter_model: FlavorFilter, hydrate: bool = False) -> Page[FlavorResponse]

List all stack component flavors matching the given filter criteria.

Parameters:

Name Type Description Default
flavor_filter_model FlavorFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[FlavorResponse]

List of all the stack component flavors matching the given criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
def list_flavors(
    self,
    flavor_filter_model: FlavorFilter,
    hydrate: bool = False,
) -> Page[FlavorResponse]:
    """List all stack component flavors matching the given filter criteria.

    Args:
        flavor_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        List of all the stack component flavors matching the given criteria.
    """
    with Session(self.engine) as session:
        query = select(FlavorSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=FlavorSchema,
            filter_model=flavor_filter_model,
            hydrate=hydrate,
        )
list_model_version_artifact_links(model_version_artifact_link_filter_model: ModelVersionArtifactFilter, hydrate: bool = False) -> Page[ModelVersionArtifactResponse]

Get all model version to artifact links by filter.

Parameters:

Name Type Description Default
model_version_artifact_link_filter_model ModelVersionArtifactFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ModelVersionArtifactResponse]

A page of all model version to artifact links.

Source code in src/zenml/zen_stores/sql_zen_store.py
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
def list_model_version_artifact_links(
    self,
    model_version_artifact_link_filter_model: ModelVersionArtifactFilter,
    hydrate: bool = False,
) -> Page[ModelVersionArtifactResponse]:
    """Get all model version to artifact links by filter.

    Args:
        model_version_artifact_link_filter_model: All filter parameters
            including pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all model version to artifact links.
    """
    with Session(self.engine) as session:
        query = select(ModelVersionArtifactSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=ModelVersionArtifactSchema,
            filter_model=model_version_artifact_link_filter_model,
            hydrate=hydrate,
        )
list_model_version_pipeline_run_links(model_version_pipeline_run_link_filter_model: ModelVersionPipelineRunFilter, hydrate: bool = False) -> Page[ModelVersionPipelineRunResponse]

Get all model version to pipeline run links by filter.

Parameters:

Name Type Description Default
model_version_pipeline_run_link_filter_model ModelVersionPipelineRunFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ModelVersionPipelineRunResponse]

A page of all model version to pipeline run links.

Source code in src/zenml/zen_stores/sql_zen_store.py
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
def list_model_version_pipeline_run_links(
    self,
    model_version_pipeline_run_link_filter_model: ModelVersionPipelineRunFilter,
    hydrate: bool = False,
) -> Page[ModelVersionPipelineRunResponse]:
    """Get all model version to pipeline run links by filter.

    Args:
        model_version_pipeline_run_link_filter_model: All filter parameters
            including pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all model version to pipeline run links.
    """
    query = select(ModelVersionPipelineRunSchema)
    with Session(self.engine) as session:
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=ModelVersionPipelineRunSchema,
            filter_model=model_version_pipeline_run_link_filter_model,
            hydrate=hydrate,
        )
list_model_versions(model_version_filter_model: ModelVersionFilter, hydrate: bool = False) -> Page[ModelVersionResponse]

Get all model versions by filter.

Parameters:

Name Type Description Default
model_version_filter_model ModelVersionFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ModelVersionResponse]

A page of all model versions.

Source code in src/zenml/zen_stores/sql_zen_store.py
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
def list_model_versions(
    self,
    model_version_filter_model: ModelVersionFilter,
    hydrate: bool = False,
) -> Page[ModelVersionResponse]:
    """Get all model versions by filter.

    Args:
        model_version_filter_model: All filter parameters including
            pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all model versions.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=model_version_filter_model,
            session=session,
        )
        self._set_filter_model_id(
            filter_model=model_version_filter_model,
            session=session,
        )

        query = select(ModelVersionSchema)

        return self.filter_and_paginate(
            session=session,
            query=query,
            table=ModelVersionSchema,
            filter_model=model_version_filter_model,
            hydrate=hydrate,
        )
list_models(model_filter_model: ModelFilter, hydrate: bool = False) -> Page[ModelResponse]

Get all models by filter.

Parameters:

Name Type Description Default
model_filter_model ModelFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ModelResponse]

A page of all models.

Source code in src/zenml/zen_stores/sql_zen_store.py
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
def list_models(
    self,
    model_filter_model: ModelFilter,
    hydrate: bool = False,
) -> Page[ModelResponse]:
    """Get all models by filter.

    Args:
        model_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all models.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=model_filter_model,
            session=session,
        )
        query = select(ModelSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=ModelSchema,
            filter_model=model_filter_model,
            hydrate=hydrate,
        )
list_pipelines(pipeline_filter_model: PipelineFilter, hydrate: bool = False) -> Page[PipelineResponse]

List all pipelines matching the given filter criteria.

Parameters:

Name Type Description Default
pipeline_filter_model PipelineFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineResponse]

A list of all pipelines matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
def list_pipelines(
    self,
    pipeline_filter_model: PipelineFilter,
    hydrate: bool = False,
) -> Page[PipelineResponse]:
    """List all pipelines matching the given filter criteria.

    Args:
        pipeline_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all pipelines matching the filter criteria.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=pipeline_filter_model,
            session=session,
        )
        query = select(PipelineSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=PipelineSchema,
            filter_model=pipeline_filter_model,
            hydrate=hydrate,
        )
list_projects(project_filter_model: ProjectFilter, hydrate: bool = False) -> Page[ProjectResponse]

List all projects matching the given filter criteria.

Parameters:

Name Type Description Default
project_filter_model ProjectFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ProjectResponse]

A list of all projects matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
def list_projects(
    self,
    project_filter_model: ProjectFilter,
    hydrate: bool = False,
) -> Page[ProjectResponse]:
    """List all projects matching the given filter criteria.

    Args:
        project_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all projects matching the filter criteria.
    """
    with Session(self.engine) as session:
        query = select(ProjectSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=ProjectSchema,
            filter_model=project_filter_model,
            hydrate=hydrate,
        )
list_run_steps(step_run_filter_model: StepRunFilter, hydrate: bool = False) -> Page[StepRunResponse]

List all step runs matching the given filter criteria.

Parameters:

Name Type Description Default
step_run_filter_model StepRunFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[StepRunResponse]

A list of all step runs matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
def list_run_steps(
    self,
    step_run_filter_model: StepRunFilter,
    hydrate: bool = False,
) -> Page[StepRunResponse]:
    """List all step runs matching the given filter criteria.

    Args:
        step_run_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all step runs matching the filter criteria.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=step_run_filter_model,
            session=session,
        )
        query = select(StepRunSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=StepRunSchema,
            filter_model=step_run_filter_model,
            hydrate=hydrate,
        )
list_run_templates(template_filter_model: RunTemplateFilter, hydrate: bool = False) -> Page[RunTemplateResponse]

List all run templates matching the given filter criteria.

Parameters:

Name Type Description Default
template_filter_model RunTemplateFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[RunTemplateResponse]

A list of all templates matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
def list_run_templates(
    self,
    template_filter_model: RunTemplateFilter,
    hydrate: bool = False,
) -> Page[RunTemplateResponse]:
    """List all run templates matching the given filter criteria.

    Args:
        template_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all templates matching the filter criteria.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=template_filter_model,
            session=session,
        )
        query = select(RunTemplateSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=RunTemplateSchema,
            filter_model=template_filter_model,
            hydrate=hydrate,
        )
list_runs(runs_filter_model: PipelineRunFilter, hydrate: bool = False) -> Page[PipelineRunResponse]

List all pipeline runs matching the given filter criteria.

Parameters:

Name Type Description Default
runs_filter_model PipelineRunFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineRunResponse]

A list of all pipeline runs matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
def list_runs(
    self,
    runs_filter_model: PipelineRunFilter,
    hydrate: bool = False,
) -> Page[PipelineRunResponse]:
    """List all pipeline runs matching the given filter criteria.

    Args:
        runs_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all pipeline runs matching the filter criteria.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=runs_filter_model,
            session=session,
        )
        query = select(PipelineRunSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=PipelineRunSchema,
            filter_model=runs_filter_model,
            hydrate=hydrate,
        )
list_schedules(schedule_filter_model: ScheduleFilter, hydrate: bool = False) -> Page[ScheduleResponse]

List all schedules.

Parameters:

Name Type Description Default
schedule_filter_model ScheduleFilter

All filter parameters including pagination params

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ScheduleResponse]

A list of schedules.

Source code in src/zenml/zen_stores/sql_zen_store.py
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
def list_schedules(
    self,
    schedule_filter_model: ScheduleFilter,
    hydrate: bool = False,
) -> Page[ScheduleResponse]:
    """List all schedules.

    Args:
        schedule_filter_model: All filter parameters including pagination
            params
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of schedules.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=schedule_filter_model,
            session=session,
        )
        query = select(ScheduleSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=ScheduleSchema,
            filter_model=schedule_filter_model,
            hydrate=hydrate,
        )
list_secrets(secret_filter_model: SecretFilter, hydrate: bool = False) -> Page[SecretResponse]

List all secrets matching the given filter criteria.

Note that returned secrets do not include any secret values. To fetch the secret values, use get_secret.

Parameters:

Name Type Description Default
secret_filter_model SecretFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[SecretResponse]

A list of all secrets matching the filter criteria, with pagination

Page[SecretResponse]

information and sorted according to the filter criteria. The

Page[SecretResponse]

returned secrets do not include any secret values, only metadata. To

Page[SecretResponse]

fetch the secret values, use get_secret individually with each

Page[SecretResponse]

secret.

Source code in src/zenml/zen_stores/sql_zen_store.py
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
def list_secrets(
    self, secret_filter_model: SecretFilter, hydrate: bool = False
) -> Page[SecretResponse]:
    """List all secrets matching the given filter criteria.

    Note that returned secrets do not include any secret values. To fetch
    the secret values, use `get_secret`.

    Args:
        secret_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all secrets matching the filter criteria, with pagination
        information and sorted according to the filter criteria. The
        returned secrets do not include any secret values, only metadata. To
        fetch the secret values, use `get_secret` individually with each
        secret.
    """
    with Session(self.engine) as session:
        # Filter all secrets according to their private status and the active
        # user
        secret_filter_model.set_scope_user(
            self._get_active_user(session).id
        )
        query = select(SecretSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=SecretSchema,
            filter_model=secret_filter_model,
            hydrate=hydrate,
        )
list_service_accounts(filter_model: ServiceAccountFilter, hydrate: bool = False) -> Page[ServiceAccountResponse]

List all service accounts.

Parameters:

Name Type Description Default
filter_model ServiceAccountFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ServiceAccountResponse]

A list of filtered service accounts.

Source code in src/zenml/zen_stores/sql_zen_store.py
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
def list_service_accounts(
    self,
    filter_model: ServiceAccountFilter,
    hydrate: bool = False,
) -> Page[ServiceAccountResponse]:
    """List all service accounts.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of filtered service accounts.
    """
    with Session(self.engine) as session:
        query = select(UserSchema)
        paged_service_accounts: Page[ServiceAccountResponse] = (
            self.filter_and_paginate(
                session=session,
                query=query,
                table=UserSchema,
                filter_model=filter_model,
                custom_schema_to_model_conversion=lambda user: user.to_service_account_model(
                    include_metadata=hydrate, include_resources=True
                ),
                hydrate=hydrate,
            )
        )
        return paged_service_accounts
list_service_connector_resources(filter_model: ServiceConnectorFilter) -> List[ServiceConnectorResourcesModel]

List resources that can be accessed by service connectors.

Parameters:

Name Type Description Default
filter_model ServiceConnectorFilter

Optional filter model to use when fetching service connectors.

required

Returns:

Type Description
List[ServiceConnectorResourcesModel]

The matching list of resources that available service

List[ServiceConnectorResourcesModel]

connectors have access to.

Source code in src/zenml/zen_stores/sql_zen_store.py
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
def list_service_connector_resources(
    self,
    filter_model: ServiceConnectorFilter,
) -> List[ServiceConnectorResourcesModel]:
    """List resources that can be accessed by service connectors.

    Args:
        filter_model: Optional filter model to use when fetching service
            connectors.

    Returns:
        The matching list of resources that available service
        connectors have access to.
    """
    # We process the resource_id filter separately, if set, because
    # this is not a simple string comparison, but specific to every
    # connector type.
    resource_id = filter_model.resource_id
    filter_model.resource_id = None

    service_connectors = self.list_service_connectors(
        filter_model=filter_model
    ).items

    resource_list: List[ServiceConnectorResourcesModel] = []

    for connector in service_connectors:
        if not service_connector_registry.is_registered(connector.type):
            # For connectors that we can instantiate, i.e. those that have a
            # connector type available locally, we return complete
            # information about the resources that they have access to.
            #
            # For those that are not locally available, we only return
            # rudimentary information extracted from the connector model
            # without actively trying to discover the resources that they
            # have access to.

            if resource_id and connector.resource_id != resource_id:
                # If an explicit resource ID is required, the connector
                # has to be configured with it.
                continue

            resources = (
                ServiceConnectorResourcesModel.from_connector_model(
                    connector,
                    resource_type=filter_model.resource_type,
                )
            )
            for r in resources.resources:
                if not r.resource_ids:
                    r.error = (
                        f"The service '{connector.type}' connector type is "
                        "not available."
                    )

        else:
            try:
                connector_instance = (
                    service_connector_registry.instantiate_connector(
                        model=connector
                    )
                )

                resources = connector_instance.verify(
                    resource_type=filter_model.resource_type,
                    resource_id=resource_id,
                    list_resources=True,
                )
            except (ValueError, AuthorizationException) as e:
                error = (
                    f"Failed to fetch {filter_model.resource_type or 'available'} "
                    f"resources from service connector {connector.name}/"
                    f"{connector.id}: {e}"
                )
                # Log an exception if debug logging is enabled
                if logger.isEnabledFor(logging.DEBUG):
                    logger.exception(error)
                else:
                    logger.error(error)
                continue

        resource_list.append(resources)

    return resource_list
list_service_connector_types(connector_type: Optional[str] = None, resource_type: Optional[str] = None, auth_method: Optional[str] = None) -> List[ServiceConnectorTypeModel]

Get a list of service connector types.

Parameters:

Name Type Description Default
connector_type Optional[str]

Filter by connector type.

None
resource_type Optional[str]

Filter by resource type.

None
auth_method Optional[str]

Filter by authentication method.

None

Returns:

Type Description
List[ServiceConnectorTypeModel]

List of service connector types.

Source code in src/zenml/zen_stores/sql_zen_store.py
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
def list_service_connector_types(
    self,
    connector_type: Optional[str] = None,
    resource_type: Optional[str] = None,
    auth_method: Optional[str] = None,
) -> List[ServiceConnectorTypeModel]:
    """Get a list of service connector types.

    Args:
        connector_type: Filter by connector type.
        resource_type: Filter by resource type.
        auth_method: Filter by authentication method.

    Returns:
        List of service connector types.
    """
    return service_connector_registry.list_service_connector_types(
        connector_type=connector_type,
        resource_type=resource_type,
        auth_method=auth_method,
    )
list_service_connectors(filter_model: ServiceConnectorFilter, hydrate: bool = False) -> Page[ServiceConnectorResponse]

List all service connectors.

Parameters:

Name Type Description Default
filter_model ServiceConnectorFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ServiceConnectorResponse]

A page of all service connectors.

Source code in src/zenml/zen_stores/sql_zen_store.py
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
def list_service_connectors(
    self,
    filter_model: ServiceConnectorFilter,
    hydrate: bool = False,
) -> Page[ServiceConnectorResponse]:
    """List all service connectors.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all service connectors.
    """

    def fetch_connectors(
        session: Session,
        query: Union[
            Select[ServiceConnectorSchema],
            SelectOfScalar[ServiceConnectorSchema],
        ],
        filter_model: BaseFilter,
    ) -> Sequence[ServiceConnectorSchema]:
        """Custom fetch function for connector filtering and pagination.

        Applies resource type and label filters to the query.

        Args:
            session: The database session.
            query: The query to filter.
            filter_model: The filter model.

        Returns:
            The filtered and paginated results.
        """
        assert isinstance(filter_model, ServiceConnectorFilter)
        items = self._list_filtered_service_connectors(
            session=session, query=query, filter_model=filter_model
        )

        return items

    with Session(self.engine) as session:
        query = select(ServiceConnectorSchema)
        paged_connectors: Page[ServiceConnectorResponse] = (
            self.filter_and_paginate(
                session=session,
                query=query,
                table=ServiceConnectorSchema,
                filter_model=filter_model,
                custom_fetch=fetch_connectors,
                hydrate=hydrate,
            )
        )

        self._populate_connector_type(*paged_connectors.items)
        return paged_connectors
list_services(filter_model: ServiceFilter, hydrate: bool = False) -> Page[ServiceResponse]

List all services matching the given filter criteria.

Parameters:

Name Type Description Default
filter_model ServiceFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ServiceResponse]

A list of all services matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
def list_services(
    self, filter_model: ServiceFilter, hydrate: bool = False
) -> Page[ServiceResponse]:
    """List all services matching the given filter criteria.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all services matching the filter criteria.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=filter_model,
            session=session,
        )
        query = select(ServiceSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=ServiceSchema,
            filter_model=filter_model,
            hydrate=hydrate,
        )
list_stack_components(component_filter_model: ComponentFilter, hydrate: bool = False) -> Page[ComponentResponse]

List all stack components matching the given filter criteria.

Parameters:

Name Type Description Default
component_filter_model ComponentFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ComponentResponse]

A list of all stack components matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
def list_stack_components(
    self,
    component_filter_model: ComponentFilter,
    hydrate: bool = False,
) -> Page[ComponentResponse]:
    """List all stack components matching the given filter criteria.

    Args:
        component_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all stack components matching the filter criteria.
    """
    with Session(self.engine) as session:
        query = select(StackComponentSchema)
        paged_components: Page[ComponentResponse] = (
            self.filter_and_paginate(
                session=session,
                query=query,
                table=StackComponentSchema,
                filter_model=component_filter_model,
                hydrate=hydrate,
            )
        )
        return paged_components
list_stacks(stack_filter_model: StackFilter, hydrate: bool = False) -> Page[StackResponse]

List all stacks matching the given filter criteria.

Parameters:

Name Type Description Default
stack_filter_model StackFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[StackResponse]

A list of all stacks matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
def list_stacks(
    self,
    stack_filter_model: StackFilter,
    hydrate: bool = False,
) -> Page[StackResponse]:
    """List all stacks matching the given filter criteria.

    Args:
        stack_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all stacks matching the filter criteria.
    """
    with Session(self.engine) as session:
        query = select(StackSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=StackSchema,
            filter_model=stack_filter_model,
            hydrate=hydrate,
        )
list_tags(tag_filter_model: TagFilter, hydrate: bool = False) -> Page[TagResponse]

Get all tags by filter.

Parameters:

Name Type Description Default
tag_filter_model TagFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[TagResponse]

A page of all tags.

Source code in src/zenml/zen_stores/sql_zen_store.py
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
def list_tags(
    self,
    tag_filter_model: TagFilter,
    hydrate: bool = False,
) -> Page[TagResponse]:
    """Get all tags by filter.

    Args:
        tag_filter_model: All filter parameters including pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all tags.
    """
    with Session(self.engine) as session:
        query = select(TagSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=TagSchema,
            filter_model=tag_filter_model,
            hydrate=hydrate,
        )
list_trigger_executions(trigger_execution_filter_model: TriggerExecutionFilter, hydrate: bool = False) -> Page[TriggerExecutionResponse]

List all trigger executions matching the given filter criteria.

Parameters:

Name Type Description Default
trigger_execution_filter_model TriggerExecutionFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[TriggerExecutionResponse]

A list of all trigger executions matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
def list_trigger_executions(
    self,
    trigger_execution_filter_model: TriggerExecutionFilter,
    hydrate: bool = False,
) -> Page[TriggerExecutionResponse]:
    """List all trigger executions matching the given filter criteria.

    Args:
        trigger_execution_filter_model: All filter parameters including
            pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all trigger executions matching the filter criteria.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=trigger_execution_filter_model,
            session=session,
        )
        query = select(TriggerExecutionSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=TriggerExecutionSchema,
            filter_model=trigger_execution_filter_model,
            hydrate=hydrate,
        )
list_triggers(trigger_filter_model: TriggerFilter, hydrate: bool = False) -> Page[TriggerResponse]

List all trigger matching the given filter criteria.

Parameters:

Name Type Description Default
trigger_filter_model TriggerFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[TriggerResponse]

A list of all triggers matching the filter criteria.

Source code in src/zenml/zen_stores/sql_zen_store.py
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
def list_triggers(
    self,
    trigger_filter_model: TriggerFilter,
    hydrate: bool = False,
) -> Page[TriggerResponse]:
    """List all trigger matching the given filter criteria.

    Args:
        trigger_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all triggers matching the filter criteria.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=trigger_filter_model,
            session=session,
        )
        query = select(TriggerSchema)
        return self.filter_and_paginate(
            session=session,
            query=query,
            table=TriggerSchema,
            filter_model=trigger_filter_model,
            hydrate=hydrate,
        )
list_users(user_filter_model: UserFilter, hydrate: bool = False) -> Page[UserResponse]

List all users.

Parameters:

Name Type Description Default
user_filter_model UserFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[UserResponse]

A list of all users.

Source code in src/zenml/zen_stores/sql_zen_store.py
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
def list_users(
    self,
    user_filter_model: UserFilter,
    hydrate: bool = False,
) -> Page[UserResponse]:
    """List all users.

    Args:
        user_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all users.
    """
    with Session(self.engine) as session:
        query = select(UserSchema)
        paged_user: Page[UserResponse] = self.filter_and_paginate(
            session=session,
            query=query,
            table=UserSchema,
            filter_model=user_filter_model,
            hydrate=hydrate,
        )
        return paged_user
migrate_database() -> None

Migrate the database to the head as defined by the python package.

Raises:

Type Description
RuntimeError

If the database exists and is not empty but has never been migrated with alembic before.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def migrate_database(self) -> None:
    """Migrate the database to the head as defined by the python package.

    Raises:
        RuntimeError: If the database exists and is not empty but has never
            been migrated with alembic before.
    """
    alembic_logger = logging.getLogger("alembic")

    # remove all existing handlers
    while len(alembic_logger.handlers):
        alembic_logger.removeHandler(alembic_logger.handlers[0])

    logging_level = get_logging_level()

    # suppress alembic info logging if the zenml logging level is not debug
    if logging_level == LoggingLevels.DEBUG:
        alembic_logger.setLevel(logging.DEBUG)
    else:
        alembic_logger.setLevel(logging.WARNING)

    alembic_logger.addHandler(get_console_handler())

    # We need to account for 3 distinct cases here:
    # 1. the database is completely empty (not initialized)
    # 2. the database is not empty and has been migrated with alembic before
    # 3. the database is not empty, but has never been migrated with alembic
    #   before (i.e. was created with SQLModel back when alembic wasn't
    #   used). We don't support this direct upgrade case anymore.
    current_revisions = self.alembic.current_revisions()
    head_revisions = self.alembic.head_revisions()
    if len(current_revisions) >= 1:
        # Case 2: the database has been migrated with alembic before. Just
        # upgrade to the latest revision.
        if len(current_revisions) > 1:
            logger.warning(
                "The ZenML database has more than one migration head "
                "revision. This is not expected and might indicate a "
                "database migration problem. Please raise an issue on "
                "GitHub if you encounter this."
            )

        logger.debug("Current revisions: %s", current_revisions)
        logger.debug("Head revisions: %s", head_revisions)

        # If the current revision and head revision don't match, a database
        # migration that changes the database structure or contents may
        # actually be performed, in which case we enable the backup
        # functionality. We only enable the backup functionality if the
        # database will actually be changed, to avoid the overhead for
        # unnecessary backups.
        backup_enabled = (
            self.config.backup_strategy != DatabaseBackupStrategy.DISABLED
            and set(current_revisions) != set(head_revisions)
        )
        backup_location: Optional[Any] = None
        backup_location_msg: Optional[str] = None

        if backup_enabled:
            try:
                logger.info("Backing up the database before migration.")
                (
                    backup_location_msg,
                    backup_location,
                ) = self.backup_database(overwrite=True)
            except Exception as e:
                # The database backup feature was not entirely functional
                # in ZenML 0.56.3 and earlier, due to inconsistencies in the
                # database schema. If the database is at version 0.56.3
                # or earlier and if the backup fails, we only log the
                # exception and leave the upgrade process to proceed.
                allow_backup_failures = False
                try:
                    if version.parse(
                        current_revisions[0]
                    ) <= version.parse("0.56.3"):
                        allow_backup_failures = True
                except version.InvalidVersion:
                    # This can happen if the database is not currently
                    # stamped with an official ZenML version (e.g. in
                    # development environments).
                    pass

                if allow_backup_failures:
                    logger.exception(
                        "Failed to backup the database. The database "
                        "upgrade will proceed without a backup."
                    )
                else:
                    raise RuntimeError(
                        f"Failed to backup the database: {str(e)}. "
                        "Please check the logs for more details. "
                        "If you would like to disable the database backup "
                        "functionality, set the `backup_strategy` attribute "
                        "of the store configuration to `disabled`."
                    ) from e
            else:
                if backup_location is not None:
                    logger.info(
                        "Database successfully backed up to "
                        f"{backup_location_msg}. If something goes wrong "
                        "with the upgrade, ZenML will attempt to restore "
                        "the database from this backup automatically."
                    )

        try:
            self.alembic.upgrade()
        except Exception as e:
            if backup_enabled and backup_location:
                logger.exception(
                    "Failed to migrate the database. Attempting to restore "
                    f"the database from {backup_location_msg}."
                )
                try:
                    self.restore_database(location=backup_location)
                except Exception:
                    logger.exception(
                        "Failed to restore the database from "
                        f"{backup_location_msg}. Please "
                        "check the logs for more details. You might need "
                        "to restore the database manually."
                    )
                else:
                    raise RuntimeError(
                        "The database migration failed, but the database "
                        "was successfully restored from the backup. "
                        "You can safely retry the upgrade or revert to "
                        "the previous version of ZenML. Please check the "
                        "logs for more details."
                    ) from e
            raise RuntimeError(
                f"The database migration failed: {str(e)}"
            ) from e

        else:
            # We always remove the backup after a successful upgrade,
            # not just to avoid cluttering the disk, but also to avoid
            # reusing an outdated database from the backup in case of
            # future upgrade failures.
            try:
                self.cleanup_database_backup()
            except Exception:
                logger.exception("Failed to cleanup the database backup.")

    elif self.alembic.db_is_empty():
        # Case 1: the database is empty. We can just create the
        # tables from scratch with from SQLModel. After tables are
        # created we put an alembic revision to latest and initialize
        # the settings table with needed info.
        logger.info("Creating database tables")
        with self.engine.begin() as conn:
            SQLModel.metadata.create_all(conn)
        with Session(self.engine) as session:
            server_config = ServerConfiguration.get_server_config()

            # Initialize the settings
            id_ = (
                server_config.external_server_id
                or GlobalConfiguration().user_id
            )
            session.add(
                ServerSettingsSchema(
                    id=id_,
                    server_name=server_config.server_name,
                    # We always initialize the server as inactive and decide
                    # whether to activate it later in `_initialize_database`
                    active=False,
                    enable_analytics=GlobalConfiguration().analytics_opt_in,
                    display_announcements=server_config.display_announcements,
                    display_updates=server_config.display_updates,
                    logo_url=None,
                    onboarding_state=None,
                )
            )
            session.commit()
        self.alembic.stamp("head")
    else:
        # Case 3: the database is not empty, but has never been
        # migrated with alembic before. We don't support this direct
        # upgrade case anymore. The user needs to run a two-step
        # upgrade.
        raise RuntimeError(
            "The ZenML database has never been migrated with alembic "
            "before. This can happen if you are performing a direct "
            "upgrade from a really old version of ZenML. This direct "
            "upgrade path is not supported anymore. Please upgrade "
            "your ZenML installation first to 0.54.0 or an earlier "
            "version and then to the latest version."
        )

    # If an alembic migration took place, all non-custom flavors are purged
    #  and the FlavorRegistry recreates all in-built and integration
    #  flavors in the db.
    revisions_afterwards = self.alembic.current_revisions()

    if current_revisions != revisions_afterwards:
        try:
            if current_revisions and version.parse(
                current_revisions[0]
            ) < version.parse("0.57.1"):
                # We want to send the missing user enriched events for users
                # which were created pre 0.57.1 and only on one upgrade
                self._should_send_user_enriched_events = True
        except version.InvalidVersion:
            # This can happen if the database is not currently
            # stamped with an official ZenML version (e.g. in
            # development environments).
            pass

        self._sync_flavors()
prune_artifact_versions(project_name_or_id: Union[str, UUID], only_versions: bool = True) -> None

Prunes unused artifact versions and their artifacts.

Parameters:

Name Type Description Default
project_name_or_id Union[str, UUID]

The project name or ID to prune artifact versions for.

required
only_versions bool

Only delete artifact versions, keeping artifacts

True
Source code in src/zenml/zen_stores/sql_zen_store.py
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
def prune_artifact_versions(
    self,
    project_name_or_id: Union[str, UUID],
    only_versions: bool = True,
) -> None:
    """Prunes unused artifact versions and their artifacts.

    Args:
        project_name_or_id: The project name or ID to prune artifact
            versions for.
        only_versions: Only delete artifact versions, keeping artifacts
    """
    with Session(self.engine) as session:
        project_id = self._get_schema_by_name_or_id(
            object_name_or_id=project_name_or_id,
            schema_class=ProjectSchema,
            session=session,
        ).id

        unused_artifact_versions = [
            a[0]
            for a in session.execute(
                select(ArtifactVersionSchema.id).where(
                    and_(
                        col(ArtifactVersionSchema.id).notin_(
                            select(StepRunOutputArtifactSchema.artifact_id)
                        ),
                        col(ArtifactVersionSchema.id).notin_(
                            select(StepRunInputArtifactSchema.artifact_id)
                        ),
                        col(ArtifactVersionSchema.project_id)
                        == project_id,
                    )
                )
            ).fetchall()
        ]
        session.execute(
            delete(ArtifactVersionSchema).where(
                col(ArtifactVersionSchema.id).in_(
                    unused_artifact_versions
                ),
            )
        )
        if not only_versions:
            unused_artifacts = [
                a[0]
                for a in session.execute(
                    select(ArtifactSchema.id).where(
                        col(ArtifactSchema.id).notin_(
                            select(ArtifactVersionSchema.artifact_id)
                        )
                    )
                ).fetchall()
            ]
            session.execute(
                delete(ArtifactSchema).where(
                    col(ArtifactSchema.id).in_(unused_artifacts)
                )
            )
        session.commit()
restore_database(strategy: Optional[DatabaseBackupStrategy] = None, location: Optional[Any] = None, cleanup: bool = False) -> None

Restore the database.

Parameters:

Name Type Description Default
strategy Optional[DatabaseBackupStrategy]

Custom backup strategy to use. If not set, the backup strategy from the store configuration will be used.

None
location Optional[Any]

Custom target location to restore the database from. If not set, the configured backup location will be used. Depending on the backup strategy, this can be a file path, a database name or an in-memory database representation.

None
cleanup bool

Whether to cleanup the backup after restoring the database.

False

Raises:

Type Description
ValueError

If the backup database name is not set when the backup database is requested or if the backup strategy is invalid.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def restore_database(
    self,
    strategy: Optional[DatabaseBackupStrategy] = None,
    location: Optional[Any] = None,
    cleanup: bool = False,
) -> None:
    """Restore the database.

    Args:
        strategy: Custom backup strategy to use. If not set, the backup
            strategy from the store configuration will be used.
        location: Custom target location to restore the database from. If
            not set, the configured backup location will be used. Depending
            on the backup strategy, this can be a file path, a database
            name or an in-memory database representation.
        cleanup: Whether to cleanup the backup after restoring the database.

    Raises:
        ValueError: If the backup database name is not set when the backup
            database is requested or if the backup strategy is invalid.
    """
    strategy = strategy or self.config.backup_strategy

    if (
        strategy == DatabaseBackupStrategy.DUMP_FILE
        or self.config.driver == SQLDatabaseDriver.SQLITE
    ):
        dump_file = location or self._get_db_backup_file_path()
        self.migration_utils.restore_database_from_file(
            dump_file=dump_file
        )
    elif strategy == DatabaseBackupStrategy.DATABASE:
        backup_db_name = location or self.config.backup_database
        if not backup_db_name:
            raise ValueError(
                "The backup database name must be set in the store "
                "configuration to use the backup database strategy."
            )

        self.migration_utils.restore_database_from_db(
            backup_db_name=backup_db_name
        )
    elif strategy == DatabaseBackupStrategy.IN_MEMORY:
        if location is None or not isinstance(location, list):
            raise ValueError(
                "The in-memory database representation must be provided "
                "to restore the database from an in-memory backup."
            )
        self.migration_utils.restore_database_from_memory(db_dump=location)

    else:
        raise ValueError(f"Invalid backup strategy: {strategy}.")

    if cleanup:
        self.cleanup_database_backup()
restore_secrets(ignore_errors: bool = False, delete_secrets: bool = False) -> None

Restore all secrets from the configured backup secrets store.

Parameters:

Name Type Description Default
ignore_errors bool

Whether to ignore individual errors during the restore process and attempt to restore all secrets.

False
delete_secrets bool

Whether to delete the secrets that have been successfully restored from the backup secrets store. Setting this flag effectively moves all secrets from the backup secrets store to the primary secrets store.

False
noqa: DAR401

Raises: BackupSecretsStoreNotConfiguredError: if no backup secrets store is configured.

Source code in src/zenml/zen_stores/sql_zen_store.py
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
def restore_secrets(
    self, ignore_errors: bool = False, delete_secrets: bool = False
) -> None:
    """Restore all secrets from the configured backup secrets store.

    Args:
        ignore_errors: Whether to ignore individual errors during the
            restore process and attempt to restore all secrets.
        delete_secrets: Whether to delete the secrets that have been
            successfully restored from the backup secrets store. Setting
            this flag effectively moves all secrets from the backup secrets
            store to the primary secrets store.

    # noqa: DAR401
    Raises:
        BackupSecretsStoreNotConfiguredError: if no backup secrets store is
            configured.
    """
    if not self.backup_secrets_store:
        raise BackupSecretsStoreNotConfiguredError(
            "Unable to restore secrets: No backup secrets store is "
            "configured."
        )

    with Session(self.engine) as session:
        secrets_in_db = session.exec(select(SecretSchema)).all()

    for secret in secrets_in_db:
        try:
            values = self._get_backup_secret_values(secret_id=secret.id)
        except Exception:
            logger.exception(
                f"Failed to get backup secret values for secret with ID "
                f"{secret.id}."
            )
            if ignore_errors:
                continue
            raise

        try:
            self._update_secret_values(
                secret_id=secret.id,
                values=cast(Dict[str, Optional[str]], values),
                overwrite=True,
                backup=False,
            )
        except Exception:
            logger.exception(
                f"Failed to restore secret with ID {secret.id}. "
            )
            if ignore_errors:
                continue
            raise

        if delete_secrets:
            try:
                self._delete_backup_secret_values(secret_id=secret.id)
            except Exception:
                logger.exception(
                    f"Failed to delete backup secret with ID {secret.id} "
                    f"from the backup secrets store after restoring it to "
                    f"the primary secrets store."
                )
                if ignore_errors:
                    continue
                raise
rotate_api_key(service_account_id: UUID, api_key_name_or_id: Union[str, UUID], rotate_request: APIKeyRotateRequest) -> APIKeyResponse

Rotate an API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to rotate the API key.

required
api_key_name_or_id Union[str, UUID]

The name or ID of the API key to rotate.

required
rotate_request APIKeyRotateRequest

The rotate request on the API key.

required

Returns:

Type Description
APIKeyResponse

The updated API key.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def rotate_api_key(
    self,
    service_account_id: UUID,
    api_key_name_or_id: Union[str, UUID],
    rotate_request: APIKeyRotateRequest,
) -> APIKeyResponse:
    """Rotate an API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to
            rotate the API key.
        api_key_name_or_id: The name or ID of the API key to rotate.
        rotate_request: The rotate request on the API key.

    Returns:
        The updated API key.
    """
    with Session(self.engine) as session:
        self._set_request_user_id(
            request_model=rotate_request, session=session
        )

        api_key = self._get_api_key(
            service_account_id=service_account_id,
            api_key_name_or_id=api_key_name_or_id,
            session=session,
        )

        _, new_key = api_key.rotate(rotate_request)
        session.add(api_key)
        session.commit()

        # Refresh the Model that was just created
        session.refresh(api_key)
        api_key_model = api_key.to_model()
        api_key_model.set_key(new_key)

        return api_key_model
run_template(template_id: UUID, run_configuration: Optional[PipelineRunConfiguration] = None) -> NoReturn

Run a template.

Parameters:

Name Type Description Default
template_id UUID

The ID of the template to run.

required
run_configuration Optional[PipelineRunConfiguration]

Configuration for the run.

None

Raises:

Type Description
NotImplementedError

Always.

Source code in src/zenml/zen_stores/sql_zen_store.py
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
def run_template(
    self,
    template_id: UUID,
    run_configuration: Optional[PipelineRunConfiguration] = None,
) -> NoReturn:
    """Run a template.

    Args:
        template_id: The ID of the template to run.
        run_configuration: Configuration for the run.

    Raises:
        NotImplementedError: Always.
    """
    raise NotImplementedError(
        "Running a template is not possible with a local store."
    )
set_filter_project_id(filter_model: ProjectScopedFilter, project_name_or_id: Optional[Union[UUID, str]] = None) -> None

Set the project ID on a filter model.

Parameters:

Name Type Description Default
filter_model ProjectScopedFilter

The filter model to set the project ID on.

required
project_name_or_id Optional[Union[UUID, str]]

The project to set the scope for. If not provided, the project scope is determined from the request project filter or the default project, in that order.

None
Source code in src/zenml/zen_stores/sql_zen_store.py
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
def set_filter_project_id(
    self,
    filter_model: ProjectScopedFilter,
    project_name_or_id: Optional[Union[UUID, str]] = None,
) -> None:
    """Set the project ID on a filter model.

    Args:
        filter_model: The filter model to set the project ID on.
        project_name_or_id: The project to set the scope for. If not
            provided, the project scope is determined from the request
            project filter or the default project, in that order.
    """
    with Session(self.engine) as session:
        self._set_filter_project_id(
            filter_model=filter_model,
            session=session,
            project_name_or_id=project_name_or_id,
        )
update_action(action_id: UUID, action_update: ActionUpdate) -> ActionResponse

Update an existing action.

Parameters:

Name Type Description Default
action_id UUID

The ID of the action to update.

required
action_update ActionUpdate

The update to be applied to the action.

required

Returns:

Type Description
ActionResponse

The updated action.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def update_action(
    self,
    action_id: UUID,
    action_update: ActionUpdate,
) -> ActionResponse:
    """Update an existing action.

    Args:
        action_id: The ID of the action to update.
        action_update: The update to be applied to the action.

    Returns:
        The updated action.
    """
    with Session(self.engine) as session:
        action = self._get_schema_by_id(
            resource_id=action_id,
            schema_class=ActionSchema,
            session=session,
        )

        if action_update.service_account_id:
            # Verify that the given service account exists
            self._get_account_schema(
                account_name_or_id=action_update.service_account_id,
                session=session,
                service_account=True,
            )

        # In case of a renaming update, make sure no action already exists
        # with that name
        self._verify_name_uniqueness(
            resource=action_update,
            schema=action,
            session=session,
        )

        action.update(action_update=action_update)
        session.add(action)
        session.commit()

        session.refresh(action)

        return action.to_model(
            include_metadata=True, include_resources=True
        )
update_api_key(service_account_id: UUID, api_key_name_or_id: Union[str, UUID], api_key_update: APIKeyUpdate) -> APIKeyResponse

Update an API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to update the API key.

required
api_key_name_or_id Union[str, UUID]

The name or ID of the API key to update.

required
api_key_update APIKeyUpdate

The update request on the API key.

required

Returns:

Type Description
APIKeyResponse

The updated API key.

Raises:

Type Description
EntityExistsError

if the API key update would result in a name conflict with an existing API key for the same service account.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def update_api_key(
    self,
    service_account_id: UUID,
    api_key_name_or_id: Union[str, UUID],
    api_key_update: APIKeyUpdate,
) -> APIKeyResponse:
    """Update an API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to update
            the API key.
        api_key_name_or_id: The name or ID of the API key to update.
        api_key_update: The update request on the API key.

    Returns:
        The updated API key.

    Raises:
        EntityExistsError: if the API key update would result in a name
            conflict with an existing API key for the same service account.
    """
    with Session(self.engine) as session:
        api_key = self._get_api_key(
            service_account_id=service_account_id,
            api_key_name_or_id=api_key_name_or_id,
            session=session,
        )

        if api_key_update.name and api_key.name != api_key_update.name:
            # Check if a key with the new name already exists for the same
            # service account
            try:
                self._get_api_key(
                    service_account_id=service_account_id,
                    api_key_name_or_id=api_key_update.name,
                    session=session,
                )

                raise EntityExistsError(
                    f"Unable to update API key with name "
                    f"'{api_key_update.name}': Found an existing API key "
                    "with the same name configured for the same "
                    f"'{api_key.service_account.name}' service account."
                )
            except KeyError:
                pass

        api_key.update(update=api_key_update)
        session.add(api_key)
        session.commit()

        # Refresh the Model that was just created
        session.refresh(api_key)
        return api_key.to_model(
            include_metadata=True, include_resources=True
        )
update_artifact(artifact_id: UUID, artifact_update: ArtifactUpdate) -> ArtifactResponse

Updates an artifact.

Parameters:

Name Type Description Default
artifact_id UUID

The ID of the artifact to update.

required
artifact_update ArtifactUpdate

The update to be applied to the artifact.

required

Returns:

Type Description
ArtifactResponse

The updated artifact.

Source code in src/zenml/zen_stores/sql_zen_store.py
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
def update_artifact(
    self, artifact_id: UUID, artifact_update: ArtifactUpdate
) -> ArtifactResponse:
    """Updates an artifact.

    Args:
        artifact_id: The ID of the artifact to update.
        artifact_update: The update to be applied to the artifact.

    Returns:
        The updated artifact.
    """
    with Session(self.engine) as session:
        existing_artifact = self._get_schema_by_id(
            resource_id=artifact_id,
            schema_class=ArtifactSchema,
            session=session,
        )

        self._verify_name_uniqueness(
            resource=artifact_update,
            schema=existing_artifact,
            session=session,
        )

        # Update the schema itself.
        existing_artifact.update(artifact_update=artifact_update)
        session.add(existing_artifact)
        session.commit()
        session.refresh(existing_artifact)

        # Handle tag updates.
        self._attach_tags_to_resources(
            tags=artifact_update.add_tags,
            resources=existing_artifact,
            session=session,
        )
        self._detach_tags_from_resources(
            tags=artifact_update.remove_tags,
            resources=existing_artifact,
            session=session,
        )
        session.refresh(existing_artifact)
        return existing_artifact.to_model(
            include_metadata=True, include_resources=True
        )
update_artifact_version(artifact_version_id: UUID, artifact_version_update: ArtifactVersionUpdate) -> ArtifactVersionResponse

Updates an artifact version.

Parameters:

Name Type Description Default
artifact_version_id UUID

The ID of the artifact version to update.

required
artifact_version_update ArtifactVersionUpdate

The update to be applied to the artifact version.

required

Returns:

Type Description
ArtifactVersionResponse

The updated artifact version.

Source code in src/zenml/zen_stores/sql_zen_store.py
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
def update_artifact_version(
    self,
    artifact_version_id: UUID,
    artifact_version_update: ArtifactVersionUpdate,
) -> ArtifactVersionResponse:
    """Updates an artifact version.

    Args:
        artifact_version_id: The ID of the artifact version to update.
        artifact_version_update: The update to be applied to the artifact
            version.

    Returns:
        The updated artifact version.
    """
    with Session(self.engine) as session:
        existing_artifact_version = self._get_schema_by_id(
            resource_id=artifact_version_id,
            schema_class=ArtifactVersionSchema,
            session=session,
        )

        # Update the schema itself.
        existing_artifact_version.update(
            artifact_version_update=artifact_version_update
        )
        session.add(existing_artifact_version)
        session.commit()
        session.refresh(existing_artifact_version)

        # Handle tag updates.
        self._attach_tags_to_resources(
            tags=artifact_version_update.add_tags,
            resources=existing_artifact_version,
            session=session,
        )
        self._detach_tags_from_resources(
            tags=artifact_version_update.remove_tags,
            resources=existing_artifact_version,
            session=session,
        )

        session.refresh(existing_artifact_version)
        return existing_artifact_version.to_model(
            include_metadata=True, include_resources=True
        )
update_authorized_device(device_id: UUID, update: OAuthDeviceUpdate) -> OAuthDeviceResponse

Updates an existing OAuth 2.0 authorized device for internal use.

Parameters:

Name Type Description Default
device_id UUID

The ID of the device to update.

required
update OAuthDeviceUpdate

The update to be applied to the device.

required

Returns:

Type Description
OAuthDeviceResponse

The updated OAuth 2.0 authorized device.

Source code in src/zenml/zen_stores/sql_zen_store.py
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
def update_authorized_device(
    self, device_id: UUID, update: OAuthDeviceUpdate
) -> OAuthDeviceResponse:
    """Updates an existing OAuth 2.0 authorized device for internal use.

    Args:
        device_id: The ID of the device to update.
        update: The update to be applied to the device.

    Returns:
        The updated OAuth 2.0 authorized device.
    """
    with Session(self.engine) as session:
        existing_device = self._get_schema_by_id(
            resource_id=device_id,
            schema_class=OAuthDeviceSchema,
            session=session,
            resource_type="authorized device",
        )

        existing_device.update(update)

        session.add(existing_device)
        session.commit()

        return existing_device.to_model(
            include_metadata=True, include_resources=True
        )
update_code_repository(code_repository_id: UUID, update: CodeRepositoryUpdate) -> CodeRepositoryResponse

Updates an existing code repository.

Parameters:

Name Type Description Default
code_repository_id UUID

The ID of the code repository to update.

required
update CodeRepositoryUpdate

The update to be applied to the code repository.

required

Returns:

Type Description
CodeRepositoryResponse

The updated code repository.

Source code in src/zenml/zen_stores/sql_zen_store.py
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
def update_code_repository(
    self, code_repository_id: UUID, update: CodeRepositoryUpdate
) -> CodeRepositoryResponse:
    """Updates an existing code repository.

    Args:
        code_repository_id: The ID of the code repository to update.
        update: The update to be applied to the code repository.

    Returns:
        The updated code repository.
    """
    with Session(self.engine) as session:
        existing_repo = self._get_schema_by_id(
            resource_id=code_repository_id,
            schema_class=CodeRepositorySchema,
            session=session,
        )

        self._verify_name_uniqueness(
            resource=update,
            schema=existing_repo,
            session=session,
        )

        existing_repo.update(update)

        session.add(existing_repo)
        session.commit()

        return existing_repo.to_model(
            include_metadata=True, include_resources=True
        )
update_event_source(event_source_id: UUID, event_source_update: EventSourceUpdate) -> EventSourceResponse

Update an existing event_source.

Parameters:

Name Type Description Default
event_source_id UUID

The ID of the event_source to update.

required
event_source_update EventSourceUpdate

The update to be applied to the event_source.

required

Returns:

Type Description
EventSourceResponse

The updated event_source.

Source code in src/zenml/zen_stores/sql_zen_store.py
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
def update_event_source(
    self,
    event_source_id: UUID,
    event_source_update: EventSourceUpdate,
) -> EventSourceResponse:
    """Update an existing event_source.

    Args:
        event_source_id: The ID of the event_source to update.
        event_source_update: The update to be applied to the event_source.

    Returns:
        The updated event_source.
    """
    with Session(self.engine) as session:
        event_source = self._get_schema_by_id(
            resource_id=event_source_id,
            schema_class=EventSourceSchema,
            session=session,
        )

        self._verify_name_uniqueness(
            resource=event_source_update,
            schema=event_source,
            session=session,
        )

        event_source.update(update=event_source_update)
        session.add(event_source)
        session.commit()

        # Refresh the event_source that was just created
        session.refresh(event_source)
        return event_source.to_model(
            include_metadata=True, include_resources=True
        )
update_flavor(flavor_id: UUID, flavor_update: FlavorUpdate) -> FlavorResponse

Updates an existing user.

Parameters:

Name Type Description Default
flavor_id UUID

The id of the flavor to update.

required
flavor_update FlavorUpdate

The update to be applied to the flavor.

required

Returns:

Type Description
FlavorResponse

The updated flavor.

Raises:

Type Description
EntityExistsError

If a flavor with the same name and type already exists.

Source code in src/zenml/zen_stores/sql_zen_store.py
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
def update_flavor(
    self, flavor_id: UUID, flavor_update: FlavorUpdate
) -> FlavorResponse:
    """Updates an existing user.

    Args:
        flavor_id: The id of the flavor to update.
        flavor_update: The update to be applied to the flavor.

    Returns:
        The updated flavor.

    Raises:
        EntityExistsError: If a flavor with the same name and type already
            exists.
    """
    with Session(self.engine) as session:
        existing_flavor = self._get_schema_by_id(
            resource_id=flavor_id,
            schema_class=FlavorSchema,
            session=session,
        )

        # Check if flavor with the new domain key (name, type) already
        # exists
        if (
            flavor_update.name
            and flavor_update.name != existing_flavor.name
            or flavor_update.type
            and flavor_update.type != existing_flavor.type
        ):
            other_flavor = session.exec(
                select(FlavorSchema)
                .where(
                    FlavorSchema.name
                    == (flavor_update.name or existing_flavor.name)
                )
                .where(
                    FlavorSchema.type
                    == (flavor_update.type or existing_flavor.type)
                )
            ).first()

            if other_flavor is not None:
                raise EntityExistsError(
                    f"Unable to update '{existing_flavor.type}' flavor "
                    f"with name '{existing_flavor.name}': Found an existing "
                    f"flavor with the same name and type."
                )

        existing_flavor.update(flavor_update=flavor_update)
        session.add(existing_flavor)
        session.commit()

        # Refresh the Model that was just created
        session.refresh(existing_flavor)
        return existing_flavor.to_model(
            include_metadata=True, include_resources=True
        )
update_internal_api_key(api_key_id: UUID, api_key_update: APIKeyInternalUpdate) -> APIKeyResponse

Update an API key with internal details.

Parameters:

Name Type Description Default
api_key_id UUID

The ID of the API key.

required
api_key_update APIKeyInternalUpdate

The update request on the API key.

required

Returns:

Type Description
APIKeyResponse

The updated API key.

Raises:

Type Description
KeyError

if the API key doesn't exist.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def update_internal_api_key(
    self, api_key_id: UUID, api_key_update: APIKeyInternalUpdate
) -> APIKeyResponse:
    """Update an API key with internal details.

    Args:
        api_key_id: The ID of the API key.
        api_key_update: The update request on the API key.

    Returns:
        The updated API key.

    Raises:
        KeyError: if the API key doesn't exist.
    """
    with Session(self.engine) as session:
        api_key = session.exec(
            select(APIKeySchema).where(APIKeySchema.id == api_key_id)
        ).first()

        if not api_key:
            raise KeyError(f"API key with ID {api_key_id} not found.")

        api_key.internal_update(update=api_key_update)
        session.add(api_key)
        session.commit()

        # Refresh the Model that was just created
        session.refresh(api_key)
        return api_key.to_model(
            include_metadata=True, include_resources=True
        )
update_internal_authorized_device(device_id: UUID, update: OAuthDeviceInternalUpdate) -> OAuthDeviceInternalResponse

Updates an existing OAuth 2.0 authorized device.

Parameters:

Name Type Description Default
device_id UUID

The ID of the device to update.

required
update OAuthDeviceInternalUpdate

The update to be applied to the device.

required

Returns:

Type Description
OAuthDeviceInternalResponse

The updated OAuth 2.0 authorized device.

Source code in src/zenml/zen_stores/sql_zen_store.py
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
def update_internal_authorized_device(
    self, device_id: UUID, update: OAuthDeviceInternalUpdate
) -> OAuthDeviceInternalResponse:
    """Updates an existing OAuth 2.0 authorized device.

    Args:
        device_id: The ID of the device to update.
        update: The update to be applied to the device.

    Returns:
        The updated OAuth 2.0 authorized device.
    """
    with Session(self.engine) as session:
        existing_device = self._get_schema_by_id(
            resource_id=device_id,
            schema_class=OAuthDeviceSchema,
            session=session,
            resource_type="authorized device",
        )

        (
            _,
            user_code,
            device_code,
        ) = existing_device.internal_update(update)

        session.add(existing_device)
        session.commit()

        device_model = existing_device.to_internal_model(
            include_metadata=True, include_resources=True
        )
        if user_code:
            # Replace the hashed user code with the original user code
            device_model.user_code = user_code

        if device_code:
            # Replace the hashed device code with the original device code
            device_model.device_code = device_code

        return device_model
update_model(model_id: UUID, model_update: ModelUpdate) -> ModelResponse

Updates an existing model.

Parameters:

Name Type Description Default
model_id UUID

UUID of the model to be updated.

required
model_update ModelUpdate

the Model to be updated.

required

Raises:

Type Description
KeyError

specified ID not found.

Returns:

Type Description
ModelResponse

The updated model.

Source code in src/zenml/zen_stores/sql_zen_store.py
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
def update_model(
    self,
    model_id: UUID,
    model_update: ModelUpdate,
) -> ModelResponse:
    """Updates an existing model.

    Args:
        model_id: UUID of the model to be updated.
        model_update: the Model to be updated.

    Raises:
        KeyError: specified ID not found.

    Returns:
        The updated model.
    """
    with Session(self.engine) as session:
        existing_model = session.exec(
            select(ModelSchema).where(ModelSchema.id == model_id)
        ).first()

        if not existing_model:
            raise KeyError(f"Model with ID {model_id} not found.")

        self._verify_name_uniqueness(
            resource=model_update,
            schema=existing_model,
            session=session,
        )

        existing_model.update(model_update=model_update)

        session.add(existing_model)
        session.commit()

        # Refresh the Model that was just created
        session.refresh(existing_model)

        self._attach_tags_to_resources(
            tags=model_update.add_tags,
            resources=existing_model,
            session=session,
        )
        self._detach_tags_from_resources(
            tags=model_update.remove_tags,
            resources=existing_model,
            session=session,
        )

        session.refresh(existing_model)

        return existing_model.to_model(
            include_metadata=True, include_resources=True
        )
update_model_version(model_version_id: UUID, model_version_update_model: ModelVersionUpdate) -> ModelVersionResponse

Get all model versions by filter.

Parameters:

Name Type Description Default
model_version_id UUID

The ID of model version to be updated.

required
model_version_update_model ModelVersionUpdate

The model version to be updated.

required

Returns:

Type Description
ModelVersionResponse

An updated model version.

Raises:

Type Description
KeyError

If the model version not found

RuntimeError

If there is a model version with target stage, but force flag is off

Source code in src/zenml/zen_stores/sql_zen_store.py
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
def update_model_version(
    self,
    model_version_id: UUID,
    model_version_update_model: ModelVersionUpdate,
) -> ModelVersionResponse:
    """Get all model versions by filter.

    Args:
        model_version_id: The ID of model version to be updated.
        model_version_update_model: The model version to be updated.

    Returns:
        An updated model version.

    Raises:
        KeyError: If the model version not found
        RuntimeError: If there is a model version with target stage,
            but `force` flag is off
    """
    with Session(self.engine) as session:
        existing_model_version = session.exec(
            select(ModelVersionSchema).where(
                ModelVersionSchema.id == model_version_id
            )
        ).first()

        if not existing_model_version:
            raise KeyError(f"Model version {model_version_id} not found.")

        stage = None
        if (stage_ := model_version_update_model.stage) is not None:
            stage = getattr(stage_, "value", stage_)

            existing_model_version_in_target_stage = session.exec(
                select(ModelVersionSchema)
                .where(
                    ModelVersionSchema.model_id
                    == existing_model_version.model_id
                )
                .where(ModelVersionSchema.stage == stage)
            ).first()

            if (
                existing_model_version_in_target_stage is not None
                and existing_model_version_in_target_stage.id
                != existing_model_version.id
            ):
                if not model_version_update_model.force:
                    raise RuntimeError(
                        f"Model version {existing_model_version_in_target_stage.name} is "
                        f"in {stage}, but `force` flag is False."
                    )
                else:
                    existing_model_version_in_target_stage.update(
                        target_stage=ModelStages.ARCHIVED.value
                    )
                    session.add(existing_model_version_in_target_stage)

                    logger.info(
                        f"Model version {existing_model_version_in_target_stage.name} has been set to {ModelStages.ARCHIVED.value}."
                    )

        existing_model_version.update(
            target_stage=stage,
            target_name=model_version_update_model.name,
            target_description=model_version_update_model.description,
        )
        session.add(existing_model_version)
        session.commit()
        session.refresh(existing_model_version)

        self._attach_tags_to_resources(
            tags=model_version_update_model.add_tags,
            resources=existing_model_version,
            session=session,
        )
        self._detach_tags_from_resources(
            tags=model_version_update_model.remove_tags,
            resources=existing_model_version,
            session=session,
        )
        session.refresh(existing_model_version)
        return existing_model_version.to_model(
            include_metadata=True, include_resources=True
        )
update_onboarding_state(completed_steps: Set[str]) -> None

Update the server onboarding state.

Parameters:

Name Type Description Default
completed_steps Set[str]

Newly completed onboarding steps.

required
Source code in src/zenml/zen_stores/sql_zen_store.py
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
def update_onboarding_state(self, completed_steps: Set[str]) -> None:
    """Update the server onboarding state.

    Args:
        completed_steps: Newly completed onboarding steps.
    """
    with Session(self.engine) as session:
        self._update_onboarding_state(
            completed_steps=completed_steps, session=session
        )
update_pipeline(pipeline_id: UUID, pipeline_update: PipelineUpdate) -> PipelineResponse

Updates a pipeline.

Parameters:

Name Type Description Default
pipeline_id UUID

The ID of the pipeline to be updated.

required
pipeline_update PipelineUpdate

The update to be applied.

required

Returns:

Type Description
PipelineResponse

The updated pipeline.

Source code in src/zenml/zen_stores/sql_zen_store.py
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
def update_pipeline(
    self,
    pipeline_id: UUID,
    pipeline_update: PipelineUpdate,
) -> PipelineResponse:
    """Updates a pipeline.

    Args:
        pipeline_id: The ID of the pipeline to be updated.
        pipeline_update: The update to be applied.

    Returns:
        The updated pipeline.
    """
    with Session(self.engine) as session:
        # Check if pipeline with the given ID exists
        existing_pipeline = self._get_schema_by_id(
            resource_id=pipeline_id,
            schema_class=PipelineSchema,
            session=session,
        )

        existing_pipeline.update(pipeline_update)
        session.add(existing_pipeline)
        session.commit()
        session.refresh(existing_pipeline)

        self._attach_tags_to_resources(
            tags=pipeline_update.add_tags,
            resources=existing_pipeline,
            session=session,
        )
        self._detach_tags_from_resources(
            tags=pipeline_update.remove_tags,
            resources=existing_pipeline,
            session=session,
        )
        session.refresh(existing_pipeline)

        return existing_pipeline.to_model(
            include_metadata=True, include_resources=True
        )
update_project(project_id: UUID, project_update: ProjectUpdate) -> ProjectResponse

Update an existing project.

Parameters:

Name Type Description Default
project_id UUID

The ID of the project to be updated.

required
project_update ProjectUpdate

The update to be applied to the project.

required

Returns:

Type Description
ProjectResponse

The updated project.

Raises:

Type Description
IllegalOperationError

If the request tries to update the name of the default project.

Source code in src/zenml/zen_stores/sql_zen_store.py
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
def update_project(
    self, project_id: UUID, project_update: ProjectUpdate
) -> ProjectResponse:
    """Update an existing project.

    Args:
        project_id: The ID of the project to be updated.
        project_update: The update to be applied to the project.

    Returns:
        The updated project.

    Raises:
        IllegalOperationError: If the request tries to update the name of
            the default project.
    """
    with Session(self.engine) as session:
        existing_project = self._get_schema_by_id(
            resource_id=project_id,
            schema_class=ProjectSchema,
            session=session,
        )
        if (
            existing_project.name == self._default_project_name
            and "name" in project_update.model_fields_set
            and project_update.name != existing_project.name
        ):
            raise IllegalOperationError(
                "The name of the default project cannot be changed."
            )

        self._verify_name_uniqueness(
            resource=project_update,
            schema=existing_project,
            session=session,
        )

        # Update the project
        existing_project.update(project_update=project_update)
        session.add(existing_project)
        session.commit()

        # Refresh the Model that was just created
        session.refresh(existing_project)
        return existing_project.to_model(
            include_metadata=True, include_resources=True
        )
update_run(run_id: UUID, run_update: PipelineRunUpdate) -> PipelineRunResponse

Updates a pipeline run.

Parameters:

Name Type Description Default
run_id UUID

The ID of the pipeline run to update.

required
run_update PipelineRunUpdate

The update to be applied to the pipeline run.

required

Returns:

Type Description
PipelineRunResponse

The updated pipeline run.

Source code in src/zenml/zen_stores/sql_zen_store.py
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
def update_run(
    self, run_id: UUID, run_update: PipelineRunUpdate
) -> PipelineRunResponse:
    """Updates a pipeline run.

    Args:
        run_id: The ID of the pipeline run to update.
        run_update: The update to be applied to the pipeline run.

    Returns:
        The updated pipeline run.
    """
    with Session(self.engine) as session:
        # Check if pipeline run with the given ID exists
        existing_run = self._get_schema_by_id(
            resource_id=run_id,
            schema_class=PipelineRunSchema,
            session=session,
        )

        existing_run.update(run_update=run_update)
        session.add(existing_run)
        session.commit()
        session.refresh(existing_run)

        self._attach_tags_to_resources(
            tags=run_update.add_tags,
            resources=existing_run,
            session=session,
        )
        self._detach_tags_from_resources(
            tags=run_update.remove_tags,
            resources=existing_run,
            session=session,
        )
        session.refresh(existing_run)
        return existing_run.to_model(
            include_metadata=True, include_resources=True
        )
update_run_step(step_run_id: UUID, step_run_update: StepRunUpdate) -> StepRunResponse

Updates a step run.

Parameters:

Name Type Description Default
step_run_id UUID

The ID of the step to update.

required
step_run_update StepRunUpdate

The update to be applied to the step.

required

Returns:

Type Description
StepRunResponse

The updated step run.

Source code in src/zenml/zen_stores/sql_zen_store.py
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
def update_run_step(
    self,
    step_run_id: UUID,
    step_run_update: StepRunUpdate,
) -> StepRunResponse:
    """Updates a step run.

    Args:
        step_run_id: The ID of the step to update.
        step_run_update: The update to be applied to the step.

    Returns:
        The updated step run.
    """
    with Session(self.engine) as session:
        # Check if the step exists
        existing_step_run = self._get_schema_by_id(
            resource_id=step_run_id,
            schema_class=StepRunSchema,
            session=session,
        )

        # Update the step
        existing_step_run.update(step_run_update)
        session.add(existing_step_run)

        # Update the artifacts.
        for name, artifact_version_ids in step_run_update.outputs.items():
            for artifact_version_id in artifact_version_ids:
                self._set_run_step_output_artifact(
                    step_run=existing_step_run,
                    artifact_version_id=artifact_version_id,
                    name=name,
                    session=session,
                )

        # Update loaded artifacts.
        for (
            artifact_name,
            artifact_version_id,
        ) in step_run_update.loaded_artifact_versions.items():
            self._set_run_step_input_artifact(
                step_run=existing_step_run,
                artifact_version_id=artifact_version_id,
                name=artifact_name,
                input_type=StepRunInputArtifactType.MANUAL,
                session=session,
            )

        self._update_pipeline_run_status(
            pipeline_run_id=existing_step_run.pipeline_run_id,
            session=session,
        )

        session.commit()
        session.refresh(existing_step_run)

        return existing_step_run.to_model(
            include_metadata=True, include_resources=True
        )
update_run_template(template_id: UUID, template_update: RunTemplateUpdate) -> RunTemplateResponse

Updates a run template.

Parameters:

Name Type Description Default
template_id UUID

The ID of the template to update.

required
template_update RunTemplateUpdate

The update to apply.

required

Returns:

Type Description
RunTemplateResponse

The updated template.

Source code in src/zenml/zen_stores/sql_zen_store.py
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
def update_run_template(
    self,
    template_id: UUID,
    template_update: RunTemplateUpdate,
) -> RunTemplateResponse:
    """Updates a run template.

    Args:
        template_id: The ID of the template to update.
        template_update: The update to apply.

    Returns:
        The updated template.
    """
    with Session(self.engine) as session:
        template = self._get_schema_by_id(
            resource_id=template_id,
            schema_class=RunTemplateSchema,
            session=session,
        )

        template.update(template_update)
        session.add(template)
        session.commit()
        session.refresh(template)

        self._attach_tags_to_resources(
            tags=template_update.add_tags,
            resources=template,
            session=session,
        )
        self._detach_tags_from_resources(
            tags=template_update.remove_tags,
            resources=template,
            session=session,
        )

        session.refresh(template)

        return template.to_model(
            include_metadata=True, include_resources=True
        )
update_schedule(schedule_id: UUID, schedule_update: ScheduleUpdate) -> ScheduleResponse

Updates a schedule.

Parameters:

Name Type Description Default
schedule_id UUID

The ID of the schedule to be updated.

required
schedule_update ScheduleUpdate

The update to be applied.

required

Returns:

Type Description
ScheduleResponse

The updated schedule.

Source code in src/zenml/zen_stores/sql_zen_store.py
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
def update_schedule(
    self,
    schedule_id: UUID,
    schedule_update: ScheduleUpdate,
) -> ScheduleResponse:
    """Updates a schedule.

    Args:
        schedule_id: The ID of the schedule to be updated.
        schedule_update: The update to be applied.

    Returns:
        The updated schedule.
    """
    with Session(self.engine) as session:
        # Check if schedule with the given ID exists
        existing_schedule = self._get_schema_by_id(
            resource_id=schedule_id,
            schema_class=ScheduleSchema,
            session=session,
        )

        self._verify_name_uniqueness(
            resource=schedule_update,
            schema=existing_schedule,
            session=session,
        )

        # Update the schedule
        existing_schedule = existing_schedule.update(schedule_update)
        session.add(existing_schedule)
        session.commit()
        return existing_schedule.to_model(
            include_metadata=True, include_resources=True
        )
update_secret(secret_id: UUID, secret_update: SecretUpdate) -> SecretResponse

Updates a secret.

Secret values that are specified as None in the update that are present in the existing secret are removed from the existing secret. Values that are present in both secrets are overwritten. All other values in both the existing secret and the update are kept (merged).

If the update includes a change of name or scope, the scoping rules enforced in the secrets store are used to validate the update:

  • a user cannot own two private secrets with the same name
  • two public secrets cannot have the same name

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret to be updated.

required
secret_update SecretUpdate

The update to be applied.

required

Returns:

Type Description
SecretResponse

The updated secret.

Raises:

Type Description
KeyError

if the secret doesn't exist.

EntityExistsError

If a secret with the same name already exists in the same scope.

IllegalOperationError

if the secret is private and the current user is not the owner of the secret.

Source code in src/zenml/zen_stores/sql_zen_store.py
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
def update_secret(
    self, secret_id: UUID, secret_update: SecretUpdate
) -> SecretResponse:
    """Updates a secret.

    Secret values that are specified as `None` in the update that are
    present in the existing secret are removed from the existing secret.
    Values that are present in both secrets are overwritten. All other
    values in both the existing secret and the update are kept (merged).

    If the update includes a change of name or scope, the scoping rules
    enforced in the secrets store are used to validate the update:

    - a user cannot own two private secrets with the same name
    - two public secrets cannot have the same name

    Args:
        secret_id: The ID of the secret to be updated.
        secret_update: The update to be applied.

    Returns:
        The updated secret.

    Raises:
        KeyError: if the secret doesn't exist.
        EntityExistsError: If a secret with the same name already exists in
            the same scope.
        IllegalOperationError: if the secret is private and the current user
            is not the owner of the secret.
    """
    with Session(self.engine) as session:
        existing_secret = session.exec(
            select(SecretSchema).where(SecretSchema.id == secret_id)
        ).first()

        active_user = self._get_active_user(session)

        if not existing_secret or (
            # Private secrets are only accessible to their owner
            existing_secret.private
            and existing_secret.user.id != active_user.id
        ):
            raise KeyError(
                f"Secret with ID {secret_id} not found or is private and "
                "not owned by the current user."
            )

        if (
            secret_update.private is not None
            and existing_secret.user.id != active_user.id
        ):
            raise IllegalOperationError(
                "Only the user who created the secret is allowed to update "
                "its private status."
            )

        # A change in name or scope requires a check of the scoping rules.
        if (
            secret_update.name is not None
            and existing_secret.name != secret_update.name
            or secret_update.private is not None
            and existing_secret.private != secret_update.private
        ):
            secret_exists, msg = self._check_sql_secret_scope(
                session=session,
                secret_name=secret_update.name or existing_secret.name,
                private=secret_update.private
                if secret_update.private is not None
                else existing_secret.private,
                user=existing_secret.user.id,
                exclude_secret_id=secret_id,
            )

            if secret_exists:
                raise EntityExistsError(msg)

        existing_secret.update(
            secret_update=secret_update,
        )
        session.add(existing_secret)
        session.commit()

        # Refresh the Model that was just created
        session.refresh(existing_secret)
        secret_model = existing_secret.to_model(
            include_metadata=True, include_resources=True
        )

    if secret_update.values is not None:
        # Update the secret values in the configured secrets store
        updated_values = self._update_secret_values(
            secret_id=secret_id,
            values=secret_update.get_secret_values_update(),
        )
        secret_model.set_secrets(updated_values)
    else:
        secret_model.set_secrets(self._get_secret_values(secret_id))

    return secret_model
update_server_settings(settings_update: ServerSettingsUpdate) -> ServerSettingsResponse

Update the server settings.

Parameters:

Name Type Description Default
settings_update ServerSettingsUpdate

The server settings update.

required

Returns:

Type Description
ServerSettingsResponse

The updated server settings.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def update_server_settings(
    self, settings_update: ServerSettingsUpdate
) -> ServerSettingsResponse:
    """Update the server settings.

    Args:
        settings_update: The server settings update.

    Returns:
        The updated server settings.
    """
    with Session(self.engine) as session:
        settings = self._get_server_settings(session=session)

        analytics_metadata = settings_update.model_dump(
            include={
                "enable_analytics",
                "display_announcements",
                "display_updates",
            },
            exclude_none=True,
        )
        # Filter to only include the values that changed in this update
        analytics_metadata = {
            key: value
            for key, value in analytics_metadata.items()
            if getattr(settings, key) != value
        }

        track(
            event=AnalyticsEvent.SERVER_SETTINGS_UPDATED,
            metadata=analytics_metadata,
        )

        settings.update(settings_update)
        session.add(settings)
        session.commit()
        session.refresh(settings)

        return settings.to_model(
            include_metadata=True, include_resources=True
        )
update_service(service_id: UUID, update: ServiceUpdate) -> ServiceResponse

Update a service.

Parameters:

Name Type Description Default
service_id UUID

The ID of the service to update.

required
update ServiceUpdate

The update to be applied to the service.

required

Returns:

Type Description
ServiceResponse

The updated service.

Source code in src/zenml/zen_stores/sql_zen_store.py
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
def update_service(
    self, service_id: UUID, update: ServiceUpdate
) -> ServiceResponse:
    """Update a service.

    Args:
        service_id: The ID of the service to update.
        update: The update to be applied to the service.

    Returns:
        The updated service.
    """
    with Session(self.engine) as session:
        existing_service = self._get_schema_by_id(
            resource_id=service_id,
            schema_class=ServiceSchema,
            session=session,
        )

        self._get_reference_schema_by_id(
            resource=existing_service,
            reference_schema=ModelVersionSchema,
            reference_id=update.model_version_id,
            session=session,
        )

        # Update the schema itself.
        existing_service.update(update=update)
        logger.debug("Updated service: %s", existing_service)
        session.add(existing_service)
        session.commit()
        session.refresh(existing_service)
        return existing_service.to_model(
            include_metadata=True, include_resources=True
        )
update_service_account(service_account_name_or_id: Union[str, UUID], service_account_update: ServiceAccountUpdate) -> ServiceAccountResponse

Updates an existing service account.

Parameters:

Name Type Description Default
service_account_name_or_id Union[str, UUID]

The name or the ID of the service account to update.

required
service_account_update ServiceAccountUpdate

The update to be applied to the service account.

required

Returns:

Type Description
ServiceAccountResponse

The updated service account.

Raises:

Type Description
EntityExistsError

If a user or service account with the given name already exists.

Source code in src/zenml/zen_stores/sql_zen_store.py
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
def update_service_account(
    self,
    service_account_name_or_id: Union[str, UUID],
    service_account_update: ServiceAccountUpdate,
) -> ServiceAccountResponse:
    """Updates an existing service account.

    Args:
        service_account_name_or_id: The name or the ID of the service
            account to update.
        service_account_update: The update to be applied to the service
            account.

    Returns:
        The updated service account.

    Raises:
        EntityExistsError: If a user or service account with the given name
            already exists.
    """
    with Session(self.engine) as session:
        existing_service_account = self._get_account_schema(
            service_account_name_or_id,
            session=session,
            service_account=True,
        )

        if (
            service_account_update.name is not None
            and service_account_update.name
            != existing_service_account.name
        ):
            try:
                self._get_account_schema(
                    service_account_update.name,
                    session=session,
                    service_account=True,
                )
                raise EntityExistsError(
                    f"Unable to update service account with name "
                    f"'{service_account_update.name}': Found an existing "
                    "service account with this name."
                )
            except KeyError:
                pass

        existing_service_account.update_service_account(
            service_account_update=service_account_update
        )
        session.add(existing_service_account)
        session.commit()

        # Refresh the Model that was just created
        session.refresh(existing_service_account)
        return existing_service_account.to_service_account_model(
            include_metadata=True, include_resources=True
        )
update_service_connector(service_connector_id: UUID, update: ServiceConnectorUpdate) -> ServiceConnectorResponse

Updates an existing service connector.

The update model contains the fields to be updated. If a field value is set to None in the model, the field is not updated, but there are special rules concerning some fields:

  • the configuration and secrets fields together represent a full valid configuration update, not just a partial update. If either is set (i.e. not None) in the update, their values are merged together and will replace the existing configuration and secrets values.
  • the resource_id field value is also a full replacement value: if set to None, the resource ID is removed from the service connector.
  • the expiration_seconds field value is also a full replacement value: if set to None, the expiration is removed from the service connector.
  • the secret_id field value in the update is ignored, given that secrets are managed internally by the ZenML store.
  • the labels field is also a full labels update: if set (i.e. not None), all existing labels are removed and replaced by the new labels in the update.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the service connector to update.

required
update ServiceConnectorUpdate

The update to be applied to the service connector.

required

Returns:

Type Description
ServiceConnectorResponse

The updated service connector.

Raises:

Type Description
IllegalOperationError

If the service connector is referenced by one or more stack components and the update would change the connector type, resource type or resource ID.

Source code in src/zenml/zen_stores/sql_zen_store.py
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
def update_service_connector(
    self, service_connector_id: UUID, update: ServiceConnectorUpdate
) -> ServiceConnectorResponse:
    """Updates an existing service connector.

    The update model contains the fields to be updated. If a field value is
    set to None in the model, the field is not updated, but there are
    special rules concerning some fields:

    * the `configuration` and `secrets` fields together represent a full
    valid configuration update, not just a partial update. If either is
    set (i.e. not None) in the update, their values are merged together and
    will replace the existing configuration and secrets values.
    * the `resource_id` field value is also a full replacement value: if set
    to `None`, the resource ID is removed from the service connector.
    * the `expiration_seconds` field value is also a full replacement value:
    if set to `None`, the expiration is removed from the service connector.
    * the `secret_id` field value in the update is ignored, given that
    secrets are managed internally by the ZenML store.
    * the `labels` field is also a full labels update: if set (i.e. not
    `None`), all existing labels are removed and replaced by the new labels
    in the update.

    Args:
        service_connector_id: The ID of the service connector to update.
        update: The update to be applied to the service connector.

    Returns:
        The updated service connector.

    Raises:
        IllegalOperationError: If the service connector is referenced by
            one or more stack components and the update would change the
            connector type, resource type or resource ID.
    """
    with Session(self.engine) as session:
        existing_connector = self._get_schema_by_id(
            resource_id=service_connector_id,
            schema_class=ServiceConnectorSchema,
            session=session,
        )

        # In case of a renaming update, make sure no service connector uses
        # that name already
        self._verify_name_uniqueness(
            resource=update,
            schema=existing_connector,
            session=session,
        )

        existing_connector_model = existing_connector.to_model(
            include_metadata=True
        )

        if len(existing_connector.components):
            # If the service connector is already used in one or more
            # stack components, the update is no longer allowed to change
            # the service connector's authentication method, connector type,
            # resource type, or resource ID
            if (
                update.connector_type
                and update.type != existing_connector_model.connector_type
            ):
                raise IllegalOperationError(
                    "The service type of a service connector that is "
                    "already actively used in one or more stack components "
                    "cannot be changed."
                )

            if (
                update.auth_method
                and update.auth_method
                != existing_connector_model.auth_method
            ):
                raise IllegalOperationError(
                    "The authentication method of a service connector that "
                    "is already actively used in one or more stack "
                    "components cannot be changed."
                )

            if (
                update.resource_types
                and update.resource_types
                != existing_connector_model.resource_types
            ):
                raise IllegalOperationError(
                    "The resource type of a service connector that is "
                    "already actively used in one or more stack components "
                    "cannot be changed."
                )

            # The resource ID field cannot be used as a partial update: if
            # set to None, the existing resource ID is also removed
            if update.resource_id != existing_connector_model.resource_id:
                raise IllegalOperationError(
                    "The resource ID of a service connector that is "
                    "already actively used in one or more stack components "
                    "cannot be changed."
                )

        # If the connector type is locally available, we validate the update
        # against the connector type schema before storing it in the
        # database
        if service_connector_registry.is_registered(
            existing_connector.connector_type
        ):
            connector_type = (
                service_connector_registry.get_service_connector_type(
                    existing_connector.connector_type
                )
            )
            # We need the auth method to be set to be able to validate the
            # configuration
            update.auth_method = (
                update.auth_method or existing_connector_model.auth_method
            )
            # Validate the configuration update. If the configuration or
            # secrets fields are set, together they are merged into a
            # full configuration that is validated against the connector
            # type schema and replaces the existing configuration and
            # secrets values
            update.validate_and_configure_resources(
                connector_type=connector_type,
                resource_types=update.resource_types,
                resource_id=update.resource_id,
                configuration=update.configuration,
                secrets=update.secrets,
            )

        # Update secret
        secret_id = self._update_connector_secret(
            existing_connector=existing_connector_model,
            updated_connector=update,
        )

        existing_connector.update(
            connector_update=update, secret_id=secret_id
        )
        session.add(existing_connector)
        session.commit()

        connector = existing_connector.to_model(
            include_metadata=True, include_resources=True
        )
        self._populate_connector_type(connector)
        return connector
update_stack(stack_id: UUID, stack_update: StackUpdate) -> StackResponse

Update a stack.

Parameters:

Name Type Description Default
stack_id UUID

The ID of the stack update.

required
stack_update StackUpdate

The update request on the stack.

required

Returns:

Type Description
StackResponse

The updated stack.

Raises:

Type Description
IllegalOperationError

if the stack is a default stack.

Source code in src/zenml/zen_stores/sql_zen_store.py
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
@track_decorator(AnalyticsEvent.UPDATED_STACK)
def update_stack(
    self, stack_id: UUID, stack_update: StackUpdate
) -> StackResponse:
    """Update a stack.

    Args:
        stack_id: The ID of the stack update.
        stack_update: The update request on the stack.

    Returns:
        The updated stack.

    Raises:
        IllegalOperationError: if the stack is a default stack.
    """
    with Session(self.engine) as session:
        existing_stack = self._get_schema_by_id(
            resource_id=stack_id,
            schema_class=StackSchema,
            session=session,
        )
        if existing_stack.name == DEFAULT_STACK_AND_COMPONENT_NAME:
            raise IllegalOperationError(
                "The default stack cannot be modified."
            )
        # In case of a renaming update, make sure no stack already exists
        # with that name
        self._verify_name_uniqueness(
            resource=stack_update,
            schema=existing_stack,
            session=session,
        )

        components: List["StackComponentSchema"] = []
        if stack_update.components:
            for (
                component_type,
                list_of_component_ids,
            ) in stack_update.components.items():
                for component_id in list_of_component_ids:
                    component = self._get_reference_schema_by_id(
                        resource=existing_stack,
                        reference_schema=StackComponentSchema,
                        reference_id=component_id,
                        session=session,
                        reference_type=f"{str(component_type)} stack component",
                    )
                    components.append(component)

        existing_stack.update(
            stack_update=stack_update,
            components=components,
        )

        session.add(existing_stack)
        session.commit()
        session.refresh(existing_stack)

        return existing_stack.to_model(
            include_metadata=True, include_resources=True
        )
update_stack_component(component_id: UUID, component_update: ComponentUpdate) -> ComponentResponse

Update an existing stack component.

Parameters:

Name Type Description Default
component_id UUID

The ID of the stack component to update.

required
component_update ComponentUpdate

The update to be applied to the stack component.

required

Returns:

Type Description
ComponentResponse

The updated stack component.

Raises:

Type Description
IllegalOperationError

if the stack component is a default stack component.

Source code in src/zenml/zen_stores/sql_zen_store.py
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
def update_stack_component(
    self, component_id: UUID, component_update: ComponentUpdate
) -> ComponentResponse:
    """Update an existing stack component.

    Args:
        component_id: The ID of the stack component to update.
        component_update: The update to be applied to the stack component.

    Returns:
        The updated stack component.

    Raises:
        IllegalOperationError: if the stack component is a default stack
            component.
    """
    with Session(self.engine) as session:
        existing_component = self._get_schema_by_id(
            resource_id=component_id,
            schema_class=StackComponentSchema,
            session=session,
        )

        if component_update.configuration is not None:
            from zenml.stack.utils import validate_stack_component_config

            validate_stack_component_config(
                configuration_dict=component_update.configuration,
                flavor=existing_component.flavor,
                component_type=StackComponentType(existing_component.type),
                zen_store=self,
                validate_custom_flavors=False,
            )

        if (
            existing_component.name == DEFAULT_STACK_AND_COMPONENT_NAME
            and existing_component.type
            in [
                StackComponentType.ORCHESTRATOR,
                StackComponentType.ARTIFACT_STORE,
            ]
        ):
            raise IllegalOperationError(
                f"The default {existing_component.type} cannot be modified."
            )

        # In case of a renaming update, make sure no component of the same
        # type already exists with that name
        if component_update.name:
            if existing_component.name != component_update.name:
                self._fail_if_component_with_name_type_exists(
                    name=component_update.name,
                    component_type=StackComponentType(
                        existing_component.type
                    ),
                    session=session,
                )

        existing_component.update(component_update=component_update)

        if component_update.connector:
            service_connector = self._get_reference_schema_by_id(
                resource=existing_component,
                reference_schema=ServiceConnectorSchema,
                reference_id=component_update.connector,
                session=session,
            )

            existing_component.connector = service_connector
            existing_component.connector_resource_id = (
                component_update.connector_resource_id
            )
        else:
            existing_component.connector = None
            existing_component.connector_resource_id = None

        session.add(existing_component)
        session.commit()

        return existing_component.to_model(
            include_metadata=True, include_resources=True
        )
update_tag(tag_name_or_id: Union[str, UUID], tag_update_model: TagUpdate) -> TagResponse

Update tag.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

name or id of the tag to be updated.

required
tag_update_model TagUpdate

Tag to use for the update.

required

Returns:

Type Description
TagResponse

An updated tag.

Raises:

Type Description
ValueError

If the tag can not be converted to an exclusive tag due to it being associated to multiple entities.

Source code in src/zenml/zen_stores/sql_zen_store.py
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
def update_tag(
    self,
    tag_name_or_id: Union[str, UUID],
    tag_update_model: TagUpdate,
) -> TagResponse:
    """Update tag.

    Args:
        tag_name_or_id: name or id of the tag to be updated.
        tag_update_model: Tag to use for the update.

    Returns:
        An updated tag.

    Raises:
        ValueError: If the tag can not be converted to an exclusive tag due
            to it being associated to multiple entities.
    """
    with Session(self.engine) as session:
        tag = self._get_tag_schema(
            tag_name_or_id=tag_name_or_id,
            session=session,
        )
        self._verify_name_uniqueness(
            resource=tag_update_model,
            schema=tag,
            session=session,
        )

        if tag_update_model.exclusive is True:
            error_messages = []

            # Define allowed resource types for exclusive tags
            allowed_resource_types = [
                TaggableResourceTypes.PIPELINE_RUN.value,
                TaggableResourceTypes.ARTIFACT_VERSION.value,
                TaggableResourceTypes.RUN_TEMPLATE.value,
            ]

            # Check if tag is associated with any non-allowed resource types
            non_allowed_resources_query = (
                select(TagResourceSchema.resource_type)
                .where(
                    TagResourceSchema.tag_id == tag.id,
                    TagResourceSchema.resource_type.not_in(  # type: ignore[attr-defined]
                        allowed_resource_types
                    ),
                )
                .distinct()
            )

            non_allowed_resources = session.exec(
                non_allowed_resources_query
            ).all()
            if non_allowed_resources:
                error_message = (
                    f"The tag `{tag.name}` cannot be made "
                    "exclusive because it is associated with "
                    "non-allowed resource types: "
                    f"{', '.join(non_allowed_resources)}. "
                    "Exclusive tags can only be applied "
                    "to pipeline runs, artifact versions, "
                    "and run templates."
                )
                error_messages.append(error_message)

            for resource_type, resource_id, scope_id in [
                (
                    TaggableResourceTypes.PIPELINE_RUN,
                    PipelineRunSchema.id,
                    PipelineRunSchema.pipeline_id,
                ),
                (
                    TaggableResourceTypes.ARTIFACT_VERSION,
                    ArtifactVersionSchema.id,
                    ArtifactVersionSchema.artifact_id,
                ),
                (
                    TaggableResourceTypes.RUN_TEMPLATE,
                    RunTemplateSchema.id,
                    None,  # Special case - will be handled differently
                ),
            ]:
                # Special handling for run templates as they don't have direct pipeline_id
                if resource_type == TaggableResourceTypes.RUN_TEMPLATE:
                    query = (
                        select(
                            PipelineDeploymentSchema.pipeline_id,
                            func.count().label("count"),
                        )
                        .select_from(RunTemplateSchema)
                        .join(
                            TagResourceSchema,
                            and_(
                                TagResourceSchema.resource_id
                                == RunTemplateSchema.id,
                                TagResourceSchema.resource_type
                                == "run_template",
                            ),
                        )
                        .join(
                            PipelineDeploymentSchema,
                            RunTemplateSchema.source_deployment_id  # type: ignore[arg-type]
                            == PipelineDeploymentSchema.id,
                        )
                        .where(TagResourceSchema.tag_id == tag.id)
                        .group_by(PipelineDeploymentSchema.pipeline_id)  # type: ignore[arg-type]
                    )

                    results = session.exec(query).all()
                    conflicts = [k for k, v in results if v > 1]
                    if conflicts:
                        error_message = (
                            f"The tag `{tag.name}` is associated with multiple entries of "
                            f"`{resource_type.value}`s that share the same pipeline_id"
                        )
                        error_message += f": {conflicts}"
                        error_messages.append(error_message)
                else:
                    check, error = self._exclusive_check_for_existing_tags(
                        tag=tag,
                        session=session,
                        resource_type=resource_type,
                        resource_id_column=resource_id,
                        scope_id_column=scope_id,
                    )
                    if check is False:
                        error_messages.append(error)

            if error_messages:
                raise ValueError(
                    "\n".join(error_messages)
                    + "\nYou can only convert a tag into an exclusive tag "
                    "if the conflicts mentioned above are resolved."
                )

        tag.update(update=tag_update_model)
        session.add(tag)
        session.commit()

        # Refresh the tag that was just created
        session.refresh(tag)
        return tag.to_model(include_metadata=True, include_resources=True)
update_trigger(trigger_id: UUID, trigger_update: TriggerUpdate) -> TriggerResponse

Update a trigger.

Parameters:

Name Type Description Default
trigger_id UUID

The ID of the trigger update.

required
trigger_update TriggerUpdate

The update request on the trigger.

required

Returns:

Type Description
TriggerResponse

The updated trigger.

Raises:

Type Description
ValueError

If both a schedule and an event source are provided.

Source code in src/zenml/zen_stores/sql_zen_store.py
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
@track_decorator(AnalyticsEvent.UPDATED_TRIGGER)
def update_trigger(
    self, trigger_id: UUID, trigger_update: TriggerUpdate
) -> TriggerResponse:
    """Update a trigger.

    Args:
        trigger_id: The ID of the trigger update.
        trigger_update: The update request on the trigger.

    Returns:
        The updated trigger.

    Raises:
        ValueError: If both a schedule and an event source are provided.
    """
    with Session(self.engine) as session:
        # Check if trigger with the domain key (name, project, owner)
        # already exists
        existing_trigger = self._get_schema_by_id(
            resource_id=trigger_id,
            schema_class=TriggerSchema,
            session=session,
        )

        # Verify that either a schedule or an event source is provided, not
        # both
        if existing_trigger.event_source and trigger_update.schedule:
            raise ValueError(
                "Unable to update trigger: A trigger cannot have both a "
                "schedule and an event source."
            )

        # In case of a renaming update, make sure no trigger already exists
        # with that name
        self._verify_name_uniqueness(
            resource=trigger_update,
            schema=existing_trigger,
            session=session,
        )

        existing_trigger.update(
            trigger_update=trigger_update,
        )

        session.add(existing_trigger)
        session.commit()
        session.refresh(existing_trigger)

        return existing_trigger.to_model(
            include_metadata=True, include_resources=True
        )
update_user(user_id: UUID, user_update: UserUpdate) -> UserResponse

Updates an existing user.

Parameters:

Name Type Description Default
user_id UUID

The id of the user to update.

required
user_update UserUpdate

The update to be applied to the user.

required

Returns:

Type Description
UserResponse

The updated user.

Raises:

Type Description
IllegalOperationError

If the request tries to update the username for the default user account.

EntityExistsError

If the request tries to update the username to a name that is already taken by another user or service account.

Source code in src/zenml/zen_stores/sql_zen_store.py
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
def update_user(
    self, user_id: UUID, user_update: UserUpdate
) -> UserResponse:
    """Updates an existing user.

    Args:
        user_id: The id of the user to update.
        user_update: The update to be applied to the user.

    Returns:
        The updated user.

    Raises:
        IllegalOperationError: If the request tries to update the username
            for the default user account.
        EntityExistsError: If the request tries to update the username to
            a name that is already taken by another user or service account.
    """
    with Session(self.engine) as session:
        existing_user = self._get_account_schema(
            user_id, session=session, service_account=False
        )

        if (
            existing_user.is_admin is True
            and user_update.is_admin is False
        ):
            # There must be at least one admin account configured
            admin_accounts_count = session.scalar(
                select(func.count(UserSchema.id)).where(  # type: ignore[arg-type]
                    UserSchema.is_admin == True  # noqa: E712
                )
            )
            if admin_accounts_count == 1:
                raise IllegalOperationError(
                    "There has to be at least one admin account configured "
                    "on your system at all times. This is the only admin "
                    "account and therefore it cannot be demoted to a "
                    "regular user account."
                )

        if (
            user_update.name is not None
            and user_update.name != existing_user.name
        ):
            try:
                self._get_account_schema(
                    user_update.name,
                    session=session,
                    service_account=False,
                )
                raise EntityExistsError(
                    f"Unable to update user account with name "
                    f"'{user_update.name}': Found an existing user "
                    "account with this name."
                )
            except KeyError:
                pass

        user_model = existing_user.to_model(include_metadata=True)
        survey_finished_before = (
            FINISHED_ONBOARDING_SURVEY_KEY in user_model.user_metadata
        )

        existing_user.update_user(user_update=user_update)
        session.add(existing_user)
        session.commit()

        # Refresh the Model that was just created
        session.refresh(existing_user)
        updated_user = existing_user.to_model(
            include_metadata=True, include_resources=True
        )

        survey_finished_after = (
            FINISHED_ONBOARDING_SURVEY_KEY in updated_user.user_metadata
        )

        if not survey_finished_before and survey_finished_after:
            analytics_metadata = {
                **updated_user.user_metadata,
                # We need to get the email from the DB model as it is not
                # included in the model that's returned from this method
                "email": existing_user.email,
                "newsletter": existing_user.email_opted_in,
                "name": updated_user.name,
                "full_name": updated_user.full_name,
            }
            with AnalyticsContext() as context:
                # This method can be called from the `/users/activate`
                # endpoint in which the auth context is not set
                # -> We need to manually set the user ID in that case,
                # otherwise the event will not be sent
                if context.user_id is None:
                    context.user_id = updated_user.id

                context.track(
                    event=AnalyticsEvent.USER_ENRICHED,
                    properties=analytics_metadata,
                )

        return updated_user
verify_service_connector(service_connector_id: UUID, resource_type: Optional[str] = None, resource_id: Optional[str] = None, list_resources: bool = True) -> ServiceConnectorResourcesModel

Verifies if a service connector instance has access to one or more resources.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the service connector to verify.

required
resource_type Optional[str]

The type of resource to verify access to.

None
resource_id Optional[str]

The ID of the resource to verify access to.

None
list_resources bool

If True, the list of all resources accessible through the service connector and matching the supplied resource type and ID are returned.

True

Returns:

Type Description
ServiceConnectorResourcesModel

The list of resources that the service connector has access to,

ServiceConnectorResourcesModel

scoped to the supplied resource type and ID, if provided.

Source code in src/zenml/zen_stores/sql_zen_store.py
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
def verify_service_connector(
    self,
    service_connector_id: UUID,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    list_resources: bool = True,
) -> ServiceConnectorResourcesModel:
    """Verifies if a service connector instance has access to one or more resources.

    Args:
        service_connector_id: The ID of the service connector to verify.
        resource_type: The type of resource to verify access to.
        resource_id: The ID of the resource to verify access to.
        list_resources: If True, the list of all resources accessible
            through the service connector and matching the supplied resource
            type and ID are returned.

    Returns:
        The list of resources that the service connector has access to,
        scoped to the supplied resource type and ID, if provided.
    """
    connector = self.get_service_connector(service_connector_id)

    connector_instance = service_connector_registry.instantiate_connector(
        model=connector
    )

    return connector_instance.verify(
        resource_type=resource_type,
        resource_id=resource_id,
        list_resources=list_resources,
    )
verify_service_connector_config(service_connector: ServiceConnectorRequest, list_resources: bool = True) -> ServiceConnectorResourcesModel

Verifies if a service connector configuration has access to resources.

Parameters:

Name Type Description Default
service_connector ServiceConnectorRequest

The service connector configuration to verify.

required
list_resources bool

If True, the list of all resources accessible through the service connector is returned.

True

Returns:

Type Description
ServiceConnectorResourcesModel

The list of resources that the service connector configuration has

ServiceConnectorResourcesModel

access to.

Source code in src/zenml/zen_stores/sql_zen_store.py
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
def verify_service_connector_config(
    self,
    service_connector: ServiceConnectorRequest,
    list_resources: bool = True,
) -> ServiceConnectorResourcesModel:
    """Verifies if a service connector configuration has access to resources.

    Args:
        service_connector: The service connector configuration to verify.
        list_resources: If True, the list of all resources accessible
            through the service connector is returned.

    Returns:
        The list of resources that the service connector configuration has
        access to.
    """
    connector_instance = service_connector_registry.instantiate_connector(
        model=service_connector
    )
    return connector_instance.verify(list_resources=list_resources)
SqlZenStoreConfiguration

Bases: StoreConfiguration

SQL ZenML store configuration.

Attributes:

Name Type Description
type StoreType

The type of the store.

secrets_store Optional[SerializeAsAny[SecretsStoreConfiguration]]

The configuration of the secrets store to use. This defaults to a SQL secrets store that extends the SQL ZenML store.

backup_secrets_store Optional[SerializeAsAny[SecretsStoreConfiguration]]

The configuration of a backup secrets store to use in addition to the primary one as an intermediate step during the migration to a new secrets store.

driver Optional[SQLDatabaseDriver]

The SQL database driver.

database Optional[str]

database name. If not already present on the server, it will be created automatically on first access.

username Optional[PlainSerializedSecretStr]

The database username.

password Optional[PlainSerializedSecretStr]

The database password.

ssl bool

Whether to use SSL.

ssl_ca Optional[PlainSerializedSecretStr]

certificate authority certificate. Required for SSL enabled authentication if the CA certificate is not part of the certificates shipped by the operating system.

ssl_cert Optional[PlainSerializedSecretStr]

client certificate. Required for SSL enabled authentication if client certificates are used.

ssl_key Optional[PlainSerializedSecretStr]

client certificate private key. Required for SSL enabled if client certificates are used.

ssl_verify_server_cert bool

set to verify the identity of the server against the provided server certificate.

pool_size int

The maximum number of connections to keep in the SQLAlchemy pool.

max_overflow int

The maximum number of connections to allow in the SQLAlchemy pool in addition to the pool_size.

pool_pre_ping bool

Enable emitting a test statement on the SQL connection at the start of each connection pool checkout, to test that the database connection is still viable.

Functions
get_local_url(path: str) -> str staticmethod

Get a local SQL url for a given local path.

Parameters:

Name Type Description Default
path str

The path to the local sqlite file.

required

Returns:

Type Description
str

The local SQL url for the given path.

Source code in src/zenml/zen_stores/sql_zen_store.py
687
688
689
690
691
692
693
694
695
696
697
@staticmethod
def get_local_url(path: str) -> str:
    """Get a local SQL url for a given local path.

    Args:
        path: The path to the local sqlite file.

    Returns:
        The local SQL url for the given path.
    """
    return f"sqlite:///{path}/{ZENML_SQLITE_DB_FILENAME}"
get_sqlalchemy_config(database: Optional[str] = None) -> Tuple[URL, Dict[str, Any], Dict[str, Any]]

Get the SQLAlchemy engine configuration for the SQL ZenML store.

Parameters:

Name Type Description Default
database Optional[str]

Custom database name to use. If not set, the database name from the configuration will be used.

None

Returns:

Type Description
Tuple[URL, Dict[str, Any], Dict[str, Any]]

The URL and connection arguments for the SQLAlchemy engine.

Raises:

Type Description
NotImplementedError

If the SQL driver is not supported.

Source code in src/zenml/zen_stores/sql_zen_store.py
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
def get_sqlalchemy_config(
    self,
    database: Optional[str] = None,
) -> Tuple[URL, Dict[str, Any], Dict[str, Any]]:
    """Get the SQLAlchemy engine configuration for the SQL ZenML store.

    Args:
        database: Custom database name to use. If not set, the database name
            from the configuration will be used.

    Returns:
        The URL and connection arguments for the SQLAlchemy engine.

    Raises:
        NotImplementedError: If the SQL driver is not supported.
    """
    sql_url = make_url(self.url)
    sqlalchemy_connect_args: Dict[str, Any] = {}
    engine_args = {}
    if sql_url.drivername == SQLDatabaseDriver.SQLITE:
        assert self.database is not None
        # The following default value is needed for sqlite to avoid the
        # Error:
        #   sqlite3.ProgrammingError: SQLite objects created in a thread can
        #   only be used in that same thread.
        sqlalchemy_connect_args = {"check_same_thread": False}
    elif sql_url.drivername == SQLDatabaseDriver.MYSQL:
        # all these are guaranteed by our root validator
        assert self.database is not None
        assert self.username is not None
        assert self.password is not None
        assert sql_url.host is not None

        if not database:
            database = self.database

        engine_args = {
            "pool_size": self.pool_size,
            "max_overflow": self.max_overflow,
            "pool_pre_ping": self.pool_pre_ping,
        }

        sql_url = sql_url._replace(
            drivername="mysql+pymysql",
            username=self.username.get_secret_value(),
            password=self.password.get_secret_value(),
            database=database,
        )

        sqlalchemy_ssl_args: Dict[str, Any] = {}

        # Handle SSL params
        if self.ssl:
            sqlalchemy_ssl_args["ssl"] = True
            for key in ["ssl_key", "ssl_ca", "ssl_cert"]:
                ssl_setting = getattr(self, key)
                if not ssl_setting:
                    continue
                if not os.path.isfile(ssl_setting.get_secret_value()):
                    logger.warning(
                        f"Database SSL setting `{key}` is not a file. "
                    )
                sqlalchemy_ssl_args[key.removeprefix("ssl_")] = (
                    ssl_setting.get_secret_value()
                )
            sqlalchemy_ssl_args["check_hostname"] = (
                self.ssl_verify_server_cert
            )
            sqlalchemy_connect_args["ssl"] = sqlalchemy_ssl_args
    else:
        raise NotImplementedError(
            f"SQL driver `{sql_url.drivername}` is not supported."
        )

    return sql_url, sqlalchemy_connect_args, engine_args
supports_url_scheme(url: str) -> bool classmethod

Check if a URL scheme is supported by this store.

Parameters:

Name Type Description Default
url str

The URL to check.

required

Returns:

Type Description
bool

True if the URL scheme is supported, False otherwise.

Source code in src/zenml/zen_stores/sql_zen_store.py
699
700
701
702
703
704
705
706
707
708
709
@classmethod
def supports_url_scheme(cls, url: str) -> bool:
    """Check if a URL scheme is supported by this store.

    Args:
        url: The URL to check.

    Returns:
        True if the URL scheme is supported, False otherwise.
    """
    return make_url(url).drivername in SQLDatabaseDriver.values()
validate_secrets_store(secrets_store: Optional[SecretsStoreConfiguration]) -> SecretsStoreConfiguration classmethod

Ensures that the secrets store is initialized with a default SQL secrets store.

Parameters:

Name Type Description Default
secrets_store Optional[SecretsStoreConfiguration]

The secrets store config to be validated.

required

Returns:

Type Description
SecretsStoreConfiguration

The validated secrets store config.

Source code in src/zenml/zen_stores/sql_zen_store.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
@field_validator("secrets_store")
@classmethod
def validate_secrets_store(
    cls, secrets_store: Optional[SecretsStoreConfiguration]
) -> SecretsStoreConfiguration:
    """Ensures that the secrets store is initialized with a default SQL secrets store.

    Args:
        secrets_store: The secrets store config to be validated.

    Returns:
        The validated secrets store config.
    """
    if secrets_store is None:
        secrets_store = SqlSecretsStoreConfiguration()

    return secrets_store
Functions
exponential_backoff_with_jitter(attempt: int, base_duration: float = 0.05) -> float

Exponential backoff with jitter.

Implemented the Full jitter algorithm described in https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/

Parameters:

Name Type Description Default
attempt int

The backoff attempt.

required
base_duration float

The backoff base duration.

0.05

Returns:

Type Description
float

The backoff duration.

Source code in src/zenml/zen_stores/sql_zen_store.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
def exponential_backoff_with_jitter(
    attempt: int, base_duration: float = 0.05
) -> float:
    """Exponential backoff with jitter.

    Implemented the `Full jitter` algorithm described in
    https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/

    Args:
        attempt: The backoff attempt.
        base_duration: The backoff base duration.

    Returns:
        The backoff duration.
    """
    exponential_backoff = base_duration * 1.5**attempt
    return random.uniform(0, exponential_backoff)
Modules

template_utils

Utilities for run templates.

Classes
Functions
generate_config_schema(deployment: PipelineDeploymentSchema) -> Dict[str, Any]

Generate a run configuration schema for the deployment and stack.

Parameters:

Name Type Description Default
deployment PipelineDeploymentSchema

The deployment schema.

required

Returns:

Type Description
Dict[str, Any]

The generated schema dictionary.

Source code in src/zenml/zen_stores/template_utils.py
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
def generate_config_schema(
    deployment: PipelineDeploymentSchema,
) -> Dict[str, Any]:
    """Generate a run configuration schema for the deployment and stack.

    Args:
        deployment: The deployment schema.

    Returns:
        The generated schema dictionary.
    """
    # Config schema can only be generated for a runnable template, so this is
    # guaranteed by checks in the run template schema
    assert deployment.build
    assert deployment.build.stack

    stack = deployment.build.stack
    experiment_trackers = []
    step_operators = []

    settings_fields: Dict[str, Any] = {"resources": (ResourceSettings, None)}
    for component in stack.components:
        if not component.flavor_schema:
            continue

        flavor_model = component.flavor_schema.to_model()
        flavor = Flavor.from_model(flavor_model)

        for class_ in flavor.config_class.__mro__[1:]:
            # Ugly hack to get the settings class of a flavor without having
            # the integration installed. This is based on the convention that
            # the static config of a stack component should always inherit
            # from the dynamic settings.
            if issubclass(class_, BaseSettings):
                if len(class_.model_fields) > 0:
                    settings_key = f"{component.type}.{component.flavor}"
                    settings_fields[settings_key] = (
                        Optional[class_],
                        None,
                    )

                break

        if component.type == StackComponentType.EXPERIMENT_TRACKER:
            experiment_trackers.append(component.name)
        if component.type == StackComponentType.STEP_OPERATOR:
            step_operators.append(component.name)

    settings_model = create_model("Settings", **settings_fields)

    generic_step_fields: Dict[str, Any] = {}

    for key, field_info in StepConfigurationUpdate.model_fields.items():
        if key in [
            "name",
            "outputs",
            "step_operator",
            "experiment_tracker",
            "parameters",
        ]:
            continue

        if field_info.annotation == Optional[SourceWithValidator]:
            generic_step_fields[key] = (Optional[str], None)
        else:
            generic_step_fields[key] = (field_info.annotation, field_info)

    if experiment_trackers:
        experiment_tracker_enum = Enum(  # type: ignore[misc]
            "ExperimentTrackers", {e: e for e in experiment_trackers}
        )
        generic_step_fields["experiment_tracker"] = (
            Optional[experiment_tracker_enum],
            None,
        )
    if step_operators:
        step_operator_enum = Enum(  # type: ignore[misc]
            "StepOperators", {s: s for s in step_operators}
        )
        generic_step_fields["step_operator"] = (
            Optional[step_operator_enum],
            None,
        )

    generic_step_fields["settings"] = (Optional[settings_model], None)

    all_steps: Dict[str, Any] = {}
    all_steps_required = False
    for name, step in deployment.to_model(
        include_metadata=True
    ).step_configurations.items():
        step_fields = generic_step_fields.copy()
        if step.config.parameters:
            parameter_fields: Dict[str, Any] = {
                name: (Any, FieldInfo(default=...))
                for name in step.config.parameters
            }
            parameters_class = create_model(
                f"{name}_parameters", **parameter_fields
            )
            step_fields["parameters"] = (
                parameters_class,
                FieldInfo(default=...),
            )

        step_model = create_model(name, **step_fields)

        if step.config.parameters:
            # This step has required parameters -> we make this attribute
            # required and also the parent attribute so these parameters must
            # always be included
            all_steps_required = True
            all_steps[name] = (step_model, FieldInfo(default=...))
        else:
            all_steps[name] = (Optional[step_model], FieldInfo(default=None))

    all_steps_model = create_model("Steps", **all_steps)

    top_level_fields: Dict[str, Any] = {}

    for key, field_info in PipelineRunConfiguration.model_fields.items():
        if key in ["schedule", "build", "steps", "settings", "parameters"]:
            continue

        if field_info.annotation == Optional[SourceWithValidator]:
            top_level_fields[key] = (Optional[str], None)
        else:
            top_level_fields[key] = (field_info.annotation, field_info)

    top_level_fields["settings"] = (Optional[settings_model], None)

    if all_steps_required:
        top_level_fields["steps"] = (all_steps_model, FieldInfo(default=...))
    else:
        top_level_fields["steps"] = (
            Optional[all_steps_model],
            FieldInfo(default=None),
        )

    return create_model("Result", **top_level_fields).model_json_schema()  # type: ignore[no-any-return]
generate_config_template(deployment: PipelineDeploymentSchema) -> Dict[str, Any]

Generate a run configuration template for a deployment.

Parameters:

Name Type Description Default
deployment PipelineDeploymentSchema

The deployment.

required

Returns:

Type Description
Dict[str, Any]

The run configuration template.

Source code in src/zenml/zen_stores/template_utils.py
 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
def generate_config_template(
    deployment: PipelineDeploymentSchema,
) -> Dict[str, Any]:
    """Generate a run configuration template for a deployment.

    Args:
        deployment: The deployment.

    Returns:
        The run configuration template.
    """
    deployment_model = deployment.to_model(include_metadata=True)

    steps_configs = {
        name: step.config.model_dump(
            include=set(StepConfigurationUpdate.model_fields),
            exclude={"name", "outputs"},
        )
        for name, step in deployment_model.step_configurations.items()
    }

    for config in steps_configs.values():
        config["settings"].pop("docker", None)

    pipeline_config = deployment_model.pipeline_configuration.model_dump(
        include=set(PipelineRunConfiguration.model_fields),
        exclude={"schedule", "build", "parameters"},
    )

    pipeline_config["settings"].pop("docker", None)

    config_template = {
        "run_name": deployment_model.run_name_template,
        "steps": steps_configs,
        **pipeline_config,
    }
    return config_template
validate_deployment_is_templatable(deployment: PipelineDeploymentSchema) -> None

Validate that a deployment is templatable.

Parameters:

Name Type Description Default
deployment PipelineDeploymentSchema

The deployment to validate.

required

Raises:

Type Description
ValueError

If the deployment is not templatable.

Source code in src/zenml/zen_stores/template_utils.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def validate_deployment_is_templatable(
    deployment: PipelineDeploymentSchema,
) -> None:
    """Validate that a deployment is templatable.

    Args:
        deployment: The deployment to validate.

    Raises:
        ValueError: If the deployment is not templatable.
    """
    if not deployment.build:
        raise ValueError(
            "Unable to create run template as there is no associated build. "
            "Run templates can only be created for remote orchestrators that "
            "use container images to run the pipeline."
        )

    if not deployment.build.stack:
        raise ValueError(
            "Unable to create run template as the associated build has no "
            "stack reference."
        )

    for component in deployment.build.stack.components:
        if not component.flavor_schema:
            raise ValueError(
                "Unable to create run template as a component of the "
                "associated stack has no flavor."
            )

        if component.flavor_schema.is_custom:
            raise ValueError(
                "Unable to create run template as a component of the "
                "associated stack has a custom flavor."
            )

        flavor_model = component.flavor_schema.to_model()
        flavor = Flavor.from_model(flavor_model)
        component_config = flavor.config_class(
            **component.to_model(include_metadata=True).configuration
        )

        if component_config.is_local:
            raise ValueError(
                "Unable to create run template as the associated stack "
                "contains local components."
            )

zen_store_interface

ZenML Store interface.

Classes
ZenStoreInterface

Bases: ABC

ZenML store interface.

All ZenML stores must implement the methods in this interface.

The methods in this interface are organized in the following way:

  • they are grouped into categories based on the type of resource that they operate on (e.g. stacks, stack components, etc.)

  • each category has a set of CRUD methods (create, read, update, delete) that operate on the resources in that category. The order of the methods in each category should be:

  • create methods - store a new resource. These methods should fill in generated fields (e.g. UUIDs, creation timestamps) in the resource and return the updated resource.

  • get methods - retrieve a single existing resource identified by a unique key or identifier from the store. These methods should always return a resource and raise an exception if the resource does not exist.
  • list methods - retrieve a list of resources from the store. These methods should accept a set of filter parameters that can be used to filter the list of resources retrieved from the store.
  • update methods - update an existing resource in the store. These methods should expect the updated resource to be correctly identified by its unique key or identifier and raise an exception if the resource does not exist.
  • delete methods - delete an existing resource from the store. These methods should expect the resource to be correctly identified by its unique key or identifier. If the resource does not exist, an exception should be raised.

Best practices for implementing and keeping this interface clean and easy to maintain and extend:

  • keep methods organized by resource type and ordered by CRUD operation
  • for resources with multiple keys, don't implement multiple get or list methods here if the same functionality can be achieved by a single get or list method. Instead, implement them in the BaseZenStore class and have them call the generic get or list method in this interface.
  • keep the logic required to convert between ZenML domain Model classes and internal store representations outside the ZenML domain Model classes
  • methods for resources that have two or more unique keys (e.g. a project is uniquely identified by its name as well as its UUID) should reflect that in the method variants and/or method arguments:
    • methods that take in a resource identifier as argument should accept all variants of the identifier (e.g. project_name_or_uuid for methods that get/list/update/delete projects)
    • if a compound key is involved, separate get methods should be implemented (e.g. get_pipeline to get a pipeline by ID and get_pipeline_in_project to get a pipeline by its name and the ID of the project it belongs to)
  • methods for resources that are scoped as children of other resources (e.g. a pipeline is always owned by a project) should reflect the key(s) of the parent resource in the provided method arguments:
    • list methods should feature optional filter arguments that reflect the parent resource key(s)
Functions
backup_secrets(ignore_errors: bool = True, delete_secrets: bool = False) -> None abstractmethod

Backs up all secrets to the configured backup secrets store.

Parameters:

Name Type Description Default
ignore_errors bool

Whether to ignore individual errors during the backup process and attempt to backup all secrets.

True
delete_secrets bool

Whether to delete the secrets that have been successfully backed up from the primary secrets store. Setting this flag effectively moves all secrets from the primary secrets store to the backup secrets store.

False

Raises:

Type Description
BackupSecretsStoreNotConfiguredError

if no backup secrets store is configured.

Source code in src/zenml/zen_stores/zen_store_interface.py
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
@abstractmethod
def backup_secrets(
    self, ignore_errors: bool = True, delete_secrets: bool = False
) -> None:
    """Backs up all secrets to the configured backup secrets store.

    Args:
        ignore_errors: Whether to ignore individual errors during the backup
            process and attempt to backup all secrets.
        delete_secrets: Whether to delete the secrets that have been
            successfully backed up from the primary secrets store. Setting
            this flag effectively moves all secrets from the primary secrets
            store to the backup secrets store.

    Raises:
        BackupSecretsStoreNotConfiguredError: if no backup secrets store is
            configured.
    """
batch_create_artifact_versions(artifact_versions: List[ArtifactVersionRequest]) -> List[ArtifactVersionResponse] abstractmethod

Creates a batch of artifact versions.

Parameters:

Name Type Description Default
artifact_versions List[ArtifactVersionRequest]

The artifact versions to create.

required

Returns:

Type Description
List[ArtifactVersionResponse]

The created artifact versions.

Source code in src/zenml/zen_stores/zen_store_interface.py
661
662
663
664
665
666
667
668
669
670
671
672
@abstractmethod
def batch_create_artifact_versions(
    self, artifact_versions: List[ArtifactVersionRequest]
) -> List[ArtifactVersionResponse]:
    """Creates a batch of artifact versions.

    Args:
        artifact_versions: The artifact versions to create.

    Returns:
        The created artifact versions.
    """
batch_create_tag_resource(tag_resources: List[TagResourceRequest]) -> List[TagResourceResponse] abstractmethod

Create a new tag resource relationship.

Parameters:

Name Type Description Default
tag_resources List[TagResourceRequest]

The tag resource relationships to be created.

required

Returns:

Type Description
List[TagResourceResponse]

The newly created tag resource relationships.

Source code in src/zenml/zen_stores/zen_store_interface.py
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
@abstractmethod
def batch_create_tag_resource(
    self, tag_resources: List[TagResourceRequest]
) -> List[TagResourceResponse]:
    """Create a new tag resource relationship.

    Args:
        tag_resources: The tag resource relationships to be created.

    Returns:
        The newly created tag resource relationships.
    """
batch_delete_tag_resource(tag_resources: List[TagResourceRequest]) -> None abstractmethod

Delete a batch of tag resource relationships.

Parameters:

Name Type Description Default
tag_resources List[TagResourceRequest]

The tag resource relationships to be deleted.

required
Source code in src/zenml/zen_stores/zen_store_interface.py
3094
3095
3096
3097
3098
3099
3100
3101
3102
@abstractmethod
def batch_delete_tag_resource(
    self, tag_resources: List[TagResourceRequest]
) -> None:
    """Delete a batch of tag resource relationships.

    Args:
        tag_resources: The tag resource relationships to be deleted.
    """
create_action(action: ActionRequest) -> ActionResponse abstractmethod

Create an action.

Parameters:

Name Type Description Default
action ActionRequest

The action to create.

required

Returns:

Type Description
ActionResponse

The created action.

Source code in src/zenml/zen_stores/zen_store_interface.py
275
276
277
278
279
280
281
282
283
284
@abstractmethod
def create_action(self, action: ActionRequest) -> ActionResponse:
    """Create an action.

    Args:
        action: The action to create.

    Returns:
        The created action.
    """
create_api_key(service_account_id: UUID, api_key: APIKeyRequest) -> APIKeyResponse abstractmethod

Create a new API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to create the API key.

required
api_key APIKeyRequest

The API key to create.

required

Returns:

Type Description
APIKeyResponse

The created API key.

Raises:

Type Description
KeyError

If the service account doesn't exist.

EntityExistsError

If an API key with the same name is already configured for the same service account.

Source code in src/zenml/zen_stores/zen_store_interface.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
@abstractmethod
def create_api_key(
    self, service_account_id: UUID, api_key: APIKeyRequest
) -> APIKeyResponse:
    """Create a new API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to
            create the API key.
        api_key: The API key to create.

    Returns:
        The created API key.

    Raises:
        KeyError: If the service account doesn't exist.
        EntityExistsError: If an API key with the same name is already
            configured for the same service account.
    """
create_artifact(artifact: ArtifactRequest) -> ArtifactResponse abstractmethod

Creates a new artifact.

Parameters:

Name Type Description Default
artifact ArtifactRequest

The artifact to create.

required

Returns:

Type Description
ArtifactResponse

The newly created artifact.

Raises:

Type Description
EntityExistsError

If an artifact with the same name already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
570
571
572
573
574
575
576
577
578
579
580
581
582
@abstractmethod
def create_artifact(self, artifact: ArtifactRequest) -> ArtifactResponse:
    """Creates a new artifact.

    Args:
        artifact: The artifact to create.

    Returns:
        The newly created artifact.

    Raises:
        EntityExistsError: If an artifact with the same name already exists.
    """
create_artifact_version(artifact_version: ArtifactVersionRequest) -> ArtifactVersionResponse abstractmethod

Creates an artifact version.

Parameters:

Name Type Description Default
artifact_version ArtifactVersionRequest

The artifact version to create.

required

Returns:

Type Description
ArtifactVersionResponse

The created artifact version.

Source code in src/zenml/zen_stores/zen_store_interface.py
648
649
650
651
652
653
654
655
656
657
658
659
@abstractmethod
def create_artifact_version(
    self, artifact_version: ArtifactVersionRequest
) -> ArtifactVersionResponse:
    """Creates an artifact version.

    Args:
        artifact_version: The artifact version to create.

    Returns:
        The created artifact version.
    """
create_build(build: PipelineBuildRequest) -> PipelineBuildResponse abstractmethod

Creates a new build.

Parameters:

Name Type Description Default
build PipelineBuildRequest

The build to create.

required

Returns:

Type Description
PipelineBuildResponse

The newly created build.

Raises:

Type Description
EntityExistsError

If an identical build already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
@abstractmethod
def create_build(
    self,
    build: PipelineBuildRequest,
) -> PipelineBuildResponse:
    """Creates a new build.

    Args:
        build: The build to create.

    Returns:
        The newly created build.

    Raises:
        EntityExistsError: If an identical build already exists.
    """
create_code_repository(code_repository: CodeRepositoryRequest) -> CodeRepositoryResponse abstractmethod

Creates a new code repository.

Parameters:

Name Type Description Default
code_repository CodeRepositoryRequest

Code repository to be created.

required

Returns:

Type Description
CodeRepositoryResponse

The newly created code repository.

Raises:

Type Description
EntityExistsError

If a code repository with the given name already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
@abstractmethod
def create_code_repository(
    self, code_repository: CodeRepositoryRequest
) -> CodeRepositoryResponse:
    """Creates a new code repository.

    Args:
        code_repository: Code repository to be created.

    Returns:
        The newly created code repository.

    Raises:
        EntityExistsError: If a code repository with the given name already
            exists.
    """
create_deployment(deployment: PipelineDeploymentRequest) -> PipelineDeploymentResponse abstractmethod

Creates a new deployment.

Parameters:

Name Type Description Default
deployment PipelineDeploymentRequest

The deployment to create.

required

Returns:

Type Description
PipelineDeploymentResponse

The newly created deployment.

Raises:

Type Description
EntityExistsError

If an identical deployment already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
@abstractmethod
def create_deployment(
    self,
    deployment: PipelineDeploymentRequest,
) -> PipelineDeploymentResponse:
    """Creates a new deployment.

    Args:
        deployment: The deployment to create.

    Returns:
        The newly created deployment.

    Raises:
        EntityExistsError: If an identical deployment already exists.
    """
create_event_source(event_source: EventSourceRequest) -> EventSourceResponse abstractmethod

Create an event_source.

Parameters:

Name Type Description Default
event_source EventSourceRequest

The event_source to create.

required

Returns:

Type Description
EventSourceResponse

The created event_source.

Source code in src/zenml/zen_stores/zen_store_interface.py
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
@abstractmethod
def create_event_source(
    self, event_source: EventSourceRequest
) -> EventSourceResponse:
    """Create an event_source.

    Args:
        event_source: The event_source to create.

    Returns:
        The created event_source.
    """
create_flavor(flavor: FlavorRequest) -> FlavorResponse abstractmethod

Creates a new stack component flavor.

Parameters:

Name Type Description Default
flavor FlavorRequest

The stack component flavor to create.

required

Returns:

Type Description
FlavorResponse

The newly created flavor.

Raises:

Type Description
EntityExistsError

If a flavor with the same name and type already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
@abstractmethod
def create_flavor(
    self,
    flavor: FlavorRequest,
) -> FlavorResponse:
    """Creates a new stack component flavor.

    Args:
        flavor: The stack component flavor to create.

    Returns:
        The newly created flavor.

    Raises:
        EntityExistsError: If a flavor with the same name and type
            already exists.
    """
create_model(model: ModelRequest) -> ModelResponse abstractmethod

Creates a new model.

Parameters:

Name Type Description Default
model ModelRequest

the Model to be created.

required

Returns:

Type Description
ModelResponse

The newly created model.

Raises:

Type Description
EntityExistsError

If a model with the given name already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
@abstractmethod
def create_model(self, model: ModelRequest) -> ModelResponse:
    """Creates a new model.

    Args:
        model: the Model to be created.

    Returns:
        The newly created model.

    Raises:
        EntityExistsError: If a model with the given name already exists.
    """
create_model_version(model_version: ModelVersionRequest) -> ModelVersionResponse abstractmethod

Creates a new model version.

Parameters:

Name Type Description Default
model_version ModelVersionRequest

the Model Version to be created.

required

Returns:

Type Description
ModelVersionResponse

The newly created model version.

Raises:

Type Description
ValueError

If number is not None during model version creation.

EntityExistsError

If a model version with the given name already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
@abstractmethod
def create_model_version(
    self, model_version: ModelVersionRequest
) -> ModelVersionResponse:
    """Creates a new model version.

    Args:
        model_version: the Model Version to be created.

    Returns:
        The newly created model version.

    Raises:
        ValueError: If `number` is not None during model version creation.
        EntityExistsError: If a model version with the given name already
            exists.
    """
create_model_version_artifact_link(model_version_artifact_link: ModelVersionArtifactRequest) -> ModelVersionArtifactResponse abstractmethod

Creates a new model version link.

Parameters:

Name Type Description Default
model_version_artifact_link ModelVersionArtifactRequest

the Model Version to Artifact Link to be created.

required

Returns:

Type Description
ModelVersionArtifactResponse

The newly created model version to artifact link.

Raises:

Type Description
EntityExistsError

If a link with the given name already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
@abstractmethod
def create_model_version_artifact_link(
    self, model_version_artifact_link: ModelVersionArtifactRequest
) -> ModelVersionArtifactResponse:
    """Creates a new model version link.

    Args:
        model_version_artifact_link: the Model Version to Artifact Link
            to be created.

    Returns:
        The newly created model version to artifact link.

    Raises:
        EntityExistsError: If a link with the given name already exists.
    """
create_model_version_pipeline_run_link(model_version_pipeline_run_link: ModelVersionPipelineRunRequest) -> ModelVersionPipelineRunResponse abstractmethod

Creates a new model version to pipeline run link.

Parameters:

Name Type Description Default
model_version_pipeline_run_link ModelVersionPipelineRunRequest

the Model Version to Pipeline Run Link to be created.

required

Returns:

Type Description
ModelVersionPipelineRunResponse
  • If Model Version to Pipeline Run Link already exists - returns the existing link.
ModelVersionPipelineRunResponse
  • Otherwise, returns the newly created model version to pipeline run link.
Source code in src/zenml/zen_stores/zen_store_interface.py
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
@abstractmethod
def create_model_version_pipeline_run_link(
    self,
    model_version_pipeline_run_link: ModelVersionPipelineRunRequest,
) -> ModelVersionPipelineRunResponse:
    """Creates a new model version to pipeline run link.

    Args:
        model_version_pipeline_run_link: the Model Version to Pipeline Run
            Link to be created.

    Returns:
        - If Model Version to Pipeline Run Link already exists - returns
            the existing link.
        - Otherwise, returns the newly created model version to pipeline
            run link.
    """
create_pipeline(pipeline: PipelineRequest) -> PipelineResponse abstractmethod

Creates a new pipeline.

Parameters:

Name Type Description Default
pipeline PipelineRequest

The pipeline to create.

required

Returns:

Type Description
PipelineResponse

The newly created pipeline.

Raises:

Type Description
EntityExistsError

If an identical pipeline already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
@abstractmethod
def create_pipeline(
    self,
    pipeline: PipelineRequest,
) -> PipelineResponse:
    """Creates a new pipeline.

    Args:
        pipeline: The pipeline to create.

    Returns:
        The newly created pipeline.

    Raises:
        EntityExistsError: If an identical pipeline already exists.
    """
create_project(project: ProjectRequest) -> ProjectResponse abstractmethod

Creates a new project.

Parameters:

Name Type Description Default
project ProjectRequest

The project to create.

required

Returns:

Type Description
ProjectResponse

The newly created project.

Raises:

Type Description
EntityExistsError

If a project with the given name already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
@abstractmethod
def create_project(self, project: ProjectRequest) -> ProjectResponse:
    """Creates a new project.

    Args:
        project: The project to create.

    Returns:
        The newly created project.

    Raises:
        EntityExistsError: If a project with the given name already exists.
    """
create_run_metadata(run_metadata: RunMetadataRequest) -> None abstractmethod

Creates run metadata.

Parameters:

Name Type Description Default
run_metadata RunMetadataRequest

The run metadata to create.

required

Returns:

Type Description
None

None

Source code in src/zenml/zen_stores/zen_store_interface.py
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
@abstractmethod
def create_run_metadata(self, run_metadata: RunMetadataRequest) -> None:
    """Creates run metadata.

    Args:
        run_metadata: The run metadata to create.

    Returns:
        None
    """
create_run_step(step_run: StepRunRequest) -> StepRunResponse abstractmethod

Creates a step run.

Parameters:

Name Type Description Default
step_run StepRunRequest

The step run to create.

required

Returns:

Type Description
StepRunResponse

The created step run.

Raises:

Type Description
EntityExistsError

if the step run already exists.

KeyError

if the pipeline run doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
@abstractmethod
def create_run_step(self, step_run: StepRunRequest) -> StepRunResponse:
    """Creates a step run.

    Args:
        step_run: The step run to create.

    Returns:
        The created step run.

    Raises:
        EntityExistsError: if the step run already exists.
        KeyError: if the pipeline run doesn't exist.
    """
create_run_template(template: RunTemplateRequest) -> RunTemplateResponse abstractmethod

Create a new run template.

Parameters:

Name Type Description Default
template RunTemplateRequest

The template to create.

required

Returns:

Type Description
RunTemplateResponse

The newly created template.

Raises:

Type Description
EntityExistsError

If a template with the same name already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
@abstractmethod
def create_run_template(
    self,
    template: RunTemplateRequest,
) -> RunTemplateResponse:
    """Create a new run template.

    Args:
        template: The template to create.

    Returns:
        The newly created template.

    Raises:
        EntityExistsError: If a template with the same name already exists.
    """
create_schedule(schedule: ScheduleRequest) -> ScheduleResponse abstractmethod

Creates a new schedule.

Parameters:

Name Type Description Default
schedule ScheduleRequest

The schedule to create.

required

Returns:

Type Description
ScheduleResponse

The newly created schedule.

Source code in src/zenml/zen_stores/zen_store_interface.py
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
@abstractmethod
def create_schedule(self, schedule: ScheduleRequest) -> ScheduleResponse:
    """Creates a new schedule.

    Args:
        schedule: The schedule to create.

    Returns:
        The newly created schedule.
    """
create_secret(secret: SecretRequest) -> SecretResponse abstractmethod

Creates a new secret.

The new secret is also validated against the scoping rules enforced in the secrets store:

  • only one private secret with the given name can exist.
  • only one public secret with the given name can exist.

Parameters:

Name Type Description Default
secret SecretRequest

The secret to create.

required

Returns:

Type Description
SecretResponse

The newly created secret.

Raises:

Type Description
KeyError

if the user does not exist.

EntityExistsError

If a secret with the same name already exists in the same scope.

Source code in src/zenml/zen_stores/zen_store_interface.py
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
@abstractmethod
def create_secret(
    self,
    secret: SecretRequest,
) -> SecretResponse:
    """Creates a new secret.

    The new secret is also validated against the scoping rules enforced in
    the secrets store:

      - only one private secret with the given name can exist.
      - only one public secret with the given name can exist.

    Args:
        secret: The secret to create.

    Returns:
        The newly created secret.

    Raises:
        KeyError: if the user does not exist.
        EntityExistsError: If a secret with the same name already exists in
            the same scope.
    """
create_service(service: ServiceRequest) -> ServiceResponse abstractmethod

Create a new service.

Parameters:

Name Type Description Default
service ServiceRequest

The service to create.

required

Returns:

Type Description
ServiceResponse

The newly created service.

Raises:

Type Description
EntityExistsError

If a service with the same name already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
@abstractmethod
def create_service(
    self,
    service: ServiceRequest,
) -> ServiceResponse:
    """Create a new service.

    Args:
        service: The service to create.

    Returns:
        The newly created service.

    Raises:
        EntityExistsError: If a service with the same name already exists.
    """
create_service_account(service_account: ServiceAccountRequest) -> ServiceAccountResponse abstractmethod

Creates a new service account.

Parameters:

Name Type Description Default
service_account ServiceAccountRequest

Service account to be created.

required

Returns:

Type Description
ServiceAccountResponse

The newly created service account.

Raises:

Type Description
EntityExistsError

If a user or service account with the given name already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
@abstractmethod
def create_service_account(
    self, service_account: ServiceAccountRequest
) -> ServiceAccountResponse:
    """Creates a new service account.

    Args:
        service_account: Service account to be created.

    Returns:
        The newly created service account.

    Raises:
        EntityExistsError: If a user or service account with the given name
            already exists.
    """
create_service_connector(service_connector: ServiceConnectorRequest) -> ServiceConnectorResponse abstractmethod

Creates a new service connector.

Parameters:

Name Type Description Default
service_connector ServiceConnectorRequest

Service connector to be created.

required

Returns:

Type Description
ServiceConnectorResponse

The newly created service connector.

Raises:

Type Description
EntityExistsError

If a service connector with the given name already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
@abstractmethod
def create_service_connector(
    self,
    service_connector: ServiceConnectorRequest,
) -> ServiceConnectorResponse:
    """Creates a new service connector.

    Args:
        service_connector: Service connector to be created.

    Returns:
        The newly created service connector.

    Raises:
        EntityExistsError: If a service connector with the given name
            already exists.
    """
create_stack(stack: StackRequest) -> StackResponse abstractmethod

Create a new stack.

Parameters:

Name Type Description Default
stack StackRequest

The stack to create.

required

Returns:

Type Description
StackResponse

The created stack.

Raises:

Type Description
EntityExistsError

If a stack, stack component or service connector with the same name already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
@abstractmethod
def create_stack(self, stack: StackRequest) -> StackResponse:
    """Create a new stack.

    Args:
        stack: The stack to create.

    Returns:
        The created stack.

    Raises:
        EntityExistsError: If a stack, stack component or service connector
            with the same name already exists.
    """
create_stack_component(component: ComponentRequest) -> ComponentResponse abstractmethod

Create a stack component.

Parameters:

Name Type Description Default
component ComponentRequest

The stack component to create.

required

Returns:

Type Description
ComponentResponse

The created stack component.

Raises:

Type Description
EntityExistsError

If a stack component with the same name and type already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
@abstractmethod
def create_stack_component(
    self, component: ComponentRequest
) -> ComponentResponse:
    """Create a stack component.

    Args:
        component: The stack component to create.

    Returns:
        The created stack component.

    Raises:
        EntityExistsError: If a stack component with the same name
            and type already exists.
    """
create_tag(tag: TagRequest) -> TagResponse abstractmethod

Creates a new tag.

Parameters:

Name Type Description Default
tag TagRequest

the tag to be created.

required

Returns:

Type Description
TagResponse

The newly created tag.

Raises:

Type Description
EntityExistsError

If a tag with the given name already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
@abstractmethod
def create_tag(self, tag: TagRequest) -> TagResponse:
    """Creates a new tag.

    Args:
        tag: the tag to be created.

    Returns:
        The newly created tag.

    Raises:
        EntityExistsError: If a tag with the given name already exists.
    """
create_tag_resource(tag_resource: TagResourceRequest) -> TagResourceResponse abstractmethod

Create a new tag resource relationship.

Parameters:

Name Type Description Default
tag_resource TagResourceRequest

The tag resource relationship to be created.

required

Returns:

Type Description
TagResourceResponse

The newly created tag resource relationship.

Source code in src/zenml/zen_stores/zen_store_interface.py
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
@abstractmethod
def create_tag_resource(
    self, tag_resource: TagResourceRequest
) -> TagResourceResponse:
    """Create a new tag resource relationship.

    Args:
        tag_resource: The tag resource relationship to be created.

    Returns:
        The newly created tag resource relationship.
    """
create_trigger(trigger: TriggerRequest) -> TriggerResponse abstractmethod

Create an trigger.

Parameters:

Name Type Description Default
trigger TriggerRequest

The trigger to create.

required

Returns:

Type Description
TriggerResponse

The created trigger.

Source code in src/zenml/zen_stores/zen_store_interface.py
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
@abstractmethod
def create_trigger(self, trigger: TriggerRequest) -> TriggerResponse:
    """Create an trigger.

    Args:
        trigger: The trigger to create.

    Returns:
        The created trigger.
    """
create_user(user: UserRequest) -> UserResponse abstractmethod

Creates a new user.

Parameters:

Name Type Description Default
user UserRequest

User to be created.

required

Returns:

Type Description
UserResponse

The newly created user.

Raises:

Type Description
EntityExistsError

If a user with the given name already exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
@abstractmethod
def create_user(self, user: UserRequest) -> UserResponse:
    """Creates a new user.

    Args:
        user: User to be created.

    Returns:
        The newly created user.

    Raises:
        EntityExistsError: If a user with the given name already exists.
    """
delete_action(action_id: UUID) -> None abstractmethod

Delete an action.

Parameters:

Name Type Description Default
action_id UUID

The ID of the action to delete.

required

Raises:

Type Description
KeyError

If the action doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
343
344
345
346
347
348
349
350
351
352
@abstractmethod
def delete_action(self, action_id: UUID) -> None:
    """Delete an action.

    Args:
        action_id: The ID of the action to delete.

    Raises:
        KeyError: If the action doesn't exist.
    """
delete_all_model_version_artifact_links(model_version_id: UUID, only_links: bool = True) -> None abstractmethod

Deletes all model version to artifact links.

Parameters:

Name Type Description Default
model_version_id UUID

ID of the model version containing the link.

required
only_links bool

Flag deciding whether to delete only links or all.

True
Source code in src/zenml/zen_stores/zen_store_interface.py
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
@abstractmethod
def delete_all_model_version_artifact_links(
    self,
    model_version_id: UUID,
    only_links: bool = True,
) -> None:
    """Deletes all model version to artifact links.

    Args:
        model_version_id: ID of the model version containing the link.
        only_links: Flag deciding whether to delete only links or all.
    """
delete_api_key(service_account_id: UUID, api_key_name_or_id: Union[str, UUID]) -> None abstractmethod

Delete an API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to delete the API key.

required
api_key_name_or_id Union[str, UUID]

The name or ID of the API key to delete.

required

Raises:

Type Description
KeyError

if an API key with the given name or ID is not configured for the given service account.

Source code in src/zenml/zen_stores/zen_store_interface.py
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
@abstractmethod
def delete_api_key(
    self,
    service_account_id: UUID,
    api_key_name_or_id: Union[str, UUID],
) -> None:
    """Delete an API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to
            delete the API key.
        api_key_name_or_id: The name or ID of the API key to delete.

    Raises:
        KeyError: if an API key with the given name or ID is not configured
            for the given service account.
    """
delete_artifact(artifact_id: UUID) -> None abstractmethod

Deletes an artifact.

Parameters:

Name Type Description Default
artifact_id UUID

The ID of the artifact to delete.

required

Raises:

Type Description
KeyError

if the artifact doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
635
636
637
638
639
640
641
642
643
644
@abstractmethod
def delete_artifact(self, artifact_id: UUID) -> None:
    """Deletes an artifact.

    Args:
        artifact_id: The ID of the artifact to delete.

    Raises:
        KeyError: if the artifact doesn't exist.
    """
delete_artifact_version(artifact_version_id: UUID) -> None abstractmethod

Deletes an artifact version.

Parameters:

Name Type Description Default
artifact_version_id UUID

The ID of the artifact version to delete.

required

Raises:

Type Description
KeyError

if the artifact version doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
730
731
732
733
734
735
736
737
738
739
@abstractmethod
def delete_artifact_version(self, artifact_version_id: UUID) -> None:
    """Deletes an artifact version.

    Args:
        artifact_version_id: The ID of the artifact version to delete.

    Raises:
        KeyError: if the artifact version doesn't exist.
    """
delete_authorized_device(device_id: UUID) -> None abstractmethod

Deletes an OAuth 2.0 authorized device.

Parameters:

Name Type Description Default
device_id UUID

The ID of the device to delete.

required

Raises:

Type Description
KeyError

If no device with the given ID exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
@abstractmethod
def delete_authorized_device(self, device_id: UUID) -> None:
    """Deletes an OAuth 2.0 authorized device.

    Args:
        device_id: The ID of the device to delete.

    Raises:
        KeyError: If no device with the given ID exists.
    """
delete_build(build_id: UUID) -> None abstractmethod

Deletes a build.

Parameters:

Name Type Description Default
build_id UUID

The ID of the build to delete.

required

Raises:

Type Description
KeyError

if the build doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
@abstractmethod
def delete_build(self, build_id: UUID) -> None:
    """Deletes a build.

    Args:
        build_id: The ID of the build to delete.

    Raises:
        KeyError: if the build doesn't exist.
    """
delete_code_repository(code_repository_id: UUID) -> None abstractmethod

Deletes a code repository.

Parameters:

Name Type Description Default
code_repository_id UUID

The ID of the code repository to delete.

required

Raises:

Type Description
KeyError

If no code repository with the given ID exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
866
867
868
869
870
871
872
873
874
875
@abstractmethod
def delete_code_repository(self, code_repository_id: UUID) -> None:
    """Deletes a code repository.

    Args:
        code_repository_id: The ID of the code repository to delete.

    Raises:
        KeyError: If no code repository with the given ID exists.
    """
delete_deployment(deployment_id: UUID) -> None abstractmethod

Deletes a deployment.

Parameters:

Name Type Description Default
deployment_id UUID

The ID of the deployment to delete.

required

Raises:

Type Description
KeyError

If the deployment doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
@abstractmethod
def delete_deployment(self, deployment_id: UUID) -> None:
    """Deletes a deployment.

    Args:
        deployment_id: The ID of the deployment to delete.

    Raises:
        KeyError: If the deployment doesn't exist.
    """
delete_event_source(event_source_id: UUID) -> None abstractmethod

Delete an event_source.

Parameters:

Name Type Description Default
event_source_id UUID

The ID of the event_source to delete.

required

Raises:

Type Description
KeyError

if the event_source doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
@abstractmethod
def delete_event_source(self, event_source_id: UUID) -> None:
    """Delete an event_source.

    Args:
        event_source_id: The ID of the event_source to delete.

    Raises:
        KeyError: if the event_source doesn't exist.
    """
delete_flavor(flavor_id: UUID) -> None abstractmethod

Delete a stack component flavor.

Parameters:

Name Type Description Default
flavor_id UUID

The ID of the stack component flavor to delete.

required

Raises:

Type Description
KeyError

if the stack component flavor doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
@abstractmethod
def delete_flavor(self, flavor_id: UUID) -> None:
    """Delete a stack component flavor.

    Args:
        flavor_id: The ID of the stack component flavor to delete.

    Raises:
        KeyError: if the stack component flavor doesn't exist.
    """
delete_model(model_id: UUID) -> None abstractmethod

Deletes a model.

Parameters:

Name Type Description Default
model_id UUID

id of the model to be deleted.

required

Raises:

Type Description
KeyError

model with specified ID not found.

Source code in src/zenml/zen_stores/zen_store_interface.py
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
@abstractmethod
def delete_model(self, model_id: UUID) -> None:
    """Deletes a model.

    Args:
        model_id: id of the model to be deleted.

    Raises:
        KeyError: model with specified ID not found.
    """
delete_model_version(model_version_id: UUID) -> None abstractmethod

Deletes a model version.

Parameters:

Name Type Description Default
model_version_id UUID

id of the model version to be deleted.

required

Raises:

Type Description
KeyError

specified ID or name not found.

Source code in src/zenml/zen_stores/zen_store_interface.py
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
@abstractmethod
def delete_model_version(
    self,
    model_version_id: UUID,
) -> None:
    """Deletes a model version.

    Args:
        model_version_id: id of the model version to be deleted.

    Raises:
        KeyError: specified ID or name not found.
    """
delete_model_version_artifact_link(model_version_id: UUID, model_version_artifact_link_name_or_id: Union[str, UUID]) -> None abstractmethod

Deletes a model version to artifact link.

Parameters:

Name Type Description Default
model_version_id UUID

ID of the model version containing the link.

required
model_version_artifact_link_name_or_id Union[str, UUID]

name or ID of the model version to artifact link to be deleted.

required

Raises:

Type Description
KeyError

specified ID or name not found.

Source code in src/zenml/zen_stores/zen_store_interface.py
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
@abstractmethod
def delete_model_version_artifact_link(
    self,
    model_version_id: UUID,
    model_version_artifact_link_name_or_id: Union[str, UUID],
) -> None:
    """Deletes a model version to artifact link.

    Args:
        model_version_id: ID of the model version containing the link.
        model_version_artifact_link_name_or_id: name or ID of the model
            version to artifact link to be deleted.

    Raises:
        KeyError: specified ID or name not found.
    """
delete_model_version_pipeline_run_link(model_version_id: UUID, model_version_pipeline_run_link_name_or_id: Union[str, UUID]) -> None abstractmethod

Deletes a model version to pipeline run link.

Parameters:

Name Type Description Default
model_version_id UUID

ID of the model version containing the link.

required
model_version_pipeline_run_link_name_or_id Union[str, UUID]

name or ID of the model version to pipeline run link to be deleted.

required

Raises:

Type Description
KeyError

specified ID not found.

Source code in src/zenml/zen_stores/zen_store_interface.py
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
@abstractmethod
def delete_model_version_pipeline_run_link(
    self,
    model_version_id: UUID,
    model_version_pipeline_run_link_name_or_id: Union[str, UUID],
) -> None:
    """Deletes a model version to pipeline run link.

    Args:
        model_version_id: ID of the model version containing the link.
        model_version_pipeline_run_link_name_or_id: name or ID of the model
            version to pipeline run link to be deleted.

    Raises:
        KeyError: specified ID not found.
    """
delete_pipeline(pipeline_id: UUID) -> None abstractmethod

Deletes a pipeline.

Parameters:

Name Type Description Default
pipeline_id UUID

The ID of the pipeline to delete.

required

Raises:

Type Description
KeyError

if the pipeline doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
@abstractmethod
def delete_pipeline(self, pipeline_id: UUID) -> None:
    """Deletes a pipeline.

    Args:
        pipeline_id: The ID of the pipeline to delete.

    Raises:
        KeyError: if the pipeline doesn't exist.
    """
delete_project(project_name_or_id: Union[str, UUID]) -> None abstractmethod

Deletes a project.

Parameters:

Name Type Description Default
project_name_or_id Union[str, UUID]

Name or ID of the project to delete.

required

Raises:

Type Description
KeyError

If no project with the given name exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
@abstractmethod
def delete_project(self, project_name_or_id: Union[str, UUID]) -> None:
    """Deletes a project.

    Args:
        project_name_or_id: Name or ID of the project to delete.

    Raises:
        KeyError: If no project with the given name exists.
    """
delete_run(run_id: UUID) -> None abstractmethod

Deletes a pipeline run.

Parameters:

Name Type Description Default
run_id UUID

The ID of the pipeline run to delete.

required

Raises:

Type Description
KeyError

if the pipeline run doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
@abstractmethod
def delete_run(self, run_id: UUID) -> None:
    """Deletes a pipeline run.

    Args:
        run_id: The ID of the pipeline run to delete.

    Raises:
        KeyError: if the pipeline run doesn't exist.
    """
delete_run_template(template_id: UUID) -> None abstractmethod

Delete a run template.

Parameters:

Name Type Description Default
template_id UUID

The ID of the template to delete.

required

Raises:

Type Description
KeyError

If the template does not exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
@abstractmethod
def delete_run_template(self, template_id: UUID) -> None:
    """Delete a run template.

    Args:
        template_id: The ID of the template to delete.

    Raises:
        KeyError: If the template does not exist.
    """
delete_schedule(schedule_id: UUID) -> None abstractmethod

Deletes a schedule.

Parameters:

Name Type Description Default
schedule_id UUID

The ID of the schedule to delete.

required

Raises:

Type Description
KeyError

if the schedule doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
@abstractmethod
def delete_schedule(self, schedule_id: UUID) -> None:
    """Deletes a schedule.

    Args:
        schedule_id: The ID of the schedule to delete.

    Raises:
        KeyError: if the schedule doesn't exist.
    """
delete_secret(secret_id: UUID) -> None abstractmethod

Deletes a secret.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret to delete.

required

Raises:

Type Description
KeyError

if the secret doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
@abstractmethod
def delete_secret(self, secret_id: UUID) -> None:
    """Deletes a secret.

    Args:
        secret_id: The ID of the secret to delete.

    Raises:
        KeyError: if the secret doesn't exist.
    """
delete_service(service_id: UUID) -> None abstractmethod

Delete a service.

Parameters:

Name Type Description Default
service_id UUID

The ID of the service to delete.

required

Raises:

Type Description
KeyError

if the service doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
557
558
559
560
561
562
563
564
565
566
@abstractmethod
def delete_service(self, service_id: UUID) -> None:
    """Delete a service.

    Args:
        service_id: The ID of the service to delete.

    Raises:
        KeyError: if the service doesn't exist.
    """
delete_service_account(service_account_name_or_id: Union[str, UUID]) -> None abstractmethod

Delete a service account.

Parameters:

Name Type Description Default
service_account_name_or_id Union[str, UUID]

The name or the ID of the service account to delete.

required

Raises:

Type Description
IllegalOperationError

if the service account has already been used to create other resources.

Source code in src/zenml/zen_stores/zen_store_interface.py
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
@abstractmethod
def delete_service_account(
    self,
    service_account_name_or_id: Union[str, UUID],
) -> None:
    """Delete a service account.

    Args:
        service_account_name_or_id: The name or the ID of the service
            account to delete.

    Raises:
        IllegalOperationError: if the service account has already been used
            to create other resources.
    """
delete_service_connector(service_connector_id: UUID) -> None abstractmethod

Deletes a service connector.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the service connector to delete.

required

Raises:

Type Description
KeyError

If no service connector with the given ID exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
@abstractmethod
def delete_service_connector(self, service_connector_id: UUID) -> None:
    """Deletes a service connector.

    Args:
        service_connector_id: The ID of the service connector to delete.

    Raises:
        KeyError: If no service connector with the given ID exists.
    """
delete_stack(stack_id: UUID) -> None abstractmethod

Delete a stack.

Parameters:

Name Type Description Default
stack_id UUID

The ID of the stack to delete.

required

Raises:

Type Description
KeyError

if the stack doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
@abstractmethod
def delete_stack(self, stack_id: UUID) -> None:
    """Delete a stack.

    Args:
        stack_id: The ID of the stack to delete.

    Raises:
        KeyError: if the stack doesn't exist.
    """
delete_stack_component(component_id: UUID) -> None abstractmethod

Delete a stack component.

Parameters:

Name Type Description Default
component_id UUID

The ID of the stack component to delete.

required

Raises:

Type Description
KeyError

if the stack component doesn't exist.

ValueError

if the stack component is part of one or more stacks.

Source code in src/zenml/zen_stores/zen_store_interface.py
953
954
955
956
957
958
959
960
961
962
963
@abstractmethod
def delete_stack_component(self, component_id: UUID) -> None:
    """Delete a stack component.

    Args:
        component_id: The ID of the stack component to delete.

    Raises:
        KeyError: if the stack component doesn't exist.
        ValueError: if the stack component is part of one or more stacks.
    """
delete_tag(tag_name_or_id: Union[str, UUID]) -> None abstractmethod

Deletes a tag.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

name or id of the tag to delete.

required

Raises:

Type Description
KeyError

specified ID or name not found.

Source code in src/zenml/zen_stores/zen_store_interface.py
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
@abstractmethod
def delete_tag(
    self,
    tag_name_or_id: Union[str, UUID],
) -> None:
    """Deletes a tag.

    Args:
        tag_name_or_id: name or id of the tag to delete.

    Raises:
        KeyError: specified ID or name not found.
    """
delete_tag_resource(tag_resource: TagResourceRequest) -> None abstractmethod

Delete a tag resource relationship.

Parameters:

Name Type Description Default
tag_resource TagResourceRequest

The tag resource relationship to delete.

required
Source code in src/zenml/zen_stores/zen_store_interface.py
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
@abstractmethod
def delete_tag_resource(
    self,
    tag_resource: TagResourceRequest,
) -> None:
    """Delete a tag resource relationship.

    Args:
        tag_resource: The tag resource relationship to delete.
    """
delete_trigger(trigger_id: UUID) -> None abstractmethod

Delete an trigger.

Parameters:

Name Type Description Default
trigger_id UUID

The ID of the trigger to delete.

required

Raises:

Type Description
KeyError

if the trigger doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
@abstractmethod
def delete_trigger(self, trigger_id: UUID) -> None:
    """Delete an trigger.

    Args:
        trigger_id: The ID of the trigger to delete.

    Raises:
        KeyError: if the trigger doesn't exist.
    """
delete_trigger_execution(trigger_execution_id: UUID) -> None abstractmethod

Delete a trigger execution.

Parameters:

Name Type Description Default
trigger_execution_id UUID

The ID of the trigger execution to delete.

required

Raises:

Type Description
KeyError

If the trigger execution doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
@abstractmethod
def delete_trigger_execution(self, trigger_execution_id: UUID) -> None:
    """Delete a trigger execution.

    Args:
        trigger_execution_id: The ID of the trigger execution to delete.

    Raises:
        KeyError: If the trigger execution doesn't exist.
    """
delete_user(user_name_or_id: Union[str, UUID]) -> None abstractmethod

Deletes a user.

Parameters:

Name Type Description Default
user_name_or_id Union[str, UUID]

The name or ID of the user to delete.

required

Raises:

Type Description
KeyError

If no user with the given ID exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
@abstractmethod
def delete_user(self, user_name_or_id: Union[str, UUID]) -> None:
    """Deletes a user.

    Args:
        user_name_or_id: The name or ID of the user to delete.

    Raises:
        KeyError: If no user with the given ID exists.
    """
get_action(action_id: UUID, hydrate: bool = True) -> ActionResponse abstractmethod

Get an action by ID.

Parameters:

Name Type Description Default
action_id UUID

The ID of the action to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ActionResponse

The action.

Raises:

Type Description
KeyError

If the action doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
@abstractmethod
def get_action(
    self,
    action_id: UUID,
    hydrate: bool = True,
) -> ActionResponse:
    """Get an action by ID.

    Args:
        action_id: The ID of the action to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The action.

    Raises:
        KeyError: If the action doesn't exist.
    """
get_api_key(service_account_id: UUID, api_key_name_or_id: Union[str, UUID], hydrate: bool = True) -> APIKeyResponse abstractmethod

Get an API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to fetch the API key.

required
api_key_name_or_id Union[str, UUID]

The name or ID of the API key to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
APIKeyResponse

The API key with the given ID.

Raises:

Type Description
KeyError

if an API key with the given name or ID is not configured for the given service account.

Source code in src/zenml/zen_stores/zen_store_interface.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
@abstractmethod
def get_api_key(
    self,
    service_account_id: UUID,
    api_key_name_or_id: Union[str, UUID],
    hydrate: bool = True,
) -> APIKeyResponse:
    """Get an API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to fetch
            the API key.
        api_key_name_or_id: The name or ID of the API key to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The API key with the given ID.

    Raises:
        KeyError: if an API key with the given name or ID is not configured
            for the given service account.
    """
get_artifact(artifact_id: UUID, hydrate: bool = True) -> ArtifactResponse abstractmethod

Gets an artifact.

Parameters:

Name Type Description Default
artifact_id UUID

The ID of the artifact to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ArtifactResponse

The artifact.

Raises:

Type Description
KeyError

if the artifact doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
@abstractmethod
def get_artifact(
    self, artifact_id: UUID, hydrate: bool = True
) -> ArtifactResponse:
    """Gets an artifact.

    Args:
        artifact_id: The ID of the artifact to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The artifact.

    Raises:
        KeyError: if the artifact doesn't exist.
    """
get_artifact_version(artifact_version_id: UUID, hydrate: bool = True) -> ArtifactVersionResponse abstractmethod

Gets an artifact version.

Parameters:

Name Type Description Default
artifact_version_id UUID

The ID of the artifact version to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ArtifactVersionResponse

The artifact version.

Raises:

Type Description
KeyError

if the artifact version doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
@abstractmethod
def get_artifact_version(
    self, artifact_version_id: UUID, hydrate: bool = True
) -> ArtifactVersionResponse:
    """Gets an artifact version.

    Args:
        artifact_version_id: The ID of the artifact version to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The artifact version.

    Raises:
        KeyError: if the artifact version doesn't exist.
    """
get_artifact_visualization(artifact_visualization_id: UUID, hydrate: bool = True) -> ArtifactVisualizationResponse abstractmethod

Gets an artifact visualization.

Parameters:

Name Type Description Default
artifact_visualization_id UUID

The ID of the artifact visualization to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ArtifactVisualizationResponse

The artifact visualization.

Raises:

Type Description
KeyError

if the artifact visualization doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
@abstractmethod
def get_artifact_visualization(
    self, artifact_visualization_id: UUID, hydrate: bool = True
) -> ArtifactVisualizationResponse:
    """Gets an artifact visualization.

    Args:
        artifact_visualization_id: The ID of the artifact visualization
            to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The artifact visualization.

    Raises:
        KeyError: if the artifact visualization doesn't exist.
    """
get_authorized_device(device_id: UUID, hydrate: bool = True) -> OAuthDeviceResponse abstractmethod

Gets a specific OAuth 2.0 authorized device.

Parameters:

Name Type Description Default
device_id UUID

The ID of the device to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
OAuthDeviceResponse

The requested device, if it was found.

Raises:

Type Description
KeyError

If no device with the given ID exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
@abstractmethod
def get_authorized_device(
    self, device_id: UUID, hydrate: bool = True
) -> OAuthDeviceResponse:
    """Gets a specific OAuth 2.0 authorized device.

    Args:
        device_id: The ID of the device to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested device, if it was found.

    Raises:
        KeyError: If no device with the given ID exists.
    """
get_build(build_id: UUID, hydrate: bool = True) -> PipelineBuildResponse abstractmethod

Get a build with a given ID.

Parameters:

Name Type Description Default
build_id UUID

ID of the build.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineBuildResponse

The build.

Raises:

Type Description
KeyError

If the build does not exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
@abstractmethod
def get_build(
    self, build_id: UUID, hydrate: bool = True
) -> PipelineBuildResponse:
    """Get a build with a given ID.

    Args:
        build_id: ID of the build.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The build.

    Raises:
        KeyError: If the build does not exist.
    """
get_code_reference(code_reference_id: UUID, hydrate: bool = True) -> CodeReferenceResponse abstractmethod

Gets a specific code reference.

Parameters:

Name Type Description Default
code_reference_id UUID

The ID of the code reference to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
CodeReferenceResponse

The requested code reference, if it was found.

Raises:

Type Description
KeyError

If no code reference with the given ID exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
@abstractmethod
def get_code_reference(
    self, code_reference_id: UUID, hydrate: bool = True
) -> CodeReferenceResponse:
    """Gets a specific code reference.

    Args:
        code_reference_id: The ID of the code reference to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested code reference, if it was found.

    Raises:
        KeyError: If no code reference with the given ID exists.
    """
get_code_repository(code_repository_id: UUID, hydrate: bool = True) -> CodeRepositoryResponse abstractmethod

Gets a specific code repository.

Parameters:

Name Type Description Default
code_repository_id UUID

The ID of the code repository to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
CodeRepositoryResponse

The requested code repository, if it was found.

Raises:

Type Description
KeyError

If no code repository with the given ID exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
@abstractmethod
def get_code_repository(
    self, code_repository_id: UUID, hydrate: bool = True
) -> CodeRepositoryResponse:
    """Gets a specific code repository.

    Args:
        code_repository_id: The ID of the code repository to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested code repository, if it was found.

    Raises:
        KeyError: If no code repository with the given ID exists.
    """
get_deployment(deployment_id: UUID, hydrate: bool = True) -> PipelineDeploymentResponse abstractmethod

Get a deployment with a given ID.

Parameters:

Name Type Description Default
deployment_id UUID

ID of the deployment.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineDeploymentResponse

The deployment.

Raises:

Type Description
KeyError

If the deployment does not exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
@abstractmethod
def get_deployment(
    self, deployment_id: UUID, hydrate: bool = True
) -> PipelineDeploymentResponse:
    """Get a deployment with a given ID.

    Args:
        deployment_id: ID of the deployment.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The deployment.

    Raises:
        KeyError: If the deployment does not exist.
    """
get_deployment_id() -> UUID abstractmethod

Get the ID of the deployment.

Returns:

Type Description
UUID

The ID of the deployment.

Source code in src/zenml/zen_stores/zen_store_interface.py
236
237
238
239
240
241
242
@abstractmethod
def get_deployment_id(self) -> UUID:
    """Get the ID of the deployment.

    Returns:
        The ID of the deployment.
    """
get_event_source(event_source_id: UUID, hydrate: bool = True) -> EventSourceResponse abstractmethod

Get an event_source by ID.

Parameters:

Name Type Description Default
event_source_id UUID

The ID of the event_source to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
EventSourceResponse

The event_source.

Raises:

Type Description
KeyError

if the stack event_source doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
@abstractmethod
def get_event_source(
    self,
    event_source_id: UUID,
    hydrate: bool = True,
) -> EventSourceResponse:
    """Get an event_source by ID.

    Args:
        event_source_id: The ID of the event_source to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The event_source.

    Raises:
        KeyError: if the stack event_source doesn't exist.
    """
get_flavor(flavor_id: UUID, hydrate: bool = True) -> FlavorResponse abstractmethod

Get a stack component flavor by ID.

Parameters:

Name Type Description Default
flavor_id UUID

The ID of the flavor to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
FlavorResponse

The stack component flavor.

Raises:

Type Description
KeyError

if the stack component flavor doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
@abstractmethod
def get_flavor(
    self, flavor_id: UUID, hydrate: bool = True
) -> FlavorResponse:
    """Get a stack component flavor by ID.

    Args:
        flavor_id: The ID of the flavor to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The stack component flavor.

    Raises:
        KeyError: if the stack component flavor doesn't exist.
    """
get_logs(logs_id: UUID, hydrate: bool = True) -> LogsResponse abstractmethod

Get logs by its unique ID.

Parameters:

Name Type Description Default
logs_id UUID

The ID of the logs to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
LogsResponse

The logs with the given ID.

Raises:

Type Description
KeyError

if the logs doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
@abstractmethod
def get_logs(self, logs_id: UUID, hydrate: bool = True) -> LogsResponse:
    """Get logs by its unique ID.

    Args:
        logs_id: The ID of the logs to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The logs with the given ID.

    Raises:
        KeyError: if the logs doesn't exist.
    """
get_model(model_id: UUID, hydrate: bool = True) -> ModelResponse abstractmethod

Get an existing model.

Parameters:

Name Type Description Default
model_id UUID

id of the model to be retrieved.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ModelResponse

The model of interest.

Raises:

Type Description
KeyError

model with specified ID not found.

Source code in src/zenml/zen_stores/zen_store_interface.py
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
@abstractmethod
def get_model(self, model_id: UUID, hydrate: bool = True) -> ModelResponse:
    """Get an existing model.

    Args:
        model_id: id of the model to be retrieved.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The model of interest.

    Raises:
        KeyError: model with specified ID not found.
    """
get_model_version(model_version_id: UUID, hydrate: bool = True) -> ModelVersionResponse abstractmethod

Get an existing model version.

Parameters:

Name Type Description Default
model_version_id UUID

name, id, stage or number of the model version to be retrieved. If skipped - latest is retrieved.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ModelVersionResponse

The model version of interest.

Raises:

Type Description
KeyError

specified ID or name not found.

Source code in src/zenml/zen_stores/zen_store_interface.py
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
@abstractmethod
def get_model_version(
    self, model_version_id: UUID, hydrate: bool = True
) -> ModelVersionResponse:
    """Get an existing model version.

    Args:
        model_version_id: name, id, stage or number of the model version to
            be retrieved. If skipped - latest is retrieved.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.


    Returns:
        The model version of interest.

    Raises:
        KeyError: specified ID or name not found.
    """
get_or_create_run(pipeline_run: PipelineRunRequest) -> Tuple[PipelineRunResponse, bool] abstractmethod

Gets or creates a pipeline run.

If a run with the same ID or name already exists, it is returned. Otherwise, a new run is created.

Parameters:

Name Type Description Default
pipeline_run PipelineRunRequest

The pipeline run to get or create.

required

Returns:

Type Description
PipelineRunResponse

The pipeline run, and a boolean indicating whether the run was

bool

created or not.

Source code in src/zenml/zen_stores/zen_store_interface.py
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
@abstractmethod
def get_or_create_run(
    self, pipeline_run: PipelineRunRequest
) -> Tuple[PipelineRunResponse, bool]:
    """Gets or creates a pipeline run.

    If a run with the same ID or name already exists, it is returned.
    Otherwise, a new run is created.

    Args:
        pipeline_run: The pipeline run to get or create.

    Returns:
        The pipeline run, and a boolean indicating whether the run was
        created or not.
    """
get_pipeline(pipeline_id: UUID, hydrate: bool = True) -> PipelineResponse abstractmethod

Get a pipeline with a given ID.

Parameters:

Name Type Description Default
pipeline_id UUID

ID of the pipeline.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineResponse

The pipeline.

Raises:

Type Description
KeyError

if the pipeline does not exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
@abstractmethod
def get_pipeline(
    self, pipeline_id: UUID, hydrate: bool = True
) -> PipelineResponse:
    """Get a pipeline with a given ID.

    Args:
        pipeline_id: ID of the pipeline.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The pipeline.

    Raises:
        KeyError: if the pipeline does not exist.
    """
get_project(project_name_or_id: Union[UUID, str], hydrate: bool = True) -> ProjectResponse abstractmethod

Get an existing project by name or ID.

Parameters:

Name Type Description Default
project_name_or_id Union[UUID, str]

Name or ID of the project to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ProjectResponse

The requested project.

Raises:

Type Description
KeyError

If there is no such project.

Source code in src/zenml/zen_stores/zen_store_interface.py
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
@abstractmethod
def get_project(
    self, project_name_or_id: Union[UUID, str], hydrate: bool = True
) -> ProjectResponse:
    """Get an existing project by name or ID.

    Args:
        project_name_or_id: Name or ID of the project to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested project.

    Raises:
        KeyError: If there is no such project.
    """
get_run(run_id: UUID, hydrate: bool = True) -> PipelineRunResponse abstractmethod

Gets a pipeline run.

Parameters:

Name Type Description Default
run_id UUID

The ID of the pipeline run to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineRunResponse

The pipeline run.

Raises:

Type Description
KeyError

if the pipeline run doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
@abstractmethod
def get_run(
    self, run_id: UUID, hydrate: bool = True
) -> PipelineRunResponse:
    """Gets a pipeline run.

    Args:
        run_id: The ID of the pipeline run to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The pipeline run.

    Raises:
        KeyError: if the pipeline run doesn't exist.
    """
get_run_step(step_run_id: UUID, hydrate: bool = True) -> StepRunResponse abstractmethod

Get a step run by ID.

Parameters:

Name Type Description Default
step_run_id UUID

The ID of the step run to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
StepRunResponse

The step run.

Raises:

Type Description
KeyError

if the step run doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
@abstractmethod
def get_run_step(
    self, step_run_id: UUID, hydrate: bool = True
) -> StepRunResponse:
    """Get a step run by ID.

    Args:
        step_run_id: The ID of the step run to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The step run.

    Raises:
        KeyError: if the step run doesn't exist.
    """
get_run_template(template_id: UUID, hydrate: bool = True) -> RunTemplateResponse abstractmethod

Get a run template with a given ID.

Parameters:

Name Type Description Default
template_id UUID

ID of the template.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
RunTemplateResponse

The template.

Raises:

Type Description
KeyError

If the template does not exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
@abstractmethod
def get_run_template(
    self, template_id: UUID, hydrate: bool = True
) -> RunTemplateResponse:
    """Get a run template with a given ID.

    Args:
        template_id: ID of the template.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The template.

    Raises:
        KeyError: If the template does not exist.
    """
get_schedule(schedule_id: UUID, hydrate: bool = True) -> ScheduleResponse abstractmethod

Get a schedule with a given ID.

Parameters:

Name Type Description Default
schedule_id UUID

ID of the schedule.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ScheduleResponse

The schedule.

Raises:

Type Description
KeyError

if the schedule does not exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
@abstractmethod
def get_schedule(
    self, schedule_id: UUID, hydrate: bool = True
) -> ScheduleResponse:
    """Get a schedule with a given ID.

    Args:
        schedule_id: ID of the schedule.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The schedule.

    Raises:
        KeyError: if the schedule does not exist.
    """
get_secret(secret_id: UUID, hydrate: bool = True) -> SecretResponse abstractmethod

Get a secret with a given name.

Parameters:

Name Type Description Default
secret_id UUID

ID of the secret.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
SecretResponse

The secret.

Raises:

Type Description
KeyError

if the secret does not exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
@abstractmethod
def get_secret(
    self, secret_id: UUID, hydrate: bool = True
) -> SecretResponse:
    """Get a secret with a given name.

    Args:
        secret_id: ID of the secret.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The secret.

    Raises:
        KeyError: if the secret does not exist.
    """
get_server_settings(hydrate: bool = True) -> ServerSettingsResponse abstractmethod

Get the server settings.

Parameters:

Name Type Description Default
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServerSettingsResponse

The server settings.

Source code in src/zenml/zen_stores/zen_store_interface.py
246
247
248
249
250
251
252
253
254
255
256
257
258
@abstractmethod
def get_server_settings(
    self, hydrate: bool = True
) -> ServerSettingsResponse:
    """Get the server settings.

    Args:
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The server settings.
    """
get_service(service_id: UUID, hydrate: bool = True) -> ServiceResponse abstractmethod

Get a service by ID.

Parameters:

Name Type Description Default
service_id UUID

The ID of the service to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServiceResponse

The service.

Raises:

Type Description
KeyError

if the service doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
@abstractmethod
def get_service(
    self, service_id: UUID, hydrate: bool = True
) -> ServiceResponse:
    """Get a service by ID.

    Args:
        service_id: The ID of the service to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The service.

    Raises:
        KeyError: if the service doesn't exist.
    """
get_service_account(service_account_name_or_id: Union[str, UUID], hydrate: bool = True) -> ServiceAccountResponse abstractmethod

Gets a specific service account.

Parameters:

Name Type Description Default
service_account_name_or_id Union[str, UUID]

The name or ID of the service account to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServiceAccountResponse

The requested service account, if it was found.

Raises:

Type Description
KeyError

If no service account with the given name or ID exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
@abstractmethod
def get_service_account(
    self,
    service_account_name_or_id: Union[str, UUID],
    hydrate: bool = True,
) -> ServiceAccountResponse:
    """Gets a specific service account.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested service account, if it was found.

    Raises:
        KeyError: If no service account with the given name or ID exists.
    """
get_service_connector(service_connector_id: UUID, hydrate: bool = True) -> ServiceConnectorResponse abstractmethod

Gets a specific service connector.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the service connector to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServiceConnectorResponse

The requested service connector, if it was found.

Raises:

Type Description
KeyError

If no service connector with the given ID exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
@abstractmethod
def get_service_connector(
    self, service_connector_id: UUID, hydrate: bool = True
) -> ServiceConnectorResponse:
    """Gets a specific service connector.

    Args:
        service_connector_id: The ID of the service connector to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested service connector, if it was found.

    Raises:
        KeyError: If no service connector with the given ID exists.
    """
get_service_connector_client(service_connector_id: UUID, resource_type: Optional[str] = None, resource_id: Optional[str] = None) -> ServiceConnectorResponse abstractmethod

Get a service connector client for a service connector and given resource.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the base service connector to use.

required
resource_type Optional[str]

The type of resource to get a client for.

None
resource_id Optional[str]

The ID of the resource to get a client for.

None

Returns:

Type Description
ServiceConnectorResponse

A service connector client that can be used to access the given

ServiceConnectorResponse

resource.

Raises:

Type Description
KeyError

If no service connector with the given name exists.

NotImplementError

If the service connector cannot be instantiated on the store e.g. due to missing package dependencies.

Source code in src/zenml/zen_stores/zen_store_interface.py
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
@abstractmethod
def get_service_connector_client(
    self,
    service_connector_id: UUID,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
) -> ServiceConnectorResponse:
    """Get a service connector client for a service connector and given resource.

    Args:
        service_connector_id: The ID of the base service connector to use.
        resource_type: The type of resource to get a client for.
        resource_id: The ID of the resource to get a client for.

    Returns:
        A service connector client that can be used to access the given
        resource.

    Raises:
        KeyError: If no service connector with the given name exists.
        NotImplementError: If the service connector cannot be instantiated
            on the store e.g. due to missing package dependencies.
    """
get_service_connector_type(connector_type: str) -> ServiceConnectorTypeModel abstractmethod

Returns the requested service connector type.

Parameters:

Name Type Description Default
connector_type str

the service connector type identifier.

required

Returns:

Type Description
ServiceConnectorTypeModel

The requested service connector type.

Raises:

Type Description
KeyError

If no service connector type with the given ID exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
@abstractmethod
def get_service_connector_type(
    self,
    connector_type: str,
) -> ServiceConnectorTypeModel:
    """Returns the requested service connector type.

    Args:
        connector_type: the service connector type identifier.

    Returns:
        The requested service connector type.

    Raises:
        KeyError: If no service connector type with the given ID exists.
    """
get_stack(stack_id: UUID, hydrate: bool = True) -> StackResponse abstractmethod

Get a stack by its unique ID.

Parameters:

Name Type Description Default
stack_id UUID

The ID of the stack to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
StackResponse

The stack with the given ID.

Raises:

Type Description
KeyError

if the stack doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
@abstractmethod
def get_stack(self, stack_id: UUID, hydrate: bool = True) -> StackResponse:
    """Get a stack by its unique ID.

    Args:
        stack_id: The ID of the stack to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The stack with the given ID.

    Raises:
        KeyError: if the stack doesn't exist.
    """
get_stack_component(component_id: UUID, hydrate: bool = True) -> ComponentResponse abstractmethod

Get a stack component by ID.

Parameters:

Name Type Description Default
component_id UUID

The ID of the stack component to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ComponentResponse

The stack component.

Raises:

Type Description
KeyError

if the stack component doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
@abstractmethod
def get_stack_component(
    self,
    component_id: UUID,
    hydrate: bool = True,
) -> ComponentResponse:
    """Get a stack component by ID.

    Args:
        component_id: The ID of the stack component to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The stack component.

    Raises:
        KeyError: if the stack component doesn't exist.
    """
get_stack_deployment_config(provider: StackDeploymentProvider, stack_name: str, location: Optional[str] = None) -> StackDeploymentConfig abstractmethod

Return the cloud provider console URL and configuration needed to deploy the ZenML stack.

Parameters:

Name Type Description Default
provider StackDeploymentProvider

The stack deployment provider.

required
stack_name str

The name of the stack.

required
location Optional[str]

The location where the stack should be deployed.

None

Returns:

Type Description
StackDeploymentConfig

The cloud provider console URL and configuration needed to deploy

StackDeploymentConfig

the ZenML stack to the specified cloud provider.

Source code in src/zenml/zen_stores/zen_store_interface.py
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
@abstractmethod
def get_stack_deployment_config(
    self,
    provider: StackDeploymentProvider,
    stack_name: str,
    location: Optional[str] = None,
) -> StackDeploymentConfig:
    """Return the cloud provider console URL and configuration needed to deploy the ZenML stack.

    Args:
        provider: The stack deployment provider.
        stack_name: The name of the stack.
        location: The location where the stack should be deployed.

    Returns:
        The cloud provider console URL and configuration needed to deploy
        the ZenML stack to the specified cloud provider.
    """
get_stack_deployment_info(provider: StackDeploymentProvider) -> StackDeploymentInfo abstractmethod

Get information about a stack deployment provider.

Parameters:

Name Type Description Default
provider StackDeploymentProvider

The stack deployment provider.

required

Returns:

Type Description
StackDeploymentInfo

Information about the stack deployment provider.

Source code in src/zenml/zen_stores/zen_store_interface.py
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
@abstractmethod
def get_stack_deployment_info(
    self,
    provider: StackDeploymentProvider,
) -> StackDeploymentInfo:
    """Get information about a stack deployment provider.

    Args:
        provider: The stack deployment provider.

    Returns:
        Information about the stack deployment provider.
    """
get_stack_deployment_stack(provider: StackDeploymentProvider, stack_name: str, location: Optional[str] = None, date_start: Optional[datetime.datetime] = None) -> Optional[DeployedStack] abstractmethod

Return a matching ZenML stack that was deployed and registered.

Parameters:

Name Type Description Default
provider StackDeploymentProvider

The stack deployment provider.

required
stack_name str

The name of the stack.

required
location Optional[str]

The location where the stack should be deployed.

None
date_start Optional[datetime]

The date when the deployment started.

None

Returns:

Type Description
Optional[DeployedStack]

The ZenML stack that was deployed and registered or None if the

Optional[DeployedStack]

stack was not found.

Source code in src/zenml/zen_stores/zen_store_interface.py
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
@abstractmethod
def get_stack_deployment_stack(
    self,
    provider: StackDeploymentProvider,
    stack_name: str,
    location: Optional[str] = None,
    date_start: Optional[datetime.datetime] = None,
) -> Optional[DeployedStack]:
    """Return a matching ZenML stack that was deployed and registered.

    Args:
        provider: The stack deployment provider.
        stack_name: The name of the stack.
        location: The location where the stack should be deployed.
        date_start: The date when the deployment started.

    Returns:
        The ZenML stack that was deployed and registered or None if the
        stack was not found.
    """
get_store_info() -> ServerModel abstractmethod

Get information about the store.

Returns:

Type Description
ServerModel

Information about the store.

Source code in src/zenml/zen_stores/zen_store_interface.py
228
229
230
231
232
233
234
@abstractmethod
def get_store_info(self) -> ServerModel:
    """Get information about the store.

    Returns:
        Information about the store.
    """
get_tag(tag_name_or_id: Union[str, UUID], hydrate: bool = True) -> TagResponse abstractmethod

Get an existing tag.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

name or id of the tag to be retrieved.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
TagResponse

The tag of interest.

Raises:

Type Description
KeyError

specified ID or name not found.

Source code in src/zenml/zen_stores/zen_store_interface.py
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
@abstractmethod
def get_tag(
    self,
    tag_name_or_id: Union[str, UUID],
    hydrate: bool = True,
) -> TagResponse:
    """Get an existing tag.

    Args:
        tag_name_or_id: name or id of the tag to be retrieved.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The tag of interest.

    Raises:
        KeyError: specified ID or name not found.
    """
get_trigger(trigger_id: UUID, hydrate: bool = True) -> TriggerResponse abstractmethod

Get an trigger by ID.

Parameters:

Name Type Description Default
trigger_id UUID

The ID of the trigger to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
TriggerResponse

The trigger.

Raises:

Type Description
KeyError

if the stack trigger doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
@abstractmethod
def get_trigger(
    self,
    trigger_id: UUID,
    hydrate: bool = True,
) -> TriggerResponse:
    """Get an trigger by ID.

    Args:
        trigger_id: The ID of the trigger to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The trigger.

    Raises:
        KeyError: if the stack trigger doesn't exist.
    """
get_trigger_execution(trigger_execution_id: UUID, hydrate: bool = True) -> TriggerExecutionResponse abstractmethod

Get a trigger execution by ID.

Parameters:

Name Type Description Default
trigger_execution_id UUID

The ID of the trigger execution to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
TriggerExecutionResponse

The trigger execution.

Raises:

Type Description
KeyError

If the trigger execution doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
@abstractmethod
def get_trigger_execution(
    self,
    trigger_execution_id: UUID,
    hydrate: bool = True,
) -> TriggerExecutionResponse:
    """Get a trigger execution by ID.

    Args:
        trigger_execution_id: The ID of the trigger execution to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The trigger execution.

    Raises:
        KeyError: If the trigger execution doesn't exist.
    """
get_user(user_name_or_id: Optional[Union[str, UUID]] = None, include_private: bool = False, hydrate: bool = True) -> UserResponse abstractmethod

Gets a specific user, when no id is specified the active user is returned.

Parameters:

Name Type Description Default
user_name_or_id Optional[Union[str, UUID]]

The name or ID of the user to get.

None
include_private bool

Whether to include private user information.

False
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
UserResponse

The requested user, if it was found.

Raises:

Type Description
KeyError

If no user with the given name or ID exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
@abstractmethod
def get_user(
    self,
    user_name_or_id: Optional[Union[str, UUID]] = None,
    include_private: bool = False,
    hydrate: bool = True,
) -> UserResponse:
    """Gets a specific user, when no id is specified the active user is returned.

    Args:
        user_name_or_id: The name or ID of the user to get.
        include_private: Whether to include private user information.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested user, if it was found.

    Raises:
        KeyError: If no user with the given name or ID exists.
    """
list_actions(action_filter_model: ActionFilter, hydrate: bool = False) -> Page[ActionResponse] abstractmethod

List all actions matching the given filter criteria.

Parameters:

Name Type Description Default
action_filter_model ActionFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ActionResponse]

A list of all actions matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
@abstractmethod
def list_actions(
    self,
    action_filter_model: ActionFilter,
    hydrate: bool = False,
) -> Page[ActionResponse]:
    """List all actions matching the given filter criteria.

    Args:
        action_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all actions matching the filter criteria.
    """
list_api_keys(service_account_id: UUID, filter_model: APIKeyFilter, hydrate: bool = False) -> Page[APIKeyResponse] abstractmethod

List all API keys for a service account matching the given filter criteria.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to list the API keys.

required
filter_model APIKeyFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[APIKeyResponse]

A list of all API keys matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
@abstractmethod
def list_api_keys(
    self,
    service_account_id: UUID,
    filter_model: APIKeyFilter,
    hydrate: bool = False,
) -> Page[APIKeyResponse]:
    """List all API keys for a service account matching the given filter criteria.

    Args:
        service_account_id: The ID of the service account for which to list
            the API keys.
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all API keys matching the filter criteria.
    """
list_artifact_versions(artifact_version_filter_model: ArtifactVersionFilter, hydrate: bool = False) -> Page[ArtifactVersionResponse] abstractmethod

List all artifact versions matching the given filter criteria.

Parameters:

Name Type Description Default
artifact_version_filter_model ArtifactVersionFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ArtifactVersionResponse]

A list of all artifact versions matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
@abstractmethod
def list_artifact_versions(
    self,
    artifact_version_filter_model: ArtifactVersionFilter,
    hydrate: bool = False,
) -> Page[ArtifactVersionResponse]:
    """List all artifact versions matching the given filter criteria.

    Args:
        artifact_version_filter_model: All filter parameters including
            pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all artifact versions matching the filter criteria.
    """
list_artifacts(filter_model: ArtifactFilter, hydrate: bool = False) -> Page[ArtifactResponse] abstractmethod

List all artifacts matching the given filter criteria.

Parameters:

Name Type Description Default
filter_model ArtifactFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ArtifactResponse]

A list of all artifacts matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
@abstractmethod
def list_artifacts(
    self, filter_model: ArtifactFilter, hydrate: bool = False
) -> Page[ArtifactResponse]:
    """List all artifacts matching the given filter criteria.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all artifacts matching the filter criteria.
    """
list_authorized_devices(filter_model: OAuthDeviceFilter, hydrate: bool = False) -> Page[OAuthDeviceResponse] abstractmethod

List all OAuth 2.0 authorized devices for a user.

Parameters:

Name Type Description Default
filter_model OAuthDeviceFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[OAuthDeviceResponse]

A page of all matching OAuth 2.0 authorized devices.

Source code in src/zenml/zen_stores/zen_store_interface.py
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
@abstractmethod
def list_authorized_devices(
    self, filter_model: OAuthDeviceFilter, hydrate: bool = False
) -> Page[OAuthDeviceResponse]:
    """List all OAuth 2.0 authorized devices for a user.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all matching OAuth 2.0 authorized devices.
    """
list_builds(build_filter_model: PipelineBuildFilter, hydrate: bool = False) -> Page[PipelineBuildResponse] abstractmethod

List all builds matching the given filter criteria.

Parameters:

Name Type Description Default
build_filter_model PipelineBuildFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineBuildResponse]

A page of all builds matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
@abstractmethod
def list_builds(
    self,
    build_filter_model: PipelineBuildFilter,
    hydrate: bool = False,
) -> Page[PipelineBuildResponse]:
    """List all builds matching the given filter criteria.

    Args:
        build_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all builds matching the filter criteria.
    """
list_code_repositories(filter_model: CodeRepositoryFilter, hydrate: bool = False) -> Page[CodeRepositoryResponse] abstractmethod

List all code repositories.

Parameters:

Name Type Description Default
filter_model CodeRepositoryFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[CodeRepositoryResponse]

A page of all code repositories.

Source code in src/zenml/zen_stores/zen_store_interface.py
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
@abstractmethod
def list_code_repositories(
    self, filter_model: CodeRepositoryFilter, hydrate: bool = False
) -> Page[CodeRepositoryResponse]:
    """List all code repositories.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all code repositories.
    """
list_deployments(deployment_filter_model: PipelineDeploymentFilter, hydrate: bool = False) -> Page[PipelineDeploymentResponse] abstractmethod

List all deployments matching the given filter criteria.

Parameters:

Name Type Description Default
deployment_filter_model PipelineDeploymentFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineDeploymentResponse]

A page of all deployments matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
@abstractmethod
def list_deployments(
    self,
    deployment_filter_model: PipelineDeploymentFilter,
    hydrate: bool = False,
) -> Page[PipelineDeploymentResponse]:
    """List all deployments matching the given filter criteria.

    Args:
        deployment_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all deployments matching the filter criteria.
    """
list_event_sources(event_source_filter_model: EventSourceFilter, hydrate: bool = False) -> Page[EventSourceResponse] abstractmethod

List all event_sources matching the given filter criteria.

Parameters:

Name Type Description Default
event_source_filter_model EventSourceFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[EventSourceResponse]

A list of all event_sources matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
@abstractmethod
def list_event_sources(
    self,
    event_source_filter_model: EventSourceFilter,
    hydrate: bool = False,
) -> Page[EventSourceResponse]:
    """List all event_sources matching the given filter criteria.

    Args:
        event_source_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all event_sources matching the filter criteria.
    """
list_flavors(flavor_filter_model: FlavorFilter, hydrate: bool = False) -> Page[FlavorResponse] abstractmethod

List all stack component flavors matching the given filter criteria.

Parameters:

Name Type Description Default
flavor_filter_model FlavorFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[FlavorResponse]

List of all the stack component flavors matching the given criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
@abstractmethod
def list_flavors(
    self,
    flavor_filter_model: FlavorFilter,
    hydrate: bool = False,
) -> Page[FlavorResponse]:
    """List all stack component flavors matching the given filter criteria.

    Args:
        flavor_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        List of all the stack component flavors matching the given criteria.
    """
list_model_version_artifact_links(model_version_artifact_link_filter_model: ModelVersionArtifactFilter, hydrate: bool = False) -> Page[ModelVersionArtifactResponse] abstractmethod

Get all model version to artifact links by filter.

Parameters:

Name Type Description Default
model_version_artifact_link_filter_model ModelVersionArtifactFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ModelVersionArtifactResponse]

A page of all model version to artifact links.

Source code in src/zenml/zen_stores/zen_store_interface.py
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
@abstractmethod
def list_model_version_artifact_links(
    self,
    model_version_artifact_link_filter_model: ModelVersionArtifactFilter,
    hydrate: bool = False,
) -> Page[ModelVersionArtifactResponse]:
    """Get all model version to artifact links by filter.

    Args:
        model_version_artifact_link_filter_model: All filter parameters
            including pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all model version to artifact links.
    """
list_model_version_pipeline_run_links(model_version_pipeline_run_link_filter_model: ModelVersionPipelineRunFilter, hydrate: bool = False) -> Page[ModelVersionPipelineRunResponse] abstractmethod

Get all model version to pipeline run links by filter.

Parameters:

Name Type Description Default
model_version_pipeline_run_link_filter_model ModelVersionPipelineRunFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ModelVersionPipelineRunResponse]

A page of all model version to pipeline run links.

Source code in src/zenml/zen_stores/zen_store_interface.py
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
@abstractmethod
def list_model_version_pipeline_run_links(
    self,
    model_version_pipeline_run_link_filter_model: ModelVersionPipelineRunFilter,
    hydrate: bool = False,
) -> Page[ModelVersionPipelineRunResponse]:
    """Get all model version to pipeline run links by filter.

    Args:
        model_version_pipeline_run_link_filter_model: All filter parameters
            including pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all model version to pipeline run links.
    """
list_model_versions(model_version_filter_model: ModelVersionFilter, hydrate: bool = False) -> Page[ModelVersionResponse] abstractmethod

Get all model versions by filter.

Parameters:

Name Type Description Default
model_version_filter_model ModelVersionFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ModelVersionResponse]

A page of all model versions.

Source code in src/zenml/zen_stores/zen_store_interface.py
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
@abstractmethod
def list_model_versions(
    self,
    model_version_filter_model: ModelVersionFilter,
    hydrate: bool = False,
) -> Page[ModelVersionResponse]:
    """Get all model versions by filter.

    Args:
        model_version_filter_model: All filter parameters including
            pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all model versions.
    """
list_models(model_filter_model: ModelFilter, hydrate: bool = False) -> Page[ModelResponse] abstractmethod

Get all models by filter.

Parameters:

Name Type Description Default
model_filter_model ModelFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ModelResponse]

A page of all models.

Source code in src/zenml/zen_stores/zen_store_interface.py
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
@abstractmethod
def list_models(
    self,
    model_filter_model: ModelFilter,
    hydrate: bool = False,
) -> Page[ModelResponse]:
    """Get all models by filter.

    Args:
        model_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all models.
    """
list_pipelines(pipeline_filter_model: PipelineFilter, hydrate: bool = False) -> Page[PipelineResponse] abstractmethod

List all pipelines matching the given filter criteria.

Parameters:

Name Type Description Default
pipeline_filter_model PipelineFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineResponse]

A list of all pipelines matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
@abstractmethod
def list_pipelines(
    self,
    pipeline_filter_model: PipelineFilter,
    hydrate: bool = False,
) -> Page[PipelineResponse]:
    """List all pipelines matching the given filter criteria.

    Args:
        pipeline_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all pipelines matching the filter criteria.
    """
list_projects(project_filter_model: ProjectFilter, hydrate: bool = False) -> Page[ProjectResponse] abstractmethod

List all projects matching the given filter criteria.

Parameters:

Name Type Description Default
project_filter_model ProjectFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ProjectResponse]

A list of all projects matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
@abstractmethod
def list_projects(
    self,
    project_filter_model: ProjectFilter,
    hydrate: bool = False,
) -> Page[ProjectResponse]:
    """List all projects matching the given filter criteria.

    Args:
        project_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all projects matching the filter criteria.
    """
list_run_steps(step_run_filter_model: StepRunFilter, hydrate: bool = False) -> Page[StepRunResponse] abstractmethod

List all step runs matching the given filter criteria.

Parameters:

Name Type Description Default
step_run_filter_model StepRunFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[StepRunResponse]

A list of all step runs matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
@abstractmethod
def list_run_steps(
    self,
    step_run_filter_model: StepRunFilter,
    hydrate: bool = False,
) -> Page[StepRunResponse]:
    """List all step runs matching the given filter criteria.

    Args:
        step_run_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all step runs matching the filter criteria.
    """
list_run_templates(template_filter_model: RunTemplateFilter, hydrate: bool = False) -> Page[RunTemplateResponse] abstractmethod

List all run templates matching the given filter criteria.

Parameters:

Name Type Description Default
template_filter_model RunTemplateFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[RunTemplateResponse]

A list of all templates matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
@abstractmethod
def list_run_templates(
    self,
    template_filter_model: RunTemplateFilter,
    hydrate: bool = False,
) -> Page[RunTemplateResponse]:
    """List all run templates matching the given filter criteria.

    Args:
        template_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all templates matching the filter criteria.
    """
list_runs(runs_filter_model: PipelineRunFilter, hydrate: bool = False) -> Page[PipelineRunResponse] abstractmethod

List all pipeline runs matching the given filter criteria.

Parameters:

Name Type Description Default
runs_filter_model PipelineRunFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineRunResponse]

A list of all pipeline runs matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
@abstractmethod
def list_runs(
    self,
    runs_filter_model: PipelineRunFilter,
    hydrate: bool = False,
) -> Page[PipelineRunResponse]:
    """List all pipeline runs matching the given filter criteria.

    Args:
        runs_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all pipeline runs matching the filter criteria.
    """
list_schedules(schedule_filter_model: ScheduleFilter, hydrate: bool = False) -> Page[ScheduleResponse] abstractmethod

List all schedules.

Parameters:

Name Type Description Default
schedule_filter_model ScheduleFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ScheduleResponse]

A list of schedules.

Source code in src/zenml/zen_stores/zen_store_interface.py
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
@abstractmethod
def list_schedules(
    self,
    schedule_filter_model: ScheduleFilter,
    hydrate: bool = False,
) -> Page[ScheduleResponse]:
    """List all schedules.

    Args:
        schedule_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of schedules.
    """
list_secrets(secret_filter_model: SecretFilter, hydrate: bool = False) -> Page[SecretResponse] abstractmethod

List all secrets matching the given filter criteria.

Note that returned secrets do not include any secret values. To fetch the secret values, use get_secret.

Parameters:

Name Type Description Default
secret_filter_model SecretFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[SecretResponse]

A list of all secrets matching the filter criteria, with pagination

Page[SecretResponse]

information and sorted according to the filter criteria. The

Page[SecretResponse]

returned secrets do not include any secret values, only metadata. To

Page[SecretResponse]

fetch the secret values, use get_secret individually with each

Page[SecretResponse]

secret.

Source code in src/zenml/zen_stores/zen_store_interface.py
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
@abstractmethod
def list_secrets(
    self, secret_filter_model: SecretFilter, hydrate: bool = False
) -> Page[SecretResponse]:
    """List all secrets matching the given filter criteria.

    Note that returned secrets do not include any secret values. To fetch
    the secret values, use `get_secret`.

    Args:
        secret_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all secrets matching the filter criteria, with pagination
        information and sorted according to the filter criteria. The
        returned secrets do not include any secret values, only metadata. To
        fetch the secret values, use `get_secret` individually with each
        secret.
    """
list_service_accounts(filter_model: ServiceAccountFilter, hydrate: bool = False) -> Page[ServiceAccountResponse] abstractmethod

List all service accounts.

Parameters:

Name Type Description Default
filter_model ServiceAccountFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ServiceAccountResponse]

A list of filtered service accounts.

Source code in src/zenml/zen_stores/zen_store_interface.py
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
@abstractmethod
def list_service_accounts(
    self,
    filter_model: ServiceAccountFilter,
    hydrate: bool = False,
) -> Page[ServiceAccountResponse]:
    """List all service accounts.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of filtered service accounts.
    """
list_service_connector_resources(filter_model: ServiceConnectorFilter) -> List[ServiceConnectorResourcesModel] abstractmethod

List resources that can be accessed by service connectors.

Parameters:

Name Type Description Default
filter_model ServiceConnectorFilter

The filter model to use when fetching service connectors.

required

Returns:

Type Description
List[ServiceConnectorResourcesModel]

The matching list of resources that available service

List[ServiceConnectorResourcesModel]

connectors have access to.

Source code in src/zenml/zen_stores/zen_store_interface.py
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
@abstractmethod
def list_service_connector_resources(
    self,
    filter_model: ServiceConnectorFilter,
) -> List[ServiceConnectorResourcesModel]:
    """List resources that can be accessed by service connectors.

    Args:
        filter_model: The filter model to use when fetching service
            connectors.

    Returns:
        The matching list of resources that available service
        connectors have access to.
    """
list_service_connector_types(connector_type: Optional[str] = None, resource_type: Optional[str] = None, auth_method: Optional[str] = None) -> List[ServiceConnectorTypeModel] abstractmethod

Get a list of service connector types.

Parameters:

Name Type Description Default
connector_type Optional[str]

Filter by connector type.

None
resource_type Optional[str]

Filter by resource type.

None
auth_method Optional[str]

Filter by authentication method.

None

Returns:

Type Description
List[ServiceConnectorTypeModel]

List of service connector types.

Source code in src/zenml/zen_stores/zen_store_interface.py
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
@abstractmethod
def list_service_connector_types(
    self,
    connector_type: Optional[str] = None,
    resource_type: Optional[str] = None,
    auth_method: Optional[str] = None,
) -> List[ServiceConnectorTypeModel]:
    """Get a list of service connector types.

    Args:
        connector_type: Filter by connector type.
        resource_type: Filter by resource type.
        auth_method: Filter by authentication method.

    Returns:
        List of service connector types.
    """
list_service_connectors(filter_model: ServiceConnectorFilter, hydrate: bool = False) -> Page[ServiceConnectorResponse] abstractmethod

List all service connectors.

Parameters:

Name Type Description Default
filter_model ServiceConnectorFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ServiceConnectorResponse]

A page of all service connectors.

Source code in src/zenml/zen_stores/zen_store_interface.py
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
@abstractmethod
def list_service_connectors(
    self,
    filter_model: ServiceConnectorFilter,
    hydrate: bool = False,
) -> Page[ServiceConnectorResponse]:
    """List all service connectors.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all service connectors.
    """
list_services(filter_model: ServiceFilter, hydrate: bool = False) -> Page[ServiceResponse] abstractmethod

List all services matching the given filter criteria.

Parameters:

Name Type Description Default
filter_model ServiceFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ServiceResponse]

A list of all services matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
@abstractmethod
def list_services(
    self, filter_model: ServiceFilter, hydrate: bool = False
) -> Page[ServiceResponse]:
    """List all services matching the given filter criteria.

    Args:
        filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all services matching the filter criteria.
    """
list_stack_components(component_filter_model: ComponentFilter, hydrate: bool = False) -> Page[ComponentResponse] abstractmethod

List all stack components matching the given filter criteria.

Parameters:

Name Type Description Default
component_filter_model ComponentFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ComponentResponse]

A list of all stack components matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
@abstractmethod
def list_stack_components(
    self,
    component_filter_model: ComponentFilter,
    hydrate: bool = False,
) -> Page[ComponentResponse]:
    """List all stack components matching the given filter criteria.

    Args:
        component_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all stack components matching the filter criteria.
    """
list_stacks(stack_filter_model: StackFilter, hydrate: bool = False) -> Page[StackResponse] abstractmethod

List all stacks matching the given filter criteria.

Parameters:

Name Type Description Default
stack_filter_model StackFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[StackResponse]

A list of all stacks matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
@abstractmethod
def list_stacks(
    self,
    stack_filter_model: StackFilter,
    hydrate: bool = False,
) -> Page[StackResponse]:
    """List all stacks matching the given filter criteria.

    Args:
        stack_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all stacks matching the filter criteria.
    """
list_tags(tag_filter_model: TagFilter, hydrate: bool = False) -> Page[TagResponse] abstractmethod

Get all tags by filter.

Parameters:

Name Type Description Default
tag_filter_model TagFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[TagResponse]

A page of all tags.

Source code in src/zenml/zen_stores/zen_store_interface.py
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
@abstractmethod
def list_tags(
    self,
    tag_filter_model: TagFilter,
    hydrate: bool = False,
) -> Page[TagResponse]:
    """Get all tags by filter.

    Args:
        tag_filter_model: All filter parameters including pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all tags.
    """
list_trigger_executions(trigger_execution_filter_model: TriggerExecutionFilter, hydrate: bool = False) -> Page[TriggerExecutionResponse] abstractmethod

List all trigger executions matching the given filter criteria.

Parameters:

Name Type Description Default
trigger_execution_filter_model TriggerExecutionFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[TriggerExecutionResponse]

A list of all trigger executions matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
@abstractmethod
def list_trigger_executions(
    self,
    trigger_execution_filter_model: TriggerExecutionFilter,
    hydrate: bool = False,
) -> Page[TriggerExecutionResponse]:
    """List all trigger executions matching the given filter criteria.

    Args:
        trigger_execution_filter_model: All filter parameters including
            pagination params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all trigger executions matching the filter criteria.
    """
list_triggers(trigger_filter_model: TriggerFilter, hydrate: bool = False) -> Page[TriggerResponse] abstractmethod

List all triggers matching the given filter criteria.

Parameters:

Name Type Description Default
trigger_filter_model TriggerFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[TriggerResponse]

A list of all triggers matching the filter criteria.

Source code in src/zenml/zen_stores/zen_store_interface.py
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
@abstractmethod
def list_triggers(
    self,
    trigger_filter_model: TriggerFilter,
    hydrate: bool = False,
) -> Page[TriggerResponse]:
    """List all triggers matching the given filter criteria.

    Args:
        trigger_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all triggers matching the filter criteria.
    """
list_users(user_filter_model: UserFilter, hydrate: bool = False) -> Page[UserResponse] abstractmethod

List all users.

Parameters:

Name Type Description Default
user_filter_model UserFilter

All filter parameters including pagination params.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[UserResponse]

A list of all users.

Source code in src/zenml/zen_stores/zen_store_interface.py
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
@abstractmethod
def list_users(
    self,
    user_filter_model: UserFilter,
    hydrate: bool = False,
) -> Page[UserResponse]:
    """List all users.

    Args:
        user_filter_model: All filter parameters including pagination
            params.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all users.
    """
prune_artifact_versions(project_name_or_id: Union[str, UUID], only_versions: bool = True) -> None abstractmethod

Prunes unused artifact versions and their artifacts.

Parameters:

Name Type Description Default
project_name_or_id Union[str, UUID]

The project name or ID to prune artifact versions for.

required
only_versions bool

Only delete artifact versions, keeping artifacts

True
Source code in src/zenml/zen_stores/zen_store_interface.py
741
742
743
744
745
746
747
748
749
750
751
752
753
@abstractmethod
def prune_artifact_versions(
    self,
    project_name_or_id: Union[str, UUID],
    only_versions: bool = True,
) -> None:
    """Prunes unused artifact versions and their artifacts.

    Args:
        project_name_or_id: The project name or ID to prune artifact
            versions for.
        only_versions: Only delete artifact versions, keeping artifacts
    """
restore_secrets(ignore_errors: bool = False, delete_secrets: bool = False) -> None abstractmethod

Restore all secrets from the configured backup secrets store.

Parameters:

Name Type Description Default
ignore_errors bool

Whether to ignore individual errors during the restore process and attempt to restore all secrets.

False
delete_secrets bool

Whether to delete the secrets that have been successfully restored from the backup secrets store. Setting this flag effectively moves all secrets from the backup secrets store to the primary secrets store.

False

Raises:

Type Description
BackupSecretsStoreNotConfiguredError

if no backup secrets store is configured.

Source code in src/zenml/zen_stores/zen_store_interface.py
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
@abstractmethod
def restore_secrets(
    self, ignore_errors: bool = False, delete_secrets: bool = False
) -> None:
    """Restore all secrets from the configured backup secrets store.

    Args:
        ignore_errors: Whether to ignore individual errors during the
            restore process and attempt to restore all secrets.
        delete_secrets: Whether to delete the secrets that have been
            successfully restored from the backup secrets store. Setting
            this flag effectively moves all secrets from the backup secrets
            store to the primary secrets store.

    Raises:
        BackupSecretsStoreNotConfiguredError: if no backup secrets store is
            configured.
    """
rotate_api_key(service_account_id: UUID, api_key_name_or_id: Union[str, UUID], rotate_request: APIKeyRotateRequest) -> APIKeyResponse abstractmethod

Rotate an API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to rotate the API key.

required
api_key_name_or_id Union[str, UUID]

The name or ID of the API key to rotate.

required
rotate_request APIKeyRotateRequest

The rotate request on the API key.

required

Returns:

Type Description
APIKeyResponse

The updated API key.

Raises:

Type Description
KeyError

if an API key with the given name or ID is not configured for the given service account.

Source code in src/zenml/zen_stores/zen_store_interface.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
@abstractmethod
def rotate_api_key(
    self,
    service_account_id: UUID,
    api_key_name_or_id: Union[str, UUID],
    rotate_request: APIKeyRotateRequest,
) -> APIKeyResponse:
    """Rotate an API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to
            rotate the API key.
        api_key_name_or_id: The name or ID of the API key to rotate.
        rotate_request: The rotate request on the API key.

    Returns:
        The updated API key.

    Raises:
        KeyError: if an API key with the given name or ID is not configured
            for the given service account.
    """
run_template(template_id: UUID, run_configuration: Optional[PipelineRunConfiguration] = None) -> PipelineRunResponse abstractmethod

Run a template.

Parameters:

Name Type Description Default
template_id UUID

The ID of the template to run.

required
run_configuration Optional[PipelineRunConfiguration]

Configuration for the run.

None

Returns:

Type Description
PipelineRunResponse

Model of the pipeline run.

Source code in src/zenml/zen_stores/zen_store_interface.py
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
@abstractmethod
def run_template(
    self,
    template_id: UUID,
    run_configuration: Optional[PipelineRunConfiguration] = None,
) -> PipelineRunResponse:
    """Run a template.

    Args:
        template_id: The ID of the template to run.
        run_configuration: Configuration for the run.

    Returns:
        Model of the pipeline run.
    """
update_action(action_id: UUID, action_update: ActionUpdate) -> ActionResponse abstractmethod

Update an existing action.

Parameters:

Name Type Description Default
action_id UUID

The ID of the action to update.

required
action_update ActionUpdate

The update to be applied to the action.

required

Returns:

Type Description
ActionResponse

The updated action.

Raises:

Type Description
KeyError

If the action doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
@abstractmethod
def update_action(
    self,
    action_id: UUID,
    action_update: ActionUpdate,
) -> ActionResponse:
    """Update an existing action.

    Args:
        action_id: The ID of the action to update.
        action_update: The update to be applied to the action.

    Returns:
        The updated action.

    Raises:
        KeyError: If the action doesn't exist.
    """
update_api_key(service_account_id: UUID, api_key_name_or_id: Union[str, UUID], api_key_update: APIKeyUpdate) -> APIKeyResponse abstractmethod

Update an API key for a service account.

Parameters:

Name Type Description Default
service_account_id UUID

The ID of the service account for which to update the API key.

required
api_key_name_or_id Union[str, UUID]

The name or ID of the API key to update.

required
api_key_update APIKeyUpdate

The update request on the API key.

required

Returns:

Type Description
APIKeyResponse

The updated API key.

Raises:

Type Description
KeyError

if an API key with the given name or ID is not configured for the given service account.

EntityExistsError

if the API key update would result in a name conflict with an existing API key for the same service account.

Source code in src/zenml/zen_stores/zen_store_interface.py
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
@abstractmethod
def update_api_key(
    self,
    service_account_id: UUID,
    api_key_name_or_id: Union[str, UUID],
    api_key_update: APIKeyUpdate,
) -> APIKeyResponse:
    """Update an API key for a service account.

    Args:
        service_account_id: The ID of the service account for which to update
            the API key.
        api_key_name_or_id: The name or ID of the API key to update.
        api_key_update: The update request on the API key.

    Returns:
        The updated API key.

    Raises:
        KeyError: if an API key with the given name or ID is not configured
            for the given service account.
        EntityExistsError: if the API key update would result in a name
            conflict with an existing API key for the same service account.
    """
update_artifact(artifact_id: UUID, artifact_update: ArtifactUpdate) -> ArtifactResponse abstractmethod

Updates an artifact.

Parameters:

Name Type Description Default
artifact_id UUID

The ID of the artifact to update.

required
artifact_update ArtifactUpdate

The update to be applied to the artifact.

required

Returns:

Type Description
ArtifactResponse

The updated artifact.

Raises:

Type Description
KeyError

if the artifact doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
@abstractmethod
def update_artifact(
    self, artifact_id: UUID, artifact_update: ArtifactUpdate
) -> ArtifactResponse:
    """Updates an artifact.

    Args:
        artifact_id: The ID of the artifact to update.
        artifact_update: The update to be applied to the artifact.

    Returns:
        The updated artifact.

    Raises:
        KeyError: if the artifact doesn't exist.
    """
update_artifact_version(artifact_version_id: UUID, artifact_version_update: ArtifactVersionUpdate) -> ArtifactVersionResponse abstractmethod

Updates an artifact version.

Parameters:

Name Type Description Default
artifact_version_id UUID

The ID of the artifact version to update.

required
artifact_version_update ArtifactVersionUpdate

The update to be applied to the artifact version.

required

Returns:

Type Description
ArtifactVersionResponse

The updated artifact version.

Raises:

Type Description
KeyError

if the artifact version doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
@abstractmethod
def update_artifact_version(
    self,
    artifact_version_id: UUID,
    artifact_version_update: ArtifactVersionUpdate,
) -> ArtifactVersionResponse:
    """Updates an artifact version.

    Args:
        artifact_version_id: The ID of the artifact version to update.
        artifact_version_update: The update to be applied to the artifact
            version.

    Returns:
        The updated artifact version.

    Raises:
        KeyError: if the artifact version doesn't exist.
    """
update_authorized_device(device_id: UUID, update: OAuthDeviceUpdate) -> OAuthDeviceResponse abstractmethod

Updates an existing OAuth 2.0 authorized device for internal use.

Parameters:

Name Type Description Default
device_id UUID

The ID of the device to update.

required
update OAuthDeviceUpdate

The update to be applied to the device.

required

Returns:

Type Description
OAuthDeviceResponse

The updated OAuth 2.0 authorized device.

Raises:

Type Description
KeyError

If no device with the given ID exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
@abstractmethod
def update_authorized_device(
    self, device_id: UUID, update: OAuthDeviceUpdate
) -> OAuthDeviceResponse:
    """Updates an existing OAuth 2.0 authorized device for internal use.

    Args:
        device_id: The ID of the device to update.
        update: The update to be applied to the device.

    Returns:
        The updated OAuth 2.0 authorized device.

    Raises:
        KeyError: If no device with the given ID exists.
    """
update_code_repository(code_repository_id: UUID, update: CodeRepositoryUpdate) -> CodeRepositoryResponse abstractmethod

Updates an existing code repository.

Parameters:

Name Type Description Default
code_repository_id UUID

The ID of the code repository to update.

required
update CodeRepositoryUpdate

The update to be applied to the code repository.

required

Returns:

Type Description
CodeRepositoryResponse

The updated code repository.

Raises:

Type Description
KeyError

If no code repository with the given name exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
@abstractmethod
def update_code_repository(
    self, code_repository_id: UUID, update: CodeRepositoryUpdate
) -> CodeRepositoryResponse:
    """Updates an existing code repository.

    Args:
        code_repository_id: The ID of the code repository to update.
        update: The update to be applied to the code repository.

    Returns:
        The updated code repository.

    Raises:
        KeyError: If no code repository with the given name exists.
    """
update_event_source(event_source_id: UUID, event_source_update: EventSourceUpdate) -> EventSourceResponse abstractmethod

Update an existing event_source.

Parameters:

Name Type Description Default
event_source_id UUID

The ID of the event_source to update.

required
event_source_update EventSourceUpdate

The update to be applied to the event_source.

required

Returns:

Type Description
EventSourceResponse

The updated event_source.

Raises:

Type Description
KeyError

if the event_source doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
@abstractmethod
def update_event_source(
    self,
    event_source_id: UUID,
    event_source_update: EventSourceUpdate,
) -> EventSourceResponse:
    """Update an existing event_source.

    Args:
        event_source_id: The ID of the event_source to update.
        event_source_update: The update to be applied to the event_source.

    Returns:
        The updated event_source.

    Raises:
        KeyError: if the event_source doesn't exist.
    """
update_flavor(flavor_id: UUID, flavor_update: FlavorUpdate) -> FlavorResponse abstractmethod

Updates an existing user.

Parameters:

Name Type Description Default
flavor_id UUID

The id of the flavor to update.

required
flavor_update FlavorUpdate

The update to be applied to the flavor.

required

Returns:

Type Description
FlavorResponse

The updated flavor.

Source code in src/zenml/zen_stores/zen_store_interface.py
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
@abstractmethod
def update_flavor(
    self, flavor_id: UUID, flavor_update: FlavorUpdate
) -> FlavorResponse:
    """Updates an existing user.

    Args:
        flavor_id: The id of the flavor to update.
        flavor_update: The update to be applied to the flavor.

    Returns:
        The updated flavor.
    """
update_model(model_id: UUID, model_update: ModelUpdate) -> ModelResponse abstractmethod

Updates an existing model.

Parameters:

Name Type Description Default
model_id UUID

UUID of the model to be updated.

required
model_update ModelUpdate

the Model to be updated.

required

Returns:

Type Description
ModelResponse

The updated model.

Source code in src/zenml/zen_stores/zen_store_interface.py
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
@abstractmethod
def update_model(
    self,
    model_id: UUID,
    model_update: ModelUpdate,
) -> ModelResponse:
    """Updates an existing model.

    Args:
        model_id: UUID of the model to be updated.
        model_update: the Model to be updated.

    Returns:
        The updated model.
    """
update_model_version(model_version_id: UUID, model_version_update_model: ModelVersionUpdate) -> ModelVersionResponse abstractmethod

Get all model versions by filter.

Parameters:

Name Type Description Default
model_version_id UUID

The ID of model version to be updated.

required
model_version_update_model ModelVersionUpdate

The model version to be updated.

required

Returns:

Type Description
ModelVersionResponse

An updated model version.

Raises:

Type Description
KeyError

If the model version not found

RuntimeError

If there is a model version with target stage, but force flag is off

Source code in src/zenml/zen_stores/zen_store_interface.py
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
@abstractmethod
def update_model_version(
    self,
    model_version_id: UUID,
    model_version_update_model: ModelVersionUpdate,
) -> ModelVersionResponse:
    """Get all model versions by filter.

    Args:
        model_version_id: The ID of model version to be updated.
        model_version_update_model: The model version to be updated.

    Returns:
        An updated model version.

    Raises:
        KeyError: If the model version not found
        RuntimeError: If there is a model version with target stage,
            but `force` flag is off
    """
update_pipeline(pipeline_id: UUID, pipeline_update: PipelineUpdate) -> PipelineResponse abstractmethod

Updates a pipeline.

Parameters:

Name Type Description Default
pipeline_id UUID

The ID of the pipeline to be updated.

required
pipeline_update PipelineUpdate

The update to be applied.

required

Returns:

Type Description
PipelineResponse

The updated pipeline.

Raises:

Type Description
KeyError

if the pipeline doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
@abstractmethod
def update_pipeline(
    self,
    pipeline_id: UUID,
    pipeline_update: PipelineUpdate,
) -> PipelineResponse:
    """Updates a pipeline.

    Args:
        pipeline_id: The ID of the pipeline to be updated.
        pipeline_update: The update to be applied.

    Returns:
        The updated pipeline.

    Raises:
        KeyError: if the pipeline doesn't exist.
    """
update_project(project_id: UUID, project_update: ProjectUpdate) -> ProjectResponse abstractmethod

Update an existing project.

Parameters:

Name Type Description Default
project_id UUID

The ID of the project to be updated.

required
project_update ProjectUpdate

The update to be applied to the project.

required

Returns:

Type Description
ProjectResponse

The updated project.

Raises:

Type Description
KeyError

if the project does not exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
@abstractmethod
def update_project(
    self, project_id: UUID, project_update: ProjectUpdate
) -> ProjectResponse:
    """Update an existing project.

    Args:
        project_id: The ID of the project to be updated.
        project_update: The update to be applied to the project.

    Returns:
        The updated project.

    Raises:
        KeyError: if the project does not exist.
    """
update_run(run_id: UUID, run_update: PipelineRunUpdate) -> PipelineRunResponse abstractmethod

Updates a pipeline run.

Parameters:

Name Type Description Default
run_id UUID

The ID of the pipeline run to update.

required
run_update PipelineRunUpdate

The update to be applied to the pipeline run.

required

Returns:

Type Description
PipelineRunResponse

The updated pipeline run.

Raises:

Type Description
KeyError

if the pipeline run doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
@abstractmethod
def update_run(
    self, run_id: UUID, run_update: PipelineRunUpdate
) -> PipelineRunResponse:
    """Updates a pipeline run.

    Args:
        run_id: The ID of the pipeline run to update.
        run_update: The update to be applied to the pipeline run.

    Returns:
        The updated pipeline run.

    Raises:
        KeyError: if the pipeline run doesn't exist.
    """
update_run_step(step_run_id: UUID, step_run_update: StepRunUpdate) -> StepRunResponse abstractmethod

Updates a step run.

Parameters:

Name Type Description Default
step_run_id UUID

The ID of the step to update.

required
step_run_update StepRunUpdate

The update to be applied to the step.

required

Returns:

Type Description
StepRunResponse

The updated step run.

Raises:

Type Description
KeyError

if the step run doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
@abstractmethod
def update_run_step(
    self,
    step_run_id: UUID,
    step_run_update: StepRunUpdate,
) -> StepRunResponse:
    """Updates a step run.

    Args:
        step_run_id: The ID of the step to update.
        step_run_update: The update to be applied to the step.

    Returns:
        The updated step run.

    Raises:
        KeyError: if the step run doesn't exist.
    """
update_run_template(template_id: UUID, template_update: RunTemplateUpdate) -> RunTemplateResponse abstractmethod

Updates a run template.

Parameters:

Name Type Description Default
template_id UUID

The ID of the template to update.

required
template_update RunTemplateUpdate

The update to apply.

required

Returns:

Type Description
RunTemplateResponse

The updated template.

Raises:

Type Description
KeyError

If the template does not exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
@abstractmethod
def update_run_template(
    self,
    template_id: UUID,
    template_update: RunTemplateUpdate,
) -> RunTemplateResponse:
    """Updates a run template.

    Args:
        template_id: The ID of the template to update.
        template_update: The update to apply.

    Returns:
        The updated template.

    Raises:
        KeyError: If the template does not exist.
    """
update_schedule(schedule_id: UUID, schedule_update: ScheduleUpdate) -> ScheduleResponse abstractmethod

Updates a schedule.

Parameters:

Name Type Description Default
schedule_id UUID

The ID of the schedule to be updated.

required
schedule_update ScheduleUpdate

The update to be applied.

required

Returns:

Type Description
ScheduleResponse

The updated schedule.

Raises:

Type Description
KeyError

if the schedule doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
@abstractmethod
def update_schedule(
    self,
    schedule_id: UUID,
    schedule_update: ScheduleUpdate,
) -> ScheduleResponse:
    """Updates a schedule.

    Args:
        schedule_id: The ID of the schedule to be updated.
        schedule_update: The update to be applied.

    Returns:
        The updated schedule.

    Raises:
        KeyError: if the schedule doesn't exist.
    """
update_secret(secret_id: UUID, secret_update: SecretUpdate) -> SecretResponse abstractmethod

Updates a secret.

Secret values that are specified as None in the update that are present in the existing secret are removed from the existing secret. Values that are present in both secrets are overwritten. All other values in both the existing secret and the update are kept (merged).

If the update includes a change of name or scope, the scoping rules enforced in the secrets store are used to validate the update:

  • only one private secret with the given name can exist.
  • only one public secret with the given name can exist.

Parameters:

Name Type Description Default
secret_id UUID

The ID of the secret to be updated.

required
secret_update SecretUpdate

The update to be applied.

required

Returns:

Type Description
SecretResponse

The updated secret.

Raises:

Type Description
KeyError

if the secret doesn't exist.

EntityExistsError

If a secret with the same name already exists in the same scope.

Source code in src/zenml/zen_stores/zen_store_interface.py
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
@abstractmethod
def update_secret(
    self,
    secret_id: UUID,
    secret_update: SecretUpdate,
) -> SecretResponse:
    """Updates a secret.

    Secret values that are specified as `None` in the update that are
    present in the existing secret are removed from the existing secret.
    Values that are present in both secrets are overwritten. All other
    values in both the existing secret and the update are kept (merged).

    If the update includes a change of name or scope, the scoping rules
    enforced in the secrets store are used to validate the update:

      - only one private secret with the given name can exist.
      - only one public secret with the given name can exist.

    Args:
        secret_id: The ID of the secret to be updated.
        secret_update: The update to be applied.

    Returns:
        The updated secret.

    Raises:
        KeyError: if the secret doesn't exist.
        EntityExistsError: If a secret with the same name already exists in
            the same scope.
    """
update_server_settings(settings_update: ServerSettingsUpdate) -> ServerSettingsResponse abstractmethod

Update the server settings.

Parameters:

Name Type Description Default
settings_update ServerSettingsUpdate

The server settings update.

required

Returns:

Type Description
ServerSettingsResponse

The updated server settings.

Source code in src/zenml/zen_stores/zen_store_interface.py
260
261
262
263
264
265
266
267
268
269
270
271
@abstractmethod
def update_server_settings(
    self, settings_update: ServerSettingsUpdate
) -> ServerSettingsResponse:
    """Update the server settings.

    Args:
        settings_update: The server settings update.

    Returns:
        The updated server settings.
    """
update_service(service_id: UUID, update: ServiceUpdate) -> ServiceResponse abstractmethod

Update an existing service.

Parameters:

Name Type Description Default
service_id UUID

The ID of the service to update.

required
update ServiceUpdate

The update to be applied to the service.

required

Returns:

Type Description
ServiceResponse

The updated service.

Raises:

Type Description
KeyError

if the service doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
@abstractmethod
def update_service(
    self, service_id: UUID, update: ServiceUpdate
) -> ServiceResponse:
    """Update an existing service.

    Args:
        service_id: The ID of the service to update.
        update: The update to be applied to the service.

    Returns:
        The updated service.

    Raises:
        KeyError: if the service doesn't exist.
    """
update_service_account(service_account_name_or_id: Union[str, UUID], service_account_update: ServiceAccountUpdate) -> ServiceAccountResponse abstractmethod

Updates an existing service account.

Parameters:

Name Type Description Default
service_account_name_or_id Union[str, UUID]

The name or the ID of the service account to update.

required
service_account_update ServiceAccountUpdate

The update to be applied to the service account.

required

Returns:

Type Description
ServiceAccountResponse

The updated service account.

Raises:

Type Description
KeyError

If no service account with the given name exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
@abstractmethod
def update_service_account(
    self,
    service_account_name_or_id: Union[str, UUID],
    service_account_update: ServiceAccountUpdate,
) -> ServiceAccountResponse:
    """Updates an existing service account.

    Args:
        service_account_name_or_id: The name or the ID of the service
            account to update.
        service_account_update: The update to be applied to the service
            account.

    Returns:
        The updated service account.

    Raises:
        KeyError: If no service account with the given name exists.
    """
update_service_connector(service_connector_id: UUID, update: ServiceConnectorUpdate) -> ServiceConnectorResponse abstractmethod

Updates an existing service connector.

The update model contains the fields to be updated. If a field value is set to None in the model, the field is not updated, but there are special rules concerning some fields:

  • the configuration and secrets fields together represent a full valid configuration update, not just a partial update. If either is set (i.e. not None) in the update, their values are merged together and will replace the existing configuration and secrets values.
  • the resource_id field value is also a full replacement value: if set to None, the resource ID is removed from the service connector.
  • the expiration_seconds field value is also a full replacement value: if set to None, the expiration is removed from the service connector.
  • the secret_id field value in the update is ignored, given that secrets are managed internally by the ZenML store.
  • the labels field is also a full labels update: if set (i.e. not None), all existing labels are removed and replaced by the new labels in the update.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the service connector to update.

required
update ServiceConnectorUpdate

The update to be applied to the service connector.

required

Returns:

Type Description
ServiceConnectorResponse

The updated service connector.

Raises:

Type Description
KeyError

If no service connector with the given name exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
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
@abstractmethod
def update_service_connector(
    self, service_connector_id: UUID, update: ServiceConnectorUpdate
) -> ServiceConnectorResponse:
    """Updates an existing service connector.

    The update model contains the fields to be updated. If a field value is
    set to None in the model, the field is not updated, but there are
    special rules concerning some fields:

    * the `configuration` and `secrets` fields together represent a full
    valid configuration update, not just a partial update. If either is
    set (i.e. not None) in the update, their values are merged together and
    will replace the existing configuration and secrets values.
    * the `resource_id` field value is also a full replacement value: if set
    to `None`, the resource ID is removed from the service connector.
    * the `expiration_seconds` field value is also a full replacement value:
    if set to `None`, the expiration is removed from the service connector.
    * the `secret_id` field value in the update is ignored, given that
    secrets are managed internally by the ZenML store.
    * the `labels` field is also a full labels update: if set (i.e. not
    `None`), all existing labels are removed and replaced by the new labels
    in the update.

    Args:
        service_connector_id: The ID of the service connector to update.
        update: The update to be applied to the service connector.

    Returns:
        The updated service connector.

    Raises:
        KeyError: If no service connector with the given name exists.
    """
update_stack(stack_id: UUID, stack_update: StackUpdate) -> StackResponse abstractmethod

Update a stack.

Parameters:

Name Type Description Default
stack_id UUID

The ID of the stack update.

required
stack_update StackUpdate

The update request on the stack.

required

Returns:

Type Description
StackResponse

The updated stack.

Raises:

Type Description
KeyError

if the stack doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
@abstractmethod
def update_stack(
    self, stack_id: UUID, stack_update: StackUpdate
) -> StackResponse:
    """Update a stack.

    Args:
        stack_id: The ID of the stack update.
        stack_update: The update request on the stack.

    Returns:
        The updated stack.

    Raises:
        KeyError: if the stack doesn't exist.
    """
update_stack_component(component_id: UUID, component_update: ComponentUpdate) -> ComponentResponse abstractmethod

Update an existing stack component.

Parameters:

Name Type Description Default
component_id UUID

The ID of the stack component to update.

required
component_update ComponentUpdate

The update to be applied to the stack component.

required

Returns:

Type Description
ComponentResponse

The updated stack component.

Raises:

Type Description
KeyError

if the stack component doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
@abstractmethod
def update_stack_component(
    self,
    component_id: UUID,
    component_update: ComponentUpdate,
) -> ComponentResponse:
    """Update an existing stack component.

    Args:
        component_id: The ID of the stack component to update.
        component_update: The update to be applied to the stack component.

    Returns:
        The updated stack component.

    Raises:
        KeyError: if the stack component doesn't exist.
    """
update_tag(tag_name_or_id: Union[str, UUID], tag_update_model: TagUpdate) -> TagResponse abstractmethod

Update tag.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

name or id of the tag to be updated.

required
tag_update_model TagUpdate

Tag to use for the update.

required

Returns:

Type Description
TagResponse

An updated tag.

Raises:

Type Description
KeyError

If the tag is not found

Source code in src/zenml/zen_stores/zen_store_interface.py
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
@abstractmethod
def update_tag(
    self,
    tag_name_or_id: Union[str, UUID],
    tag_update_model: TagUpdate,
) -> TagResponse:
    """Update tag.

    Args:
        tag_name_or_id: name or id of the tag to be updated.
        tag_update_model: Tag to use for the update.

    Returns:
        An updated tag.

    Raises:
        KeyError: If the tag is not found
    """
update_trigger(trigger_id: UUID, trigger_update: TriggerUpdate) -> TriggerResponse abstractmethod

Update an existing trigger.

Parameters:

Name Type Description Default
trigger_id UUID

The ID of the trigger to update.

required
trigger_update TriggerUpdate

The update to be applied to the trigger.

required

Returns:

Type Description
TriggerResponse

The updated trigger.

Raises:

Type Description
KeyError

if the trigger doesn't exist.

Source code in src/zenml/zen_stores/zen_store_interface.py
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
@abstractmethod
def update_trigger(
    self,
    trigger_id: UUID,
    trigger_update: TriggerUpdate,
) -> TriggerResponse:
    """Update an existing trigger.

    Args:
        trigger_id: The ID of the trigger to update.
        trigger_update: The update to be applied to the trigger.

    Returns:
        The updated trigger.

    Raises:
        KeyError: if the trigger doesn't exist.
    """
update_user(user_id: UUID, user_update: UserUpdate) -> UserResponse abstractmethod

Updates an existing user.

Parameters:

Name Type Description Default
user_id UUID

The id of the user to update.

required
user_update UserUpdate

The update to be applied to the user.

required

Returns:

Type Description
UserResponse

The updated user.

Raises:

Type Description
KeyError

If no user with the given name exists.

Source code in src/zenml/zen_stores/zen_store_interface.py
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
@abstractmethod
def update_user(
    self, user_id: UUID, user_update: UserUpdate
) -> UserResponse:
    """Updates an existing user.

    Args:
        user_id: The id of the user to update.
        user_update: The update to be applied to the user.

    Returns:
        The updated user.

    Raises:
        KeyError: If no user with the given name exists.
    """
verify_service_connector(service_connector_id: UUID, resource_type: Optional[str] = None, resource_id: Optional[str] = None, list_resources: bool = True) -> ServiceConnectorResourcesModel abstractmethod

Verifies if a service connector instance has access to one or more resources.

Parameters:

Name Type Description Default
service_connector_id UUID

The ID of the service connector to verify.

required
resource_type Optional[str]

The type of resource to verify access to.

None
resource_id Optional[str]

The ID of the resource to verify access to.

None
list_resources bool

If True, the list of all resources accessible through the service connector and matching the supplied resource type and ID are returned.

True

Returns:

Type Description
ServiceConnectorResourcesModel

The list of resources that the service connector has access to,

ServiceConnectorResourcesModel

scoped to the supplied resource type and ID, if provided.

Raises:

Type Description
KeyError

If no service connector with the given name exists.

NotImplementError

If the service connector cannot be verified e.g. due to missing package dependencies.

Source code in src/zenml/zen_stores/zen_store_interface.py
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
@abstractmethod
def verify_service_connector(
    self,
    service_connector_id: UUID,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    list_resources: bool = True,
) -> ServiceConnectorResourcesModel:
    """Verifies if a service connector instance has access to one or more resources.

    Args:
        service_connector_id: The ID of the service connector to verify.
        resource_type: The type of resource to verify access to.
        resource_id: The ID of the resource to verify access to.
        list_resources: If True, the list of all resources accessible
            through the service connector and matching the supplied resource
            type and ID are returned.

    Returns:
        The list of resources that the service connector has access to,
        scoped to the supplied resource type and ID, if provided.

    Raises:
        KeyError: If no service connector with the given name exists.
        NotImplementError: If the service connector cannot be verified
            e.g. due to missing package dependencies.
    """
verify_service_connector_config(service_connector: ServiceConnectorRequest, list_resources: bool = True) -> ServiceConnectorResourcesModel abstractmethod

Verifies if a service connector configuration has access to resources.

Parameters:

Name Type Description Default
service_connector ServiceConnectorRequest

The service connector configuration to verify.

required
list_resources bool

If True, the list of all resources accessible through the service connector is returned.

True

Returns:

Type Description
ServiceConnectorResourcesModel

The list of resources that the service connector configuration has

ServiceConnectorResourcesModel

access to.

Raises:

Type Description
NotImplementError

If the service connector cannot be verified on the store e.g. due to missing package dependencies.

Source code in src/zenml/zen_stores/zen_store_interface.py
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
@abstractmethod
def verify_service_connector_config(
    self,
    service_connector: ServiceConnectorRequest,
    list_resources: bool = True,
) -> ServiceConnectorResourcesModel:
    """Verifies if a service connector configuration has access to resources.

    Args:
        service_connector: The service connector configuration to verify.
        list_resources: If True, the list of all resources accessible
            through the service connector is returned.

    Returns:
        The list of resources that the service connector configuration has
        access to.

    Raises:
        NotImplementError: If the service connector cannot be verified
            on the store e.g. due to missing package dependencies.
    """