diff --git a/src/dstack/_internal/server/background/pipeline_tasks/jobs_submitted.py b/src/dstack/_internal/server/background/pipeline_tasks/jobs_submitted.py index f303525ee..c10b65893 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/jobs_submitted.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/jobs_submitted.py @@ -413,9 +413,8 @@ class _TerminateSubmittedJobResult: @dataclass class _VolumeAttachmentPayload: - volume_id: uuid.UUID + volume_model: VolumeModel attachment_data: str - volume_name: str @dataclass @@ -1954,9 +1953,8 @@ async def _process_volume_attachments( ) attachments.append( _VolumeAttachmentPayload( - volume_id=volume_model.id, + volume_model=volume_model, attachment_data=attachment_data.model_dump_json(), - volume_name=volume.name, ) ) break @@ -2121,11 +2119,13 @@ async def _apply_volume_attachment_result( ) -> None: job_runtime_data = get_or_error(get_job_runtime_data(job_model)) job_runtime_data.volume_names = [ - attachment.volume_name for attachment in volume_attachment_result.attachments + attachment.volume_model.name for attachment in volume_attachment_result.attachments ] job_model.job_runtime_data = job_runtime_data.model_dump_json() - volume_ids = [attachment.volume_id for attachment in volume_attachment_result.attachments] + volume_ids = [ + attachment.volume_model.id for attachment in volume_attachment_result.attachments + ] if volume_ids: now = get_current_datetime() await session.execute( @@ -2136,11 +2136,21 @@ async def _apply_volume_attachment_result( for attachment in volume_attachment_result.attachments: session.add( VolumeAttachmentModel( - volume_id=attachment.volume_id, + volume_id=attachment.volume_model.id, instance=instance_model, attachment_data=attachment.attachment_data, ) ) + events.emit( + session, + "Volume attached to instance", + actor=events.SystemActor(), + targets=[ + events.Target.from_model(attachment.volume_model), + events.Target.from_model(instance_model), + events.Target.from_model(job_model), + ], + ) if volume_attachment_result.termination_message is None: return diff --git a/src/dstack/_internal/server/background/pipeline_tasks/jobs_terminating.py b/src/dstack/_internal/server/background/pipeline_tasks/jobs_terminating.py index 06853f9a4..bd9d71a85 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/jobs_terminating.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/jobs_terminating.py @@ -345,7 +345,7 @@ class _ProcessResult: instance_update_map: Optional[_InstanceUpdateMap] = None delete_instance: bool = False volume_update_rows: list[_VolumeUpdateRow] = field(default_factory=list) - detached_volume_ids: set[uuid.UUID] = field(default_factory=set) + detached_volumes: list[VolumeModel] = field(default_factory=list) unassign_event_message: Optional[str] = None graceful_stop_event_message: Optional[str] = None sync_gateway_replicas: bool = False @@ -355,7 +355,7 @@ class _ProcessResult: @dataclass class _VolumeDetachResult: all_detached: bool - detached_volume_ids: set[uuid.UUID] = field(default_factory=set) + detached_volumes: list[VolumeModel] = field(default_factory=list) set_volumes_detached_at: bool = False @@ -575,13 +575,31 @@ async def _apply_process_result( # updates active attached volumes and/or the races are accepted. await session.execute(update(VolumeModel), result.volume_update_rows) - if result.detached_volume_ids and instance_model is not None: - await session.execute( - delete(VolumeAttachmentModel).where( + if result.detached_volumes and instance_model is not None: + res = await session.execute( + delete(VolumeAttachmentModel) + .where( VolumeAttachmentModel.instance_id == instance_model.id, - VolumeAttachmentModel.volume_id.in_(result.detached_volume_ids), + VolumeAttachmentModel.volume_id.in_([v.id for v in result.detached_volumes]), ) + .returning(VolumeAttachmentModel.volume_id) ) + deleted_attachment_volume_ids = set(res.scalars().all()) + for volume_model in result.detached_volumes: + if volume_model.id not in deleted_attachment_volume_ids: + # Only emit events for attachments deleted now. Volumes detached on earlier + # passes are reported as detached again while other volumes are still detaching. + continue + events.emit( + session, + "Volume detached from instance", + actor=events.SystemActor(), + targets=[ + events.Target.from_model(volume_model), + events.Target.from_model(instance_model), + events.Target.from_model(job_model), + ], + ) emit_job_status_change_event( session=session, @@ -744,7 +762,7 @@ async def _process_terminating_job( instance_model=instance_model, job_provisioning_data=jpd, ) - result.detached_volume_ids = detach_result.detached_volume_ids + result.detached_volumes = detach_result.detached_volumes if detach_result.set_volumes_detached_at: result.job_update_map["volumes_detached_at"] = NOW_PLACEHOLDER @@ -935,7 +953,7 @@ async def _process_job_volumes_detaching( instance_model=instance_model, job_provisioning_data=jpd, ) - result.detached_volume_ids = detach_result.detached_volume_ids + result.detached_volumes = detach_result.detached_volumes if detach_result.all_detached: result.job_update_map["status"] = _get_job_termination_status(job_model) return result @@ -1066,7 +1084,7 @@ async def _detach_volumes_from_job_instance( ) return _VolumeDetachResult(all_detached=False) - detached_volume_ids = set() + detached_volumes = [] all_detached = True for volume_model in volume_models: detached = await _detach_volume_from_job_instance( @@ -1079,13 +1097,13 @@ async def _detach_volumes_from_job_instance( run_termination_reason=run_termination_reason, ) if detached: - detached_volume_ids.add(volume_model.id) + detached_volumes.append(volume_model) else: all_detached = False return _VolumeDetachResult( all_detached=all_detached, - detached_volume_ids=detached_volume_ids, + detached_volumes=detached_volumes, set_volumes_detached_at=job_model.volumes_detached_at is None, ) diff --git a/src/tests/_internal/server/background/pipeline_tasks/test_jobs_submitted.py b/src/tests/_internal/server/background/pipeline_tasks/test_jobs_submitted.py index 08f1ecd5f..d250daffa 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/test_jobs_submitted.py +++ b/src/tests/_internal/server/background/pipeline_tasks/test_jobs_submitted.py @@ -24,6 +24,7 @@ TaskConfiguration, ) from dstack._internal.core.models.envs import Env +from dstack._internal.core.models.events import EventTargetType from dstack._internal.core.models.fleets import FleetNodesSpec, InstanceGroupPlacement from dstack._internal.core.models.instances import InstanceStatus from dstack._internal.core.models.placement import PlacementGroup @@ -88,6 +89,7 @@ get_run_spec, get_ssh_fleet_configuration, get_volume_provisioning_data, + list_events, mock_lease, ) from dstack._internal.utils.common import get_current_datetime, get_or_error @@ -2806,6 +2808,15 @@ async def test_attaches_volume_on_existing_instance( assert volume.lock_token is None assert volume.lock_expires_at is None backend_mock.compute.return_value.attach_volume.assert_called_once() + attach_events = [ + e for e in await list_events(session) if e.message == "Volume attached to instance" + ] + assert len(attach_events) == 1 + assert {(t.entity_type, t.entity_id) for t in attach_events[0].targets} == { + (EventTargetType.VOLUME, volume.id), + (EventTargetType.INSTANCE, instance.id), + (EventTargetType.JOB, job.id), + } async def test_terminates_job_when_volume_is_locked_for_processing( self, test_db, session: AsyncSession, worker: JobSubmittedWorker diff --git a/src/tests/_internal/server/background/pipeline_tasks/test_jobs_terminating.py b/src/tests/_internal/server/background/pipeline_tasks/test_jobs_terminating.py index 6b36841c2..2a25ead7c 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/test_jobs_terminating.py +++ b/src/tests/_internal/server/background/pipeline_tasks/test_jobs_terminating.py @@ -11,6 +11,7 @@ from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.configurations import TaskConfiguration +from dstack._internal.core.models.events import EventTargetType from dstack._internal.core.models.gateways import GatewayReplicaStatus, GatewayStatus from dstack._internal.core.models.instances import InstanceStatus from dstack._internal.core.models.runs import ( @@ -1258,6 +1259,15 @@ async def test_force_detaches_job_volumes( instance = res.unique().scalar_one() assert job.status == JobStatus.TERMINATED assert len(instance.volume_attachments) == 0 + detach_events = [ + e for e in await list_events(session) if e.message == "Volume detached from instance" + ] + assert len(detach_events) == 1 + assert {(t.entity_type, t.entity_id) for t in detach_events[0].targets} == { + (EventTargetType.VOLUME, volume.id), + (EventTargetType.INSTANCE, instance.id), + (EventTargetType.JOB, job.id), + } async def test_terminates_job_on_shared_instance( self, test_db, session: AsyncSession, worker: JobTerminatingWorker @@ -1371,6 +1381,13 @@ async def test_detaches_job_volumes_on_shared_instance( assert job.status == JobStatus.TERMINATED assert len(instance.volume_attachments) == 1 assert instance.volume_attachments[0].volume == volume_2 + detach_events = [ + e for e in await list_events(session) if e.message == "Volume detached from instance" + ] + assert len(detach_events) == 1 + assert (EventTargetType.VOLUME, volume_1.id) in { + (t.entity_type, t.entity_id) for t in detach_events[0].targets + } async def test_resets_job_for_retry_if_related_instance_is_locked( self, test_db, session: AsyncSession, worker: JobTerminatingWorker