Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/dstack/_internal/server/background/pipeline_tasks/fleets.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ def __init__(
workers_num: int = 10,
queue_lower_limit_factor: float = 0.5,
queue_upper_limit_factor: float = 2.0,
min_processing_interval: timedelta = timedelta(seconds=15),
# Most fleets are steady and their processing changes nothing, so the interval is long to
# avoid wasted processing. Changes that need a prompt fleet pass (master election, fleet
# deletion, etc.) set `FleetModel.skip_min_processing_interval` and hint the pipeline.
min_processing_interval: timedelta = timedelta(seconds=60),
lock_timeout: timedelta = timedelta(seconds=20),
heartbeat_trigger: timedelta = timedelta(seconds=10),
*,
Expand Down Expand Up @@ -155,6 +158,7 @@ async def fetch(self, limit: int) -> list[PipelineItem]:
or_(
FleetModel.last_processed_at <= now - self._min_processing_interval,
FleetModel.last_processed_at == FleetModel.created_at,
FleetModel.skip_min_processing_interval == True,
),
or_(
FleetModel.lock_expires_at.is_(None),
Expand All @@ -173,6 +177,7 @@ async def fetch(self, limit: int) -> list[PipelineItem]:
FleetModel.id,
FleetModel.lock_token,
FleetModel.lock_expires_at,
FleetModel.skip_min_processing_interval,
)
)
)
Expand All @@ -185,6 +190,7 @@ async def fetch(self, limit: int) -> list[PipelineItem]:
fleet_model.lock_expires_at = lock_expires_at
fleet_model.lock_token = lock_token
fleet_model.lock_owner = FleetPipeline.__name__
fleet_model.skip_min_processing_interval = False
items.append(
PipelineItem(
__tablename__=FleetModel.__tablename__,
Expand Down Expand Up @@ -608,8 +614,10 @@ def _is_fleet_ready_for_consolidation(fleet_model: FleetModel) -> bool:
# We use exponentially increasing consolidation retry delays so that
# consolidation does not happen too often. In particular, this prevents
# retrying instance provisioning constantly in case of no offers.
# A consolidated fleet (attempt 0) has nothing to retry, so its consolidation is not delayed
# and a fleet woken up by a lost instance replaces it right away.
_CONSOLIDATION_RETRY_DELAYS = [
timedelta(minutes=1),
timedelta(0),
timedelta(minutes=2),
timedelta(minutes=5),
timedelta(minutes=10),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
ProjectModel,
)
from dstack._internal.server.services import events
from dstack._internal.server.services.fleets import skip_fleet_min_processing_interval
from dstack._internal.server.services.instances import (
emit_instance_status_change_event,
is_ssh_instance,
Expand Down Expand Up @@ -307,6 +308,8 @@ async def process(self, item: InstancePipelineItem):
instance_model=process_context.instance_model,
result=process_context.result,
)
if process_context.result.wake_fleet_id is not None:
self._pipeline_hinter.hint_fetch(FleetModel.__name__)


@dataclass
Expand Down Expand Up @@ -467,6 +470,10 @@ async def _apply_process_result(
await session.rollback()
return

if result.wake_fleet_id is not None:
# Cross-pipeline write is ok: worst case the fleet is processed one extra time.
await skip_fleet_min_processing_interval(session, result.wake_fleet_id)

if result.schedule_pg_deletion_fleet_id is not None:
await schedule_fleet_placement_groups_deletion(
session=session,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import uuid
from dataclasses import dataclass
from typing import Optional
from typing import Optional, Union

from pydantic import ValidationError
from sqlalchemy import select
Expand Down Expand Up @@ -66,6 +66,13 @@ class _ClusterMasterContext:
master_job_provisioning_data: Optional[JobProvisioningData]


@dataclass
class _WaitingForClusterMaster:
"""Provisioning can't proceed as it waits for the cluster master election or provisioning"""

requires_fleet_processing: bool


async def create_cloud_instance(instance_model: InstanceModel) -> ProcessResult:
result = ProcessResult()

Expand Down Expand Up @@ -95,8 +102,9 @@ async def create_cloud_instance(instance_model: InstanceModel) -> ProcessResult:
master_job_provisioning_data = None
if instance_model.fleet is not None and is_cloud_cluster(instance_model.fleet):
cluster_context = await _get_cluster_master_context(instance_model)
if cluster_context is None:
# Waiting for the master
if isinstance(cluster_context, _WaitingForClusterMaster):
if cluster_context.requires_fleet_processing:
result.wake_fleet_id = instance_model.fleet_id
return result
placement_group_models, placement_group_model = await _get_cluster_placement_context(
instance_model=instance_model,
Expand Down Expand Up @@ -252,7 +260,7 @@ async def create_cloud_instance(instance_model: InstanceModel) -> ProcessResult:

async def _get_cluster_master_context(
instance_model: InstanceModel,
) -> Optional[_ClusterMasterContext]:
) -> Union[_ClusterMasterContext, _WaitingForClusterMaster]:
assert instance_model.fleet is not None and is_cloud_cluster(instance_model.fleet)
assert instance_model.fleet_id is not None
async with get_session_ctx() as session:
Expand All @@ -265,21 +273,21 @@ async def _get_cluster_master_context(
"%s: waiting for fleet pipeline to elect current cluster master",
fmt(instance_model),
)
return None
return _WaitingForClusterMaster(requires_fleet_processing=True)

is_current_instance_master = current_master_instance_model.id == instance_model.id
master_job_provisioning_data = None
if not is_current_instance_master:
if (
current_master_instance_model.deleted
or current_master_instance_model.status == InstanceStatus.TERMINATED
or current_master_instance_model.status in InstanceStatus.finished_statuses()
):
logger.debug(
"%s: waiting for fleet pipeline to replace current master %s",
fmt(instance_model),
current_master_instance_model.id,
)
return None
return _WaitingForClusterMaster(requires_fleet_processing=True)
master_job_provisioning_data = get_instance_provisioning_data(
current_master_instance_model
)
Expand All @@ -289,7 +297,7 @@ async def _get_cluster_master_context(
fmt(instance_model),
current_master_instance_model.id,
)
return None
return _WaitingForClusterMaster(requires_fleet_processing=False)

return _ClusterMasterContext(
current_master_instance_model=current_master_instance_model,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ class ProcessResult:
new_placement_group_models: list[PlacementGroupModel] = field(default_factory=list)
schedule_pg_deletion_fleet_id: Optional[uuid.UUID] = None
schedule_pg_deletion_except_id: Optional[uuid.UUID] = None
wake_fleet_id: Optional[uuid.UUID] = None
"""The fleet for `FleetPipeline` to process ASAP after the update is applied."""
event_messages: list[str] = field(default_factory=list)
"""Extra instance events to emit after the update is applied."""

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ async def terminate_instance(instance_model: InstanceModel) -> ProcessResult:
instance_model=instance_model,
new_status=InstanceStatus.TERMINATED,
)
# The fleet may have become empty and ready to be deleted.
result.wake_fleet_id = instance_model.fleet_id
return result


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
get_next_instance_num,
is_cloud_cluster,
new_instances_in_fleet_require_create_instance_support,
skip_fleet_min_processing_interval,
)
from dstack._internal.server.services.instances import (
filter_non_placeholder_instances,
Expand Down Expand Up @@ -330,28 +331,28 @@ async def process(self, item: JobSubmittedPipelineItem):
if context.job_model.instance_assigned:
logger.debug("%s: provisioning has started", fmt(context.job_model))
provisioning = await _process_provisioning(item=item, context=context)
_hint_pipelines_fetch(
pipeline_hinter=self._pipeline_hinter,
result=provisioning,
)
await _apply_provisioning_result(
item=item,
provisioning=provisioning,
)
_hint_pipelines_fetch(
pipeline_hinter=self._pipeline_hinter,
result=provisioning,
)
self._pipeline_hinter.hint_fetch(JobModel.__name__)
return

logger.debug("%s: assignment has started", fmt(context.job_model))
assignment = await _process_assignment(context=context)
_hint_pipelines_fetch(
pipeline_hinter=self._pipeline_hinter,
result=assignment,
)
await _apply_assignment_result(
item=item,
context=context,
assignment=assignment,
)
_hint_pipelines_fetch(
pipeline_hinter=self._pipeline_hinter,
result=assignment,
)
self._pipeline_hinter.hint_fetch(JobModel.__name__)


Expand Down Expand Up @@ -386,7 +387,8 @@ class _DeferSubmittedJobResult:
"""The job is not ready yet, so apply should just mark it processed and unlock it."""

log_message: str
hint_fleet_pipeline: bool = False
wake_fleet_id: Optional[uuid.UUID] = None
"""The fleet for `FleetPipeline` to process ASAP, e.g. to elect the cluster master."""


@dataclass
Expand Down Expand Up @@ -628,7 +630,7 @@ async def _apply_assignment_result(
await _defer_submitted_job(
session=session,
job_model=job_model,
log_message=assignment.log_message,
result=assignment,
)
return

Expand Down Expand Up @@ -1357,7 +1359,7 @@ async def _apply_provisioning_result(
await _defer_submitted_job(
session=session,
job_model=job_model,
log_message=provisioning.log_message,
result=provisioning,
)
return

Expand Down Expand Up @@ -1505,7 +1507,7 @@ async def _process_new_capacity_provisioning(
):
return _DeferSubmittedJobResult(
log_message="waiting for fleet master instance election",
hint_fleet_pipeline=True,
wake_fleet_id=fleet_model.id,
)
provision_new_capacity_result = await _provision_new_capacity(
project=context.project,
Expand Down Expand Up @@ -2279,7 +2281,7 @@ def _hint_pipelines_fetch(
if not isinstance(result, _DeferSubmittedJobResult):
return

if result.hint_fleet_pipeline:
if result.wake_fleet_id is not None:
pipeline_hinter.hint_fetch(FleetModel.__name__)


Expand Down Expand Up @@ -2796,9 +2798,12 @@ def _get_offer_mount_point_volume(
async def _defer_submitted_job(
session: AsyncSession,
job_model: JobModel,
log_message: str,
result: _DeferSubmittedJobResult,
) -> None:
logger.debug("%s: %s", fmt(job_model), log_message)
logger.debug("%s: %s", fmt(job_model), result.log_message)
if result.wake_fleet_id is not None:
# Cross-pipeline write is ok: worst case the fleet is processed one extra time.
await skip_fleet_min_processing_interval(session, result.wake_fleet_id)
await _mark_job_processed(session=session, job_model=job_model)


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""Add FleetModel.skip_min_processing_interval

Revision ID: e4a1c9f2b7d3
Revises: 17e6c7ef91dd
Create Date: 2026-11-27 09:00:00.000000+00:00

"""

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = "e4a1c9f2b7d3"
down_revision = "17e6c7ef91dd"
branch_labels = None
depends_on = None


def upgrade() -> None:
with op.batch_alter_table("fleets", schema=None) as batch_op:
batch_op.add_column(
sa.Column(
"skip_min_processing_interval",
sa.Boolean(),
server_default=sa.false(),
nullable=False,
)
)


def downgrade() -> None:
with op.batch_alter_table("fleets", schema=None) as batch_op:
batch_op.drop_column("skip_min_processing_interval")
3 changes: 3 additions & 0 deletions src/dstack/_internal/server/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,9 @@ class FleetModel(PipelineModelMixin, BaseModel):
last_processed_at: Mapped[datetime] = mapped_column(
NaiveDateTime, default=get_current_datetime
)
skip_min_processing_interval: Mapped[bool] = mapped_column(
Boolean, default=False, server_default=false()
)
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
deleted_at: Mapped[Optional[datetime]] = mapped_column(NaiveDateTime)

Expand Down
23 changes: 21 additions & 2 deletions src/dstack/_internal/server/services/fleets.py
Original file line number Diff line number Diff line change
Expand Up @@ -893,9 +893,14 @@ async def delete_fleets(
FleetStatus.TERMINATING,
actor=events.UserActor.from_user(user),
)
# Process the fleet ASAP so that an empty fleet is deleted without delay.
fleet_model.skip_min_processing_interval = True
await session.commit()
if hint_instance_pipeline and pipeline_hinter is not None:
pipeline_hinter.hint_fetch(InstanceModel.__name__)
if pipeline_hinter is not None:
if hint_instance_pipeline:
pipeline_hinter.hint_fetch(InstanceModel.__name__)
if instance_nums is None:
pipeline_hinter.hint_fetch(FleetModel.__name__)


def fleet_model_to_fleet(
Expand Down Expand Up @@ -997,6 +1002,8 @@ def get_fleet_master_instance_provisioning_data(
if (
instance_model.id == fleet_model.current_master_instance_id
and not instance_model.deleted
# A terminating master is about to be replaced by `FleetPipeline`.
and instance_model.status not in InstanceStatus.finished_statuses()
and instance_model.job_provisioning_data is not None
):
return validate_json_extra_ignore(
Expand All @@ -1006,6 +1013,18 @@ def get_fleet_master_instance_provisioning_data(
return None


async def skip_fleet_min_processing_interval(session: AsyncSession, fleet_id: uuid.UUID) -> None:
"""
Makes `FleetPipeline` process the fleet without waiting for `min_processing_interval`.
Callers should also hint `FleetPipeline` after commit.
"""
await session.execute(
update(FleetModel)
.where(FleetModel.id == fleet_id)
.values(skip_min_processing_interval=True)
)


def can_create_new_cloud_instance_in_fleet(fleet_model: FleetModel, fleet_spec: FleetSpec) -> bool:
if fleet_spec.configuration.ssh_config is not None:
return False
Expand Down
Loading
Loading