-
Notifications
You must be signed in to change notification settings - Fork 550
Feature:3963 Step HeartBeat components #4073
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Parent:
Patch filter mflow by stage
Json-Andriopoulos
wants to merge
1
commit into
develop
Choose a base branch
from
feature/3963-step-run-heartbeat
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,178 @@ | ||
| # Copyright (c) ZenML GmbH 2022. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at: | ||
| # | ||
| # https://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express | ||
| # or implied. See the License for the specific language governing | ||
| # permissions and limitations under the License. | ||
| """ZenML Step HeartBeat functionality.""" | ||
|
|
||
| import _thread | ||
| import logging | ||
| import threading | ||
| import time | ||
| from typing import Annotated | ||
| from uuid import UUID | ||
|
|
||
| from pydantic import BaseModel, conint, model_validator | ||
|
|
||
| from zenml.enums import ExecutionStatus | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class StepHeartBeatTerminationException(Exception): | ||
| """Custom exception class for heartbeat termination.""" | ||
|
|
||
| pass | ||
|
|
||
|
|
||
| class StepHeartBeatOptions(BaseModel): | ||
| """Options group for step heartbeat execution.""" | ||
|
|
||
| step_id: UUID | ||
| interval: Annotated[int, conint(ge=10, le=60)] | ||
| name: str | None = None | ||
|
|
||
| @model_validator(mode="after") | ||
| def set_default_name(self) -> "StepHeartBeatOptions": | ||
| """Model validator - set name value if missing. | ||
|
|
||
| Returns: | ||
| The validated step heartbeat options. | ||
| """ | ||
| if not self.name: | ||
| self.name = f"HeartBeatWorker-{self.step_id}" | ||
|
|
||
| return self | ||
|
|
||
|
|
||
| class HeartbeatWorker: | ||
| """Worker class implementing heartbeat polling and remote termination.""" | ||
|
|
||
| def __init__(self, options: StepHeartBeatOptions): | ||
| """Heartbeat worker constructor. | ||
|
|
||
| Args: | ||
| options: Parameter group - polling interval, step id, etc. | ||
| """ | ||
| self.options = options | ||
|
|
||
| self._thread: threading.Thread | None = None | ||
| self._running: bool = False | ||
| self._terminated: bool = ( | ||
| False # one-shot guard to avoid repeated interrupts | ||
| ) | ||
|
|
||
| # properties | ||
|
|
||
| @property | ||
| def interval(self) -> int: | ||
| """Property function for heartbeat interval. | ||
|
|
||
| Returns: | ||
| The heartbeat polling interval value. | ||
| """ | ||
| return self.options.interval | ||
|
|
||
| @property | ||
| def name(self) -> str: | ||
| """Property function for heartbeat worker name. | ||
|
|
||
| Returns: | ||
| The name of the heartbeat worker. | ||
| """ | ||
| return str(self.options.name) | ||
|
|
||
| @property | ||
| def step_id(self) -> UUID: | ||
| """Property function for heartbeat worker step ID. | ||
|
|
||
| Returns: | ||
| The id of the step heartbeat is running for. | ||
| """ | ||
| return self.options.step_id | ||
|
|
||
| # public functions | ||
|
|
||
| def start(self) -> None: | ||
| """Start the heartbeat worker on a background thread.""" | ||
| if self._thread and self._thread.is_alive(): | ||
| logger.info("%s already running; start() is a no-op", self.name) | ||
| return | ||
|
|
||
| self._running = True | ||
| self._terminated = False | ||
| self._thread = threading.Thread( | ||
| target=self._run, name=self.name, daemon=True | ||
| ) | ||
| self._thread.start() | ||
| logger.info( | ||
| "Daemon thread %s started (interval=%s)", self.name, self.interval | ||
| ) | ||
|
|
||
| def stop(self) -> None: | ||
| """Stops the heartbeat worker.""" | ||
| if not self._running: | ||
| return | ||
| self._running = False | ||
| logger.info("%s stop requested", self.name) | ||
|
|
||
| def is_alive(self) -> bool: | ||
| """Liveness of the heartbeat worker thread. | ||
|
|
||
| Returns: | ||
| True if the heartbeat worker thread is alive, False otherwise. | ||
| """ | ||
| t = self._thread | ||
| return bool(t and t.is_alive()) | ||
|
|
||
| def _run(self) -> None: | ||
| logger.info("%s run() loop entered", self.name) | ||
| try: | ||
| while self._running: | ||
| try: | ||
| self._heartbeat() | ||
| except StepHeartBeatTerminationException: | ||
| # One-shot: signal the main thread and stop the loop. | ||
| if not self._terminated: | ||
| self._terminated = True | ||
| logger.info( | ||
| "%s received HeartBeatTerminationException; " | ||
| "interrupting main thread", | ||
| self.name, | ||
| ) | ||
| _thread.interrupt_main() # raises KeyboardInterrupt in main thread | ||
| # Ensure we stop our own loop as well. | ||
| self._running = False | ||
| except Exception: | ||
| # Log-and-continue policy for all other errors. | ||
| logger.exception( | ||
| "%s heartbeat() failed; continuing", self.name | ||
| ) | ||
| # Sleep after each attempt (even after errors, unless stopped). | ||
| if self._running: | ||
| time.sleep(self.interval) | ||
| finally: | ||
| logger.info("%s run() loop exiting", self.name) | ||
|
|
||
| def _heartbeat(self) -> None: | ||
| from zenml.config.global_config import GlobalConfiguration | ||
|
|
||
| store = GlobalConfiguration().zen_store | ||
|
|
||
| response = store.update_step_heartbeat(step_run_id=self.step_id) | ||
|
|
||
| if response.status in { | ||
| ExecutionStatus.STOPPED, | ||
| ExecutionStatus.STOPPING, | ||
| }: | ||
| raise StepHeartBeatTerminationException( | ||
| f"Step {self.step_id} remotely stopped with status {response.status}." | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
30 changes: 30 additions & 0 deletions
30
src/zenml/zen_stores/migrations/versions/a5a17015b681_add_heartbeat_column_for_step_runs.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| """Add heartbeat column for step runs [a5a17015b681]. | ||
|
|
||
| Revision ID: a5a17015b681 | ||
| Revises: 0.90.0 | ||
| Create Date: 2025-10-13 12:24:12.470803 | ||
|
|
||
| """ | ||
|
|
||
| import sqlalchemy as sa | ||
| from alembic import op | ||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision = "a5a17015b681" | ||
| down_revision = "0.90.0" | ||
| branch_labels = None | ||
| depends_on = None | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| """Upgrade database schema and/or data, creating a new revision.""" | ||
| with op.batch_alter_table("step_run", schema=None) as batch_op: | ||
| batch_op.add_column( | ||
| sa.Column("latest_heartbeat", sa.DateTime(), nullable=True) | ||
| ) | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| """Downgrade database schema and/or data back to the previous revision.""" | ||
| with op.batch_alter_table("step_run", schema=None) as batch_op: | ||
| batch_op.drop_column("latest_heartbeat") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
TODO: Improve this. For sure try to capture HTTP errors in more verbose logs to avoid excessive log generation if the error is for instance server raising 500 status code.