diff --git a/contributing/ORPHAN-CLEANUP.md b/contributing/ORPHAN-CLEANUP.md
index a8bd6f83d4..efcf781694 100644
--- a/contributing/ORPHAN-CLEANUP.md
+++ b/contributing/ORPHAN-CLEANUP.md
@@ -29,7 +29,7 @@ Processing a row:
- Instance found:
- `PENDING`, `TERMINATING`: skip, since the resources may be in flight. An error is logged if a pending instance's resources look stuck.
- `TERMINATED`: orphan.
- - `PROVISIONING`, `IDLE`, `BUSY`: tracked if the base backend and `primary_id` match the instance's provisioning data, orphan otherwise.
+ - `PROVISIONING`, `IDLE`, `BUSY`: tracked if the base backend and `primary_id` match the instance's provisioning data, orphan otherwise. A backend that uses the exact launch name until it learns the provider ID can also supply `primary_name` for this match.
- Without provisioning data: ignored with an error log.
- Record found without an instance: orphan. The owner was deleted, e.g. a placeholder instance after a failed `run_job()`, so nothing can be creating its resources anymore.
- No record: ignored. Resources of other servers and projects are never touched.
diff --git a/frontend/src/types/backend.d.ts b/frontend/src/types/backend.d.ts
index 216d60829d..28af05dcef 100644
--- a/frontend/src/types/backend.d.ts
+++ b/frontend/src/types/backend.d.ts
@@ -10,6 +10,7 @@ declare type TBackendType =
| 'kubernetes'
| 'lambda'
| 'lium'
+ | 'massedcompute'
| 'local'
| 'nebius'
| 'remote'
diff --git a/mkdocs/docs/concepts/backends.md b/mkdocs/docs/concepts/backends.md
index df1d4820bd..a25a448bd1 100644
--- a/mkdocs/docs/concepts/backends.md
+++ b/mkdocs/docs/concepts/backends.md
@@ -1087,6 +1087,28 @@ projects:
+### MassedCompute
+
+Create a full-access API key in [MassedCompute settings](https://vm-docs.massedcompute.com/docs/settings/api-settings)
+and configure the backend in the server configuration.
+
+
+
+```yaml
+projects:
+ - name: main
+ backends:
+ - type: massedcompute
+ creds:
+ type: api_key
+ api_key: YOUR_MASSEDCOMPUTE_API_KEY
+```
+
+
+
+MassedCompute provisions single-node, on-demand CPU and GPU VMs and selects the site at launch
+(region `any`). It also supports experimental [network volumes](volumes.md#network-volumes).
+
### Vultr
Log into your [Vultr](https://www.vultr.com/) account, click `Account` in the sidebar, select `API`, find the `Personal Access Token` panel and click the `Enable API` button. In the `Access Control` panel, allow API requests from all addresses or from the subnet where your `dstack` server is deployed.
diff --git a/mkdocs/docs/concepts/volumes.md b/mkdocs/docs/concepts/volumes.md
index 0eea02cc32..1386f49318 100644
--- a/mkdocs/docs/concepts/volumes.md
+++ b/mkdocs/docs/concepts/volumes.md
@@ -16,7 +16,7 @@ Useful as a cache for cloud fleets or for persistent storage with SSH fleets.
## Network volumes
-> Network volumes are currently supported for the `aws`, `gcp`, `runpod`, `kubernetes`, `daytona`, and `lium` backends.
+> Network volumes are currently supported for the `aws`, `gcp`, `runpod`, `kubernetes`, `daytona`, `lium`, and `massedcompute` backends.
### Apply a configuration
@@ -64,6 +64,18 @@ If you use this configuration, `dstack` will create a new volume based on the sp
> Files on Lium volumes are owned by root and accessible to all users in the container.
+??? info "MassedCompute"
+ Network volumes are experimental. Enable Persistent Storage in your MassedCompute account and omit `size` and `region`.
+ A VM can attach up to eight volumes at launch. Delete the VM before using a volume on another VM.
+
+ ```yaml
+ type: volume
+ backend: massedcompute
+ name: my-volume
+ ```
+
+ > If a VM loses its connection to storage, deleting it can lose recent writes. See [storage limitations](https://vm-docs.massedcompute.com/docs/persistent-storage/limitations).
+
??? info "Kubernetes"
Set `region` to a kubeconfig context name enabled in the [backend configuration](backends.md#kubernetes).
Omit it only for legacy configurations without `contexts`.
@@ -228,7 +240,7 @@ and its contents will persist across runs.
### Detach a volume { #detach-network-volume }
-`dstack` automatically detaches volumes from instances when a run stops.
+`dstack` automatically detaches volumes when a run stops if the backend supports detaching them.
!!! info "Force detach"
In some clouds such as AWS a volume may stuck in the detaching state.
diff --git a/mkdocs/docs/reference/dstack.yml/volume.md b/mkdocs/docs/reference/dstack.yml/volume.md
index 7172095710..ae6ec17286 100644
--- a/mkdocs/docs/reference/dstack.yml/volume.md
+++ b/mkdocs/docs/reference/dstack.yml/volume.md
@@ -42,6 +42,14 @@ The `volume` configuration type allows creating, registering, and updating [volu
backend:
required: true
+=== "MassedCompute"
+
+ #SCHEMA# dstack._internal.core.models.volumes.MassedComputeVolumeConfiguration
+ overrides:
+ show_root_heading: false
+ backend:
+ required: true
+
=== "Kubernetes"
Kubernetes backend volumes are mapped to [`PersistentVolumeClaim`](https://kubernetes.io/docs/concepts/storage/persistent-volumes/#persistentvolumeclaims) objects.
diff --git a/mkdocs/docs/reference/server/config.yml.md b/mkdocs/docs/reference/server/config.yml.md
index 00cf2f1957..b5cf0e9adb 100644
--- a/mkdocs/docs/reference/server/config.yml.md
+++ b/mkdocs/docs/reference/server/config.yml.md
@@ -176,6 +176,23 @@ to configure [backends](../../concepts/backends.md) and other [server-level sett
type:
required: true
+##### `projects[n].backends[type=massedcompute]` { #massedcompute data-toc-label="massedcompute" }
+
+#SCHEMA# dstack._internal.core.backends.massedcompute.models.MassedComputeBackendConfigWithCreds
+ overrides:
+ show_root_heading: false
+ type:
+ required: true
+ item_id_prefix: massedcompute-
+
+###### `projects[n].backends[type=massedcompute].creds` { #massedcompute-creds data-toc-label="creds" }
+
+#SCHEMA# dstack._internal.core.backends.massedcompute.models.MassedComputeAPIKeyCreds
+ overrides:
+ show_root_heading: false
+ type:
+ required: true
+
##### `projects[n].backends[type=nebius]` { #nebius data-toc-label="nebius" }
#SCHEMA# dstack._internal.core.backends.nebius.models.NebiusBackendFileConfigWithCreds
diff --git a/pyproject.toml b/pyproject.toml
index 126589c067..5d5063499c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -32,7 +32,8 @@ dependencies = [
"python-multipart>=0.0.31",
"filelock",
"psutil",
- "gpuhunt==0.1.36",
+ # Replace with the gpuhunt release containing the MassedCompute provider before merging.
+ "gpuhunt @ git+https://github.com/dstackai/gpuhunt.git@bc78a82599800bd2612a180292747016bbe328ed",
"argcomplete>=3.5.0",
"ignore-python>=0.2.0",
"apscheduler<4",
@@ -56,6 +57,10 @@ dstack = "dstack._internal.cli.main:main"
[tool.hatch.version]
path = "src/dstack/version.py"
+[tool.hatch.metadata]
+# Remove after pinning the released gpuhunt package.
+allow-direct-references = true
+
[tool.hatch.build.targets.sdist]
artifacts = [
"src/dstack/_internal/server/statics/**",
diff --git a/runner/internal/shim/docker.go b/runner/internal/shim/docker.go
index dd402e558b..fb6867a57b 100644
--- a/runner/internal/shim/docker.go
+++ b/runner/internal/shim/docker.go
@@ -979,7 +979,7 @@ func (d *DockerRunner) createContainer(
if err != nil {
return fmt.Errorf("get docker mounts: %w", err)
}
- volumeMounts, err := getVolumeMounts(task.config.VolumeMounts)
+ volumeMounts, err := getVolumeMounts(task.config)
if err != nil {
return fmt.Errorf("get volume mounts: %w", err)
}
@@ -1328,10 +1328,19 @@ func configureHpcNetworkingIfAvailable(hostConfig *container.HostConfig) {
}
}
-func getVolumeMounts(mountPoints []VolumeMountPoint) ([]mount.Mount, error) {
+func getVolumeMounts(cfg TaskConfig) ([]mount.Mount, error) {
+ sources := make(map[string]string)
+ for _, volume := range cfg.Volumes {
+ if volume.MountPath != "" {
+ sources[volume.Name] = taskVolumeMountPoint(cfg.ID, volume)
+ }
+ }
mounts := []mount.Mount{}
- for _, mountPoint := range mountPoints {
- source := getVolumeMountPoint(mountPoint.Name)
+ for _, mountPoint := range cfg.VolumeMounts {
+ source, ok := sources[mountPoint.Name]
+ if !ok {
+ source = getVolumeMountPoint(mountPoint.Name)
+ }
mounts = append(mounts, mount.Mount{Type: mount.TypeBind, Source: source, Target: mountPoint.Path})
}
return mounts, nil
diff --git a/runner/internal/shim/models.go b/runner/internal/shim/models.go
index 6166c7c7ff..10f284a0b8 100644
--- a/runner/internal/shim/models.go
+++ b/runner/internal/shim/models.go
@@ -71,6 +71,7 @@ type VolumeInfo struct {
VolumeId string `json:"volume_id"`
InitFs bool `json:"init_fs"`
DeviceName string `json:"device_name"`
+ MountPath string `json:"mount_path,omitempty"`
}
type PortMapping struct {
diff --git a/runner/internal/shim/volumes.go b/runner/internal/shim/volumes.go
index f6d6096b0b..0194469df2 100644
--- a/runner/internal/shim/volumes.go
+++ b/runner/internal/shim/volumes.go
@@ -23,6 +23,12 @@ func prepareVolumes(ctx context.Context, taskConfig TaskConfig) error {
}
log.Debug(ctx, "Preparing volumes...")
for _, volume := range taskConfig.Volumes {
+ if volume.MountPath != "" {
+ if err := bindMountedVolume(volume.MountPath, taskVolumeMountPoint(taskConfig.ID, volume)); err != nil {
+ return fmt.Errorf("bind mounted volume %s: %w", volume.Name, err)
+ }
+ continue
+ }
err := formatAndMountVolume(ctx, volume)
if err != nil {
return fmt.Errorf("format and mount volume: %w", err)
@@ -38,12 +44,23 @@ func unmountVolumes(ctx context.Context, taskConfig TaskConfig) error {
log.Debug(ctx, "Unmounting volumes...")
var failed []string
for _, volume := range taskConfig.Volumes {
- mountPoint := getVolumeMountPoint(volume.Name)
+ mountPoint := taskVolumeMountPoint(taskConfig.ID, volume)
cmd := exec.CommandContext(ctx, "mountpoint", mountPoint)
if output, err := cmd.CombinedOutput(); err != nil {
log.Info(ctx, "skipping", "mountpoint", mountPoint, "output", output)
continue
}
+ if volume.MountPath != "" {
+ // MNT_FORCE can abort the underlying FUSE connection, including the provider's mount.
+ if err := unix.Unmount(mountPoint, 0); err != nil {
+ log.Error(ctx, "failed to release volume bind mount", "mountpoint", mountPoint, "err", err)
+ failed = append(failed, mountPoint)
+ } else {
+ _ = os.Remove(mountPoint)
+ _ = os.Remove(filepath.Dir(mountPoint))
+ }
+ continue
+ }
cmd = exec.CommandContext(ctx, "umount", "-qf", mountPoint)
if output, err := cmd.CombinedOutput(); err != nil {
log.Error(ctx, "failed to unmount", "mountpoint", mountPoint, "output", output)
@@ -58,6 +75,40 @@ func unmountVolumes(ctx context.Context, taskConfig TaskConfig) error {
return nil
}
+// bindMountedVolume pins the source directory before checking its mount ID. A provider
+// unmount between verification and bind cannot substitute a directory on the root disk.
+func bindMountedVolume(source, target string) error {
+ fd, err := unix.Open(source, unix.O_PATH|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = unix.Close(fd) }()
+ var dir, parent unix.Statx_t
+ if err := unix.Statx(fd, "", unix.AT_EMPTY_PATH, unix.STATX_MNT_ID, &dir); err != nil {
+ return err
+ }
+ if err := unix.Statx(fd, "..", 0, unix.STATX_MNT_ID, &parent); err != nil {
+ return err
+ }
+ if dir.Mask&unix.STATX_MNT_ID == 0 || parent.Mask&unix.STATX_MNT_ID == 0 || dir.Mnt_id == parent.Mnt_id {
+ return fmt.Errorf("%s is not a verified mount point", source)
+ }
+ if err := os.MkdirAll(target, 0o755); err != nil {
+ return err
+ }
+ if err := unix.Mount(fmt.Sprintf("/proc/self/fd/%d", fd), target, "", unix.MS_BIND, ""); err != nil {
+ return err
+ }
+ return unix.Mount("", target, "", unix.MS_PRIVATE, "")
+}
+
+func taskVolumeMountPoint(taskID string, volume VolumeInfo) string {
+ if volume.MountPath != "" {
+ return filepath.Join("/mnt/disks/dstack-task-volumes", taskID, volume.Name)
+ }
+ return getVolumeMountPoint(volume.Name)
+}
+
func formatAndMountVolume(ctx context.Context, volume VolumeInfo) error {
backend, err := backends.GetBackend(volume.Backend)
if err != nil {
diff --git a/runner/internal/shim/volumes_test.go b/runner/internal/shim/volumes_test.go
new file mode 100644
index 0000000000..783af3208f
--- /dev/null
+++ b/runner/internal/shim/volumes_test.go
@@ -0,0 +1,35 @@
+package shim
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "golang.org/x/sys/unix"
+)
+
+func TestBindMountedVolume(t *testing.T) {
+ source := t.TempDir()
+ target := filepath.Join(t.TempDir(), "bind")
+ // A provider can leave the directory behind even when its filesystem is missing.
+ require.ErrorContains(t, bindMountedVolume(source, target), "not a verified mount point")
+
+ if err := unix.Mount("tmpfs", source, "tmpfs", 0, "size=1m"); errors.Is(err, unix.EPERM) {
+ t.Skip("mounting tmpfs requires CAP_SYS_ADMIN")
+ } else {
+ require.NoError(t, err)
+ }
+ t.Cleanup(func() { _ = unix.Unmount(source, 0) })
+ require.NoError(t, os.WriteFile(filepath.Join(source, "checkpoint"), []byte("saved"), 0o600))
+ require.NoError(t, bindMountedVolume(source, target))
+ t.Cleanup(func() { _ = unix.Unmount(target, 0) })
+
+ // Removing the provider's original mount must never redirect the job to the local disk.
+ require.NoError(t, unix.Unmount(source, 0))
+ data, err := os.ReadFile(filepath.Join(target, "checkpoint"))
+ require.NoError(t, err)
+ require.Equal(t, "saved", string(data))
+ require.NoFileExists(t, filepath.Join(source, "checkpoint"))
+}
diff --git a/src/dstack/_internal/core/backends/base/compute.py b/src/dstack/_internal/core/backends/base/compute.py
index da099343f3..395cd63fa5 100644
--- a/src/dstack/_internal/core/backends/base/compute.py
+++ b/src/dstack/_internal/core/backends/base/compute.py
@@ -779,6 +779,14 @@ def delete_volume(self, volume: Volume):
"""
raise NotImplementedError()
+ def get_volume_mounts_to_sync(self, provisioning_data: JobProvisioningData) -> list[str]:
+ """Return host mounts to flush before terminating the instance.
+
+ Called only for VMs with provider-mounted filesystems and an SSH address.
+ Exclude mounts when the provider confirms the VM is already stopped or gone.
+ """
+ return list((provisioning_data.volume_mounts or {}).values())
+
def attach_volume(
self, volume: Volume, provisioning_data: JobProvisioningData
) -> VolumeAttachmentData:
diff --git a/src/dstack/_internal/core/backends/configurators.py b/src/dstack/_internal/core/backends/configurators.py
index 3973687c6e..d20eb75843 100644
--- a/src/dstack/_internal/core/backends/configurators.py
+++ b/src/dstack/_internal/core/backends/configurators.py
@@ -120,6 +120,13 @@
except ImportError:
pass
+try:
+ from dstack._internal.core.backends.massedcompute.configurator import MassedComputeConfigurator
+
+ _CONFIGURATOR_CLASSES.append(MassedComputeConfigurator)
+except ImportError:
+ pass
+
try:
from dstack._internal.core.backends.nebius.configurator import (
NebiusConfigurator,
diff --git a/src/dstack/_internal/core/backends/massedcompute/__init__.py b/src/dstack/_internal/core/backends/massedcompute/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/src/dstack/_internal/core/backends/massedcompute/api_client.py b/src/dstack/_internal/core/backends/massedcompute/api_client.py
new file mode 100644
index 0000000000..91d51e49b0
--- /dev/null
+++ b/src/dstack/_internal/core/backends/massedcompute/api_client.py
@@ -0,0 +1,207 @@
+from typing import Optional, TypeVar, Union
+from urllib.parse import quote
+from uuid import UUID
+
+import requests
+from pydantic import AwareDatetime, Field, ValidationError
+from typing_extensions import NotRequired, TypedDict
+
+from dstack._internal.core.errors import BackendAuthError, ComputeError, VolumeDeletionPending
+from dstack._internal.core.models.common import CoreModel, validate_json_extra_ignore
+from dstack._internal.utils.logging import get_logger
+
+API_URL = "https://vm.massedcompute.com/api/v1"
+_T = TypeVar("_T", bound=CoreModel)
+logger = get_logger(__name__)
+
+
+class MassedComputeInstance(CoreModel):
+ uuid: UUID
+ name: str
+ status: str
+ ip: Optional[str] = None
+ username: Optional[str] = None
+ os_booted: bool = False
+ created: Optional[AwareDatetime] = None
+
+
+class _AttachedInstance(CoreModel):
+ uuid: UUID
+
+
+class _VolumeIdentity(CoreModel):
+ id: UUID
+ name: str
+
+
+class MassedComputeVolume(_VolumeIdentity):
+ status: str
+ mount_path: str = Field(alias="mountPath")
+ can_manage: bool = Field(alias="canManage")
+ attached_to: list[_AttachedInstance] = Field(alias="attachedTo")
+ hidden_attached_count: int = Field(alias="hiddenAttachedCount")
+
+
+class _Volumes(CoreModel):
+ volumes: list[MassedComputeVolume] = Field(alias="storageVolumes")
+
+
+class _CreatedVolume(CoreModel):
+ volume: _VolumeIdentity = Field(alias="storageVolume")
+
+
+class _VolumeDeletion(CoreModel):
+ deleted: bool
+
+
+class _DeletedVolume(CoreModel):
+ result: _VolumeDeletion
+
+
+class _CreateVolumeRequest(TypedDict, closed=True):
+ name: str
+
+
+class _Instances(CoreModel):
+ instances: list[MassedComputeInstance] = Field(alias="runningInstances")
+
+
+class _LaunchResponse(CoreModel):
+ response: UUID
+
+
+class _LaunchRequest(TypedDict, closed=True):
+ instanceName: str
+ productName: str
+ imageId: int
+ regionName: str
+ command: str
+ sshKeys: list[str]
+ volumeIds: NotRequired[list[str]]
+
+
+class _TerminateRequest(TypedDict, closed=True):
+ instanceUuids: list[str]
+
+
+class _UnconfirmedResponse(ComputeError):
+ """The request may have succeeded without a usable response."""
+
+
+class MassedComputeAPIClient:
+ def __init__(self, api_key: str):
+ self.api_key = api_key
+
+ def validate_api_key(self) -> bool:
+ try:
+ self._request("POST", "/account/token/validation")
+ except BackendAuthError:
+ return False
+ return True
+
+ def launch(
+ self, name: str, product: str, command: str, volume_ids: Optional[list[str]] = None
+ ) -> Optional[str]:
+ """Send one launch request. Return its UUID, or None if it must be looked up by name.
+
+ A rejected request raises a backend error so the caller can try another offer.
+ """
+ payload: _LaunchRequest = {
+ "instanceName": name,
+ "productName": product,
+ "imageId": 84, # Ubuntu Server 22.04 w/ drivers
+ "regionName": "any",
+ "sshKeys": [],
+ "command": command,
+ }
+ if volume_ids:
+ payload["volumeIds"] = volume_ids
+ try:
+ response = self._request("POST", "/instance/launch", payload)
+ return str(_parse_response(_LaunchResponse, response).response)
+ except _UnconfirmedResponse as e:
+ logger.warning("MassedCompute launch of %s is unconfirmed: %s", name, e)
+ return None
+
+ def list_instances(self) -> list[MassedComputeInstance]:
+ return _parse_response(_Instances, self._request("GET", "/instance")).instances
+
+ def get_instance_by_name(self, name: str) -> Optional[MassedComputeInstance]:
+ matches = [vm for vm in self.list_instances() if vm.name == name]
+ if len(matches) > 1:
+ raise ComputeError(f"Multiple MassedCompute instances match launch name {name}")
+ return matches[0] if matches else None
+
+ def get_instance(self, instance_id: str) -> Optional[MassedComputeInstance]:
+ response = self._request("GET", "/instance/" + quote(instance_id, safe=""))
+ # The detail endpoint returns the same array as the list endpoint, empty after deletion.
+ instances = _parse_response(_Instances, response).instances
+ if not instances:
+ return None
+ if len(instances) != 1 or str(instances[0].uuid) != instance_id.lower():
+ raise ComputeError("MassedCompute returned an unexpected instance ID")
+ return instances[0]
+
+ def terminate(self, instance_id: str) -> None:
+ self._request("POST", "/instance/terminate", {"instanceUuids": [instance_id]})
+
+ def list_volumes(self) -> list[MassedComputeVolume]:
+ return _parse_response(_Volumes, self._request("GET", "/storage-volumes")).volumes
+
+ def create_volume(self, name: str) -> str:
+ payload: _CreateVolumeRequest = {"name": name}
+ response = self._request("POST", "/storage-volumes", payload)
+ return str(_parse_response(_CreatedVolume, response).volume.id)
+
+ def delete_volume(self, volume_id: str) -> None:
+ try:
+ response = self._request(
+ "DELETE", "/storage-volumes/" + quote(volume_id, safe=""), allowed_statuses=(404,)
+ )
+ if (
+ response.status_code == 404
+ or _parse_response(_DeletedVolume, response).result.deleted
+ ):
+ return
+ except (BackendAuthError, ComputeError) as e:
+ raise VolumeDeletionPending(str(e)) from e
+ raise VolumeDeletionPending("MassedCompute is still emptying the volume")
+
+ def _request(
+ self,
+ method: str,
+ path: str,
+ payload: Optional[Union[_LaunchRequest, _TerminateRequest, _CreateVolumeRequest]] = None,
+ allowed_statuses: tuple[int, ...] = (),
+ ) -> requests.Response:
+ try:
+ response = requests.request(
+ method,
+ API_URL + path,
+ json=payload,
+ timeout=30,
+ allow_redirects=False, # A redirect can replay a launch POST.
+ headers={"Authorization": f"Bearer {self.api_key}"},
+ )
+ except requests.ConnectTimeout:
+ raise ComputeError(f"MassedCompute {method} {path}: ConnectTimeout") from None
+ except requests.RequestException as e:
+ raise _UnconfirmedResponse(
+ f"MassedCompute {method} {path}: {type(e).__name__}"
+ ) from None
+ if response.status_code == 401:
+ raise BackendAuthError("Invalid MassedCompute API key")
+ if not 200 <= response.status_code < 300 and response.status_code not in allowed_statuses:
+ error = f"MassedCompute {method} {path}: HTTP {response.status_code}"
+ if 400 <= response.status_code < 500 and response.status_code != 408:
+ raise ComputeError(error)
+ raise _UnconfirmedResponse(error)
+ return response
+
+
+def _parse_response(model: type[_T], response: requests.Response) -> _T:
+ try:
+ return validate_json_extra_ignore(model, response.content)
+ except ValidationError:
+ # Instance payloads contain plaintext passwords, including in Pydantic's error inputs.
+ raise _UnconfirmedResponse("Unexpected response from MassedCompute") from None
diff --git a/src/dstack/_internal/core/backends/massedcompute/backend.py b/src/dstack/_internal/core/backends/massedcompute/backend.py
new file mode 100644
index 0000000000..832aef7a25
--- /dev/null
+++ b/src/dstack/_internal/core/backends/massedcompute/backend.py
@@ -0,0 +1,16 @@
+from dstack._internal.core.backends.base.backend import Backend
+from dstack._internal.core.backends.massedcompute.compute import MassedComputeCompute
+from dstack._internal.core.backends.massedcompute.models import MassedComputeConfig
+from dstack._internal.core.models.backends.base import BackendType
+
+
+class MassedComputeBackend(Backend):
+ TYPE = BackendType.MASSEDCOMPUTE
+ COMPUTE_CLASS = MassedComputeCompute
+
+ def __init__(self, config: MassedComputeConfig):
+ self.config = config
+ self._compute = MassedComputeCompute(self.config)
+
+ def compute(self) -> MassedComputeCompute:
+ return self._compute
diff --git a/src/dstack/_internal/core/backends/massedcompute/compute.py b/src/dstack/_internal/core/backends/massedcompute/compute.py
new file mode 100644
index 0000000000..b9c44ea1ef
--- /dev/null
+++ b/src/dstack/_internal/core/backends/massedcompute/compute.py
@@ -0,0 +1,304 @@
+import re
+import shlex
+import time
+from typing import Optional
+
+import gpuhunt
+from gpuhunt.providers.massedcompute import MassedComputeProvider
+
+from dstack._internal.core.backends.base.authorized_keys import get_add_authorized_keys_script
+from dstack._internal.core.backends.base.compute import (
+ Compute,
+ ComputeWithAllOffersCached,
+ ComputeWithCreateInstanceSupport,
+ ComputeWithInstanceVolumesSupport,
+ ComputeWithPrivilegedSupport,
+ ComputeWithResourceListingSupport,
+ ComputeWithVolumeSupport,
+ generate_unique_instance_name,
+ get_shim_commands,
+ parse_provider_ref_from_name,
+)
+from dstack._internal.core.backends.base.offers import get_catalog_offers
+from dstack._internal.core.backends.massedcompute.api_client import (
+ MassedComputeAPIClient,
+ MassedComputeInstance,
+ MassedComputeVolume,
+)
+from dstack._internal.core.backends.massedcompute.models import MassedComputeConfig
+from dstack._internal.core.errors import (
+ BackendError,
+ ComputeError,
+ NotYetTerminated,
+ ProvisioningError,
+ VolumeDeletionPending,
+ VolumeProvisioningError,
+)
+from dstack._internal.core.models.backends.base import BackendType
+from dstack._internal.core.models.backends.orphans import (
+ ListedResourceGroup,
+ OwnerType,
+ ResourceListing,
+)
+from dstack._internal.core.models.common import CoreModel, validate_json_extra_ignore
+from dstack._internal.core.models.instances import (
+ InstanceAvailability,
+ InstanceConfiguration,
+ InstanceOfferWithAvailability,
+)
+from dstack._internal.core.models.placement import PlacementGroup
+from dstack._internal.core.models.runs import JobProvisioningData
+from dstack._internal.core.models.volumes import Volume, VolumeProvisioningData
+from dstack._internal.utils.common import get_or_error
+
+
+class MassedComputeCompute(
+ ComputeWithAllOffersCached,
+ ComputeWithCreateInstanceSupport,
+ ComputeWithInstanceVolumesSupport,
+ ComputeWithPrivilegedSupport,
+ ComputeWithResourceListingSupport,
+ ComputeWithVolumeSupport,
+ Compute,
+):
+ def __init__(self, config: MassedComputeConfig):
+ super().__init__()
+ self.api_client = MassedComputeAPIClient(config.creds.api_key)
+ self.catalog = gpuhunt.Catalog(balance_resources=False, auto_reload=False)
+ self.catalog.add_provider(MassedComputeProvider(config.creds.api_key))
+
+ def get_all_offers_with_availability(
+ self, unallocated_resources: bool
+ ) -> list[InstanceOfferWithAvailability]:
+ offers = get_catalog_offers(backend=BackendType.MASSEDCOMPUTE, catalog=self.catalog)
+ return [
+ offer.with_availability(availability=InstanceAvailability.AVAILABLE)
+ for offer in offers
+ ]
+
+ def create_instance(
+ self,
+ instance_offer: InstanceOfferWithAvailability,
+ instance_config: InstanceConfiguration,
+ placement_group: Optional[PlacementGroup],
+ ) -> JobProvisioningData:
+ name = generate_unique_instance_name(instance_config, with_provider_ref=True)
+ # The image's SSH user is case-sensitive. The startup command runs as root.
+ key_script = get_add_authorized_keys_script(instance_config.get_public_keys())
+ install_keys = shlex.join(["sudo", "-H", "-u", "Ubuntu", "sh", "-c", key_script])
+ command = " && ".join(
+ [install_keys, *get_shim_commands(arch=instance_offer.instance.resources.cpu_arch)]
+ )
+ volume_mounts = self._get_volume_mounts(instance_config.volumes or [])
+ instance_id = self.api_client.launch(
+ name, instance_offer.instance.name, command, list(volume_mounts)
+ )
+ return JobProvisioningData(
+ backend=instance_offer.backend,
+ instance_type=instance_offer.instance,
+ instance_id=instance_id or name,
+ hostname=None,
+ internal_ip=None,
+ region=instance_offer.region,
+ price=instance_offer.price,
+ username="Ubuntu",
+ ssh_port=22,
+ dockerized=True,
+ ssh_proxy=None,
+ volume_mounts=volume_mounts or None,
+ backend_data=_MassedComputeLaunch(name=name).model_dump_json(),
+ )
+
+ def update_provisioning_data(
+ self,
+ provisioning_data: JobProvisioningData,
+ project_ssh_public_key: str,
+ project_ssh_private_key: str,
+ ) -> None:
+ instance = self._get_instance(
+ provisioning_data.instance_id, provisioning_data.backend_data
+ )
+ if instance is None:
+ return
+ if provisioning_data.backend_data is not None:
+ provisioning_data.instance_id = str(instance.uuid)
+ provisioning_data.backend_data = None
+ if provisioning_data.volume_mounts:
+ # Persist the confirmed UUID before a guest mount check can delay admission.
+ return
+ if instance.status.lower() == "stopped":
+ raise ProvisioningError("MassedCompute instance stopped during provisioning")
+ if instance.os_booted and instance.ip and instance.username:
+ if provisioning_data.volume_mounts:
+ attached = {
+ str(v.id): v.mount_path
+ for v in self.api_client.list_volumes()
+ if not v.hidden_attached_count
+ and [i.uuid for i in v.attached_to] == [instance.uuid]
+ }
+ for volume_id, path in provisioning_data.volume_mounts.items():
+ if attached.get(volume_id) != path:
+ raise ProvisioningError(
+ f"MassedCompute failed to attach volume {volume_id} to the VM"
+ )
+ provisioning_data.hostname = instance.ip
+ provisioning_data.username = instance.username
+
+ def terminate_instance(
+ self, instance_id: str, region: str, backend_data: Optional[str] = None
+ ) -> None:
+ instance = self._get_instance(instance_id, backend_data)
+ if backend_data is not None:
+ if instance is None:
+ # The API has no launch status or visibility deadline. If this VM never
+ # appears, termination cannot release its exclusive volumes automatically.
+ raise ComputeError(f"MassedCompute has not returned VM details for {instance_id}")
+ # Record that the VM was visible by UUID before deleting it.
+ raise NotYetTerminated(
+ f"Found MassedCompute instance {instance.uuid} for {instance_id}",
+ instance_id=str(instance.uuid),
+ )
+ if instance is None:
+ return
+ if instance.status.lower() not in {"terminating", "deleting"}:
+ self.api_client.terminate(instance_id)
+ raise NotYetTerminated(f"Waiting for MassedCompute instance {instance_id} to terminate")
+
+ def _get_instance(
+ self, instance_id: str, backend_data: Optional[str]
+ ) -> Optional[MassedComputeInstance]:
+ """Read VM details by UUID, recovering a lost launch reply by its exact name."""
+ if backend_data is not None:
+ launch = validate_json_extra_ignore(_MassedComputeLaunch, backend_data)
+ if launch.name == instance_id:
+ instance = self.api_client.get_instance_by_name(launch.name)
+ if instance is None:
+ return None
+ instance_id = str(instance.uuid)
+ return self.api_client.get_instance(instance_id)
+
+ def get_volume_mounts_to_sync(self, provisioning_data: JobProvisioningData) -> list[str]:
+ instance = self.api_client.get_instance(provisioning_data.instance_id)
+ if instance is None or instance.status.lower() in {"stopped", "terminating", "deleting"}:
+ return []
+ return super().get_volume_mounts_to_sync(provisioning_data)
+
+ def register_volume(self, volume: Volume) -> VolumeProvisioningData:
+ return self._wait_for_volume(get_or_error(volume.configuration.external_volume_id))
+
+ def create_volume(self, volume: Volume) -> VolumeProvisioningData:
+ # Stable across retries, including a server restart after a successful create.
+ name = f"dstack-{volume.id.hex[:15]}"
+ existing = next((v for v in self.api_client.list_volumes() if v.name == name), None)
+ if existing is None:
+ try:
+ volume_id = self.api_client.create_volume(name)
+ except ComputeError as e:
+ existing = next(
+ (v for v in self.api_client.list_volumes() if v.name == name), None
+ )
+ if existing is None:
+ raise ComputeError(f"Could not confirm creation of volume {name}: {e}") from e
+ volume_id = str(existing.id)
+ else:
+ volume_id = str(existing.id)
+ try:
+ return self._wait_for_volume(volume_id)
+ except BackendError as e:
+ try:
+ self.api_client.delete_volume(volume_id)
+ except VolumeDeletionPending as cleanup_error:
+ raise VolumeProvisioningError(
+ f"{e}. Volume {volume_id} still needs deletion: {cleanup_error}", volume_id
+ ) from e
+ raise
+
+ def _get_volume_mounts(self, volumes: list[Volume]) -> dict[str, str]:
+ """Check launch-time ownership and return the host mount for each requested volume."""
+ if not volumes:
+ return {}
+ if len(volumes) > 8:
+ raise ComputeError("MassedCompute accepts up to eight volumes per VM")
+ available = {str(v.id): v for v in self.api_client.list_volumes()}
+ mounts = {}
+ for volume in volumes:
+ data = volume.provisioning_data
+ if data is None or data.mount_path is None:
+ raise ComputeError(f"Missing mount path for MassedCompute volume {volume.name}")
+ provisioned = available.get(data.volume_id)
+ if (
+ provisioned is None
+ or provisioned.status != "active"
+ or not provisioned.can_manage
+ or provisioned.attached_to
+ or provisioned.hidden_attached_count
+ or provisioned.mount_path != data.mount_path
+ ):
+ raise ComputeError(f"MassedCompute volume {volume.name} is unavailable or in use")
+ mounts[data.volume_id] = data.mount_path
+ return mounts
+
+ def _wait_for_volume(self, volume_id: str) -> VolumeProvisioningData:
+ deadline = time.monotonic() + 60
+ while True:
+ volume = next(
+ (v for v in self.api_client.list_volumes() if str(v.id) == volume_id), None
+ )
+ if volume is None:
+ raise ComputeError(f"MassedCompute volume {volume_id} not found")
+ if volume.status == "active":
+ return _volume_provisioning_data(volume)
+ if volume.status != "creating" or time.monotonic() >= deadline:
+ raise ComputeError(f"MassedCompute volume {volume_id} is {volume.status}")
+ time.sleep(2)
+
+ def delete_volume(self, volume: Volume) -> None:
+ self.api_client.delete_volume(get_or_error(volume.volume_id))
+
+ def list_resource_groups(self) -> ResourceListing:
+ groups = []
+ for instance in self.api_client.list_instances():
+ provider_ref = parse_provider_ref_from_name(instance.name)
+ if provider_ref is None or instance.status.lower() in {"terminating", "deleting"}:
+ continue
+ groups.append(
+ ListedResourceGroup(
+ backend=BackendType.MASSEDCOMPUTE,
+ owner_type=OwnerType.INSTANCE,
+ provider_ref=provider_ref,
+ primary_id=str(instance.uuid),
+ primary_name=instance.name,
+ region="any",
+ created_at=instance.created,
+ description=instance.name,
+ backend_data=None,
+ )
+ )
+ return ResourceListing(resource_groups=groups)
+
+ def delete_resource_group(self, group: ListedResourceGroup) -> None:
+ if group.primary_id is not None:
+ self.terminate_instance(group.primary_id, "any")
+
+
+class _MassedComputeLaunch(CoreModel):
+ """Kept until the new VM is visible on the provider's UUID detail endpoint."""
+
+ name: str
+
+
+def _volume_provisioning_data(volume: MassedComputeVolume) -> VolumeProvisioningData:
+ if (
+ not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,20}[a-z0-9])?", volume.name)
+ or volume.mount_path != f"/persistent/{volume.name}"
+ ):
+ raise ComputeError("Invalid MassedCompute volume mount path")
+ return VolumeProvisioningData(
+ backend=BackendType.MASSEDCOMPUTE,
+ volume_id=str(volume.id),
+ size_gb=None,
+ attachable=False,
+ detachable=False,
+ exclusive_at_launch=True,
+ mount_path=volume.mount_path,
+ )
diff --git a/src/dstack/_internal/core/backends/massedcompute/configurator.py b/src/dstack/_internal/core/backends/massedcompute/configurator.py
new file mode 100644
index 0000000000..2cf76b5e48
--- /dev/null
+++ b/src/dstack/_internal/core/backends/massedcompute/configurator.py
@@ -0,0 +1,63 @@
+import json
+
+from dstack._internal.core.backends.base.configurator import (
+ BackendRecord,
+ Configurator,
+ raise_invalid_credentials_error,
+)
+from dstack._internal.core.backends.massedcompute.api_client import MassedComputeAPIClient
+from dstack._internal.core.backends.massedcompute.backend import MassedComputeBackend
+from dstack._internal.core.backends.massedcompute.models import (
+ MassedComputeBackendConfig,
+ MassedComputeBackendConfigWithCreds,
+ MassedComputeConfig,
+ MassedComputeCreds,
+ MassedComputeStoredConfig,
+)
+from dstack._internal.core.models.backends.base import BackendType
+from dstack._internal.core.models.common import validate_extra_ignore, validate_json_extra_ignore
+
+
+class MassedComputeConfigurator(
+ Configurator[MassedComputeBackendConfig, MassedComputeBackendConfigWithCreds]
+):
+ TYPE = BackendType.MASSEDCOMPUTE
+ BACKEND_CLASS = MassedComputeBackend
+
+ def validate_config(
+ self, config: MassedComputeBackendConfigWithCreds, default_creds_enabled: bool
+ ) -> None:
+ if not MassedComputeAPIClient(config.creds.api_key).validate_api_key():
+ raise_invalid_credentials_error(fields=[["creds", "api_key"]])
+
+ def create_backend(
+ self, project_name: str, config: MassedComputeBackendConfigWithCreds
+ ) -> BackendRecord:
+ return BackendRecord(
+ config=MassedComputeStoredConfig(
+ **validate_extra_ignore(MassedComputeBackendConfig, config).model_dump()
+ ).model_dump_json(),
+ auth=MassedComputeCreds.model_validate(config.creds).model_dump_json(),
+ )
+
+ def get_backend_config_with_creds(
+ self, record: BackendRecord
+ ) -> MassedComputeBackendConfigWithCreds:
+ return validate_extra_ignore(MassedComputeBackendConfigWithCreds, self._get_config(record))
+
+ def get_backend_config_without_creds(
+ self, record: BackendRecord
+ ) -> MassedComputeBackendConfig:
+ return validate_extra_ignore(MassedComputeBackendConfig, self._get_config(record))
+
+ def get_backend(self, record: BackendRecord) -> MassedComputeBackend:
+ return MassedComputeBackend(config=self._get_config(record))
+
+ def _get_config(self, record: BackendRecord) -> MassedComputeConfig:
+ return validate_extra_ignore(
+ MassedComputeConfig,
+ {
+ **json.loads(record.config),
+ "creds": validate_json_extra_ignore(MassedComputeCreds, record.auth),
+ },
+ )
diff --git a/src/dstack/_internal/core/backends/massedcompute/models.py b/src/dstack/_internal/core/backends/massedcompute/models.py
new file mode 100644
index 0000000000..68aa6a4c69
--- /dev/null
+++ b/src/dstack/_internal/core/backends/massedcompute/models.py
@@ -0,0 +1,32 @@
+from typing import Annotated, Literal
+
+from pydantic import Field
+
+from dstack._internal.core.models.common import CoreModel
+
+
+class MassedComputeAPIKeyCreds(CoreModel):
+ type: Annotated[Literal["api_key"], Field(description="The type of credentials")] = "api_key"
+ api_key: Annotated[str, Field(description="The MassedCompute API key", min_length=1)]
+
+
+AnyMassedComputeCreds = MassedComputeAPIKeyCreds
+MassedComputeCreds = AnyMassedComputeCreds
+
+
+class MassedComputeBackendConfig(CoreModel):
+ type: Annotated[Literal["massedcompute"], Field(description="The type of backend")] = (
+ "massedcompute"
+ )
+
+
+class MassedComputeBackendConfigWithCreds(MassedComputeBackendConfig):
+ creds: Annotated[AnyMassedComputeCreds, Field(description="The credentials")]
+
+
+class MassedComputeStoredConfig(MassedComputeBackendConfig):
+ pass
+
+
+class MassedComputeConfig(MassedComputeStoredConfig):
+ creds: AnyMassedComputeCreds
diff --git a/src/dstack/_internal/core/backends/models.py b/src/dstack/_internal/core/backends/models.py
index c18a9d247d..01c8d7943e 100644
--- a/src/dstack/_internal/core/backends/models.py
+++ b/src/dstack/_internal/core/backends/models.py
@@ -63,6 +63,10 @@
LiumBackendConfig,
LiumBackendConfigWithCreds,
)
+from dstack._internal.core.backends.massedcompute.models import (
+ MassedComputeBackendConfig,
+ MassedComputeBackendConfigWithCreds,
+)
from dstack._internal.core.backends.nebius.models import (
NebiusBackendConfig,
NebiusBackendConfigWithCreds,
@@ -118,6 +122,7 @@
KubernetesBackendConfig,
LambdaBackendConfig,
LiumBackendConfig,
+ MassedComputeBackendConfig,
NebiusBackendConfig,
OCIBackendConfig,
RunpodBackendConfig,
@@ -149,6 +154,7 @@
KubernetesBackendConfigWithCreds,
LambdaBackendConfigWithCreds,
LiumBackendConfigWithCreds,
+ MassedComputeBackendConfigWithCreds,
OCIBackendConfigWithCreds,
NebiusBackendConfigWithCreds,
RunpodBackendConfigWithCreds,
@@ -195,6 +201,7 @@ class BackendConfigWithCreds(RootModel[AnyBackendConfigWithCredsTagged]):
KubernetesBackendFileConfigWithCreds,
LambdaBackendConfigWithCreds,
LiumBackendConfigWithCreds,
+ MassedComputeBackendConfigWithCreds,
OCIBackendConfigWithCreds,
NebiusBackendFileConfigWithCreds,
RunpodBackendConfigWithCreds,
diff --git a/src/dstack/_internal/core/compatibility/runs.py b/src/dstack/_internal/core/compatibility/runs.py
index 83e5587e9d..ace77be939 100644
--- a/src/dstack/_internal/core/compatibility/runs.py
+++ b/src/dstack/_internal/core/compatibility/runs.py
@@ -134,7 +134,8 @@ def get_job_submission_excludes(job_submissions: list[JobSubmission]) -> Include
# `Resources.description` is deprecated and never set since 0.21. Not sending it lets 0.22
# drop the field without breaking 0.21 clients.
submission_excludes["job_provisioning_data"] = {
- "instance_type": {"resources": {"description": True}}
+ "instance_type": {"resources": {"description": True}},
+ "volume_mounts": True, # Server-owned host paths are not part of a run apply request.
}
submission_excludes["provider_ref"] = True
return submission_excludes
diff --git a/src/dstack/_internal/core/errors.py b/src/dstack/_internal/core/errors.py
index e2685a64e4..3a25617130 100644
--- a/src/dstack/_internal/core/errors.py
+++ b/src/dstack/_internal/core/errors.py
@@ -106,6 +106,18 @@ class ComputeResourceNotFoundError(ComputeError):
pass
+class VolumeProvisioningError(ComputeError):
+ """Provisioning failed after the provider allocated a volume that still needs deletion."""
+
+ def __init__(self, message: str, volume_id: str):
+ super().__init__(message)
+ self.volume_id = volume_id
+
+
+class VolumeDeletionPending(ComputeError):
+ """The provider has not confirmed volume deletion. Retry without forgetting the volume."""
+
+
class PlacementGroupInUseError(ComputeError):
pass
@@ -120,12 +132,23 @@ class NotYetTerminated(ComputeError):
and the method should be called again after some time to continue termination.
"""
- def __init__(self, details: str) -> None:
+ def __init__(
+ self,
+ details: str,
+ *,
+ instance_id: Optional[str] = None,
+ backend_data: Optional[str] = None,
+ ) -> None:
"""
Args:
details: some details about the termination status
+ instance_id: if set, persist the confirmed provider ID and its backend_data
+ before retrying termination.
+ backend_data: backend data for the confirmed provider ID.
"""
- return super().__init__(details)
+ super().__init__(details)
+ self.instance_id = instance_id
+ self.backend_data = backend_data
class SkipOffer(ComputeError):
diff --git a/src/dstack/_internal/core/models/backends/base.py b/src/dstack/_internal/core/models/backends/base.py
index 9ace18f860..822ec1a82e 100644
--- a/src/dstack/_internal/core/models/backends/base.py
+++ b/src/dstack/_internal/core/models/backends/base.py
@@ -20,6 +20,7 @@ class BackendType(str, enum.Enum):
KUBERNETES (BackendType): Kubernetes
LAMBDA (BackendType): Lambda Cloud
LIUM (BackendType): Lium
+ MASSEDCOMPUTE (BackendType): MassedCompute
NEBIUS (BackendType): Nebius AI Cloud
OCI (BackendType): Oracle Cloud Infrastructure
RUNPOD (BackendType): Runpod Cloud
@@ -48,6 +49,7 @@ class BackendType(str, enum.Enum):
KUBERNETES = "kubernetes"
LAMBDA = "lambda"
LIUM = "lium"
+ MASSEDCOMPUTE = "massedcompute"
REMOTE = "remote"
NEBIUS = "nebius"
OCI = "oci"
diff --git a/src/dstack/_internal/core/models/backends/orphans.py b/src/dstack/_internal/core/models/backends/orphans.py
index c007bf4170..ebb3bcf8ae 100644
--- a/src/dstack/_internal/core/models/backends/orphans.py
+++ b/src/dstack/_internal/core/models/backends/orphans.py
@@ -32,6 +32,8 @@ class ListedResourceGroup(CoreModel):
"""Provider's id of the owner resource (e.g.`JobProvisioningData.instance_id` for the instances).
`None` if the group has only internal resources left.
"""
+ primary_name: Optional[str] = None
+ """Exact provider name if the backend can return it as a provisional instance_id."""
region: Optional[str]
created_at: Optional[datetime]
"""Provider's creation time of the owner resource or, if it's gone, the earliest internal resource.
diff --git a/src/dstack/_internal/core/models/runs.py b/src/dstack/_internal/core/models/runs.py
index 8f11c60e23..fc1a22871f 100644
--- a/src/dstack/_internal/core/models/runs.py
+++ b/src/dstack/_internal/core/models/runs.py
@@ -45,7 +45,7 @@
from dstack._internal.core.models.resources import Memory, ResourcesSpec
from dstack._internal.core.models.services import AnyModel
from dstack._internal.core.models.unix import UnixUser
-from dstack._internal.core.models.volumes import MountPoint
+from dstack._internal.core.models.volumes import MountPoint, Volume
from dstack._internal.utils import common as common_utils
from dstack._internal.utils.common import format_pretty_duration
@@ -352,6 +352,8 @@ class JobProvisioningData(CoreModel):
ssh_proxy: Optional[SSHConnectionParams] = None
backend_data: Optional[str] = None
"""`backend_data` stores backend-specific data in JSON."""
+ volume_mounts: Optional[dict[str, str]] = None
+ """Provider volume IDs and their verified host mount paths for volumes selected at launch."""
gpu_driver: Optional[GpuDriverInfo] = None
"""`gpu_driver` is the accelerator driver installed on the host, when known.
Detected via the shim for VM-based backends and SSH fleets; taken from the
@@ -359,6 +361,16 @@ class JobProvisioningData(CoreModel):
after provisioning.
"""
+ def can_mount_volume(self, volume: Volume) -> bool:
+ """Check the location and any volume that had to be attached when this VM was created."""
+ if not volume.matches_location(self.get_base_backend(), self.region):
+ return False
+ if volume.exclusive_at_launch:
+ return any(
+ a.instance.instance_id == self.instance_id for a in volume.attachments or []
+ )
+ return True
+
def get_base_backend(self) -> BackendType:
if self.base_backend is not None:
return self.base_backend
diff --git a/src/dstack/_internal/core/models/volumes.py b/src/dstack/_internal/core/models/volumes.py
index 41ed12feed..3106666f94 100644
--- a/src/dstack/_internal/core/models/volumes.py
+++ b/src/dstack/_internal/core/models/volumes.py
@@ -187,6 +187,12 @@ class DaytonaVolumeConfiguration(VolumeConfigurationWithVolumeID):
)
+class MassedComputeVolumeConfiguration(VolumeConfigurationWithVolumeID):
+ backend: Annotated[
+ Literal[BackendType.MASSEDCOMPUTE], Field(description="The volume backend")
+ ] = BackendType.MASSEDCOMPUTE
+
+
class LiumVolumeConfiguration(VolumeConfigurationWithVolumeID):
backend: Annotated[Literal[BackendType.LIUM], Field(description="The volume backend")] = (
BackendType.LIUM
@@ -200,6 +206,7 @@ class LiumVolumeConfiguration(VolumeConfigurationWithVolumeID):
KubernetesVolumeConfiguration,
DaytonaVolumeConfiguration,
LiumVolumeConfiguration,
+ MassedComputeVolumeConfiguration,
]
@@ -232,6 +239,10 @@ class VolumeProvisioningData(CoreModel):
attachable: bool = True
"""`attachable` shows whether the volume should be attached and detached manually."""
detachable: bool = True
+ exclusive_at_launch: bool = False
+ """Reserve the volume for one instance before launch and hold it until instance termination."""
+ mount_path: Optional[str] = None
+ """Host path of a filesystem already mounted by the provider."""
backend_data: Optional[str] = None
"""`backend_data` stores backend-specific data in JSON."""
@@ -283,6 +294,10 @@ def get_attachment_data_for_instance(self, instance_id: str) -> Optional[VolumeA
# volume was attached before attachments were introduced
return self.attachment_data
+ @property
+ def exclusive_at_launch(self) -> bool:
+ return self.provisioning_data is not None and self.provisioning_data.exclusive_at_launch
+
def get_backend(self) -> BackendType:
return self.configuration.backend
diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/__init__.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/__init__.py
index d3db85274f..cdb6c513b5 100644
--- a/src/dstack/_internal/server/background/pipeline_tasks/instances/__init__.py
+++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/__init__.py
@@ -4,7 +4,7 @@
from datetime import timedelta
from typing import Optional, Sequence
-from sqlalchemy import and_, not_, or_, select, update
+from sqlalchemy import Select, and_, delete, not_, or_, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload, load_only
@@ -45,6 +45,7 @@
InstanceModel,
JobModel,
ProjectModel,
+ VolumeAttachmentModel,
)
from dstack._internal.server.services import events
from dstack._internal.server.services.instances import (
@@ -317,10 +318,8 @@ class _ProcessContext:
async def _process_pending_item(item: InstancePipelineItem) -> Optional[_ProcessContext]:
async with get_session_ctx() as session:
- instance_model = await _refetch_locked_instance_for_pending_or_terminating(
- session=session,
- item=item,
- )
+ res = await session.execute(_select_pending_or_terminating_instance(item))
+ instance_model = res.unique().scalar_one_or_none()
if instance_model is None:
log_lock_token_mismatch(logger, item)
return None
@@ -369,21 +368,26 @@ async def _process_busy_item(item: InstancePipelineItem) -> Optional[_ProcessCon
async def _process_terminating_item(item: InstancePipelineItem) -> Optional[_ProcessContext]:
async with get_session_ctx() as session:
- instance_model = await _refetch_locked_instance_for_pending_or_terminating(
- session=session,
- item=item,
+ res = await session.execute(
+ _select_pending_or_terminating_instance(item).add_columns(
+ InstanceModel.volume_attachments.any(
+ VolumeAttachmentModel.exclusive_volume_id.is_not(None)
+ )
+ )
)
- if instance_model is None:
+ row = res.unique().one_or_none()
+ if row is None:
log_lock_token_mismatch(logger, item)
return None
- result = await terminate_instance(instance_model)
+ instance_model, has_exclusive_volumes = row
+ result = await terminate_instance(instance_model, has_exclusive_volumes)
return _ProcessContext(instance_model=instance_model, result=result)
-async def _refetch_locked_instance_for_pending_or_terminating(
- session: AsyncSession, item: InstancePipelineItem
-) -> Optional[InstanceModel]:
- res = await session.execute(
+def _select_pending_or_terminating_instance(
+ item: InstancePipelineItem,
+) -> Select[InstanceModel]:
+ return (
select(InstanceModel)
.where(
InstanceModel.id == item.id,
@@ -393,7 +397,6 @@ async def _refetch_locked_instance_for_pending_or_terminating(
.options(joinedload(InstanceModel.jobs).load_only(JobModel.id, JobModel.status))
.options(joinedload(InstanceModel.fleet))
)
- return res.unique().scalar_one_or_none()
async def _refetch_locked_instance_for_idle(
@@ -478,6 +481,13 @@ async def _apply_process_result(
),
)
+ if result.release_volume_attachments:
+ await session.execute(
+ delete(VolumeAttachmentModel).where(
+ VolumeAttachmentModel.instance_id == instance_model.id,
+ VolumeAttachmentModel.exclusive_volume_id.is_not(None),
+ )
+ )
emit_instance_status_change_event(
session=session,
instance_model=instance_model,
diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py
index 76874b5f62..178acd96e4 100644
--- a/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py
+++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/check.py
@@ -59,6 +59,7 @@
)
from dstack._internal.server.services.logging import fmt
from dstack._internal.server.services.runner import client as runner_client
+from dstack._internal.server.services.runner.pool import instance_connection_pool
from dstack._internal.server.services.runner.ssh import runner_ssh_tunnel
from dstack._internal.utils.common import get_current_datetime, get_or_error, run_async
from dstack._internal.utils.logging import get_logger
@@ -357,6 +358,20 @@ async def _process_wait_for_instance_provisioning_data(
instance_model.project.ssh_public_key,
instance_model.project.ssh_private_key,
)
+ if job_provisioning_data.hostname and job_provisioning_data.volume_mounts:
+ # Publishing the SSH address admits jobs. Keep it unset while any mount is
+ # missing so a VM that times out before admission can be deleted without a flush.
+ conn = await run_async(
+ instance_connection_pool.get_or_open,
+ get_instance_ssh_private_keys(instance_model),
+ job_provisioning_data,
+ None,
+ )
+ if conn is None:
+ return result
+ if not await conn.has_volume_mounts(job_provisioning_data.volume_mounts.values()):
+ await run_async(instance_connection_pool.drop_by_jpd, job_provisioning_data)
+ return result
result.instance_update_map["job_provisioning_data"] = (
job_provisioning_data.model_dump_json()
)
diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/common.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/common.py
index c472cd062a..6dc60632d7 100644
--- a/src/dstack/_internal/server/background/pipeline_tasks/instances/common.py
+++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/common.py
@@ -67,6 +67,7 @@ class HealthCheckCreate(TypedDict):
@dataclass
class ProcessResult:
instance_update_map: InstanceUpdateMap = field(default_factory=InstanceUpdateMap)
+ release_volume_attachments: bool = False
health_check_create: Optional[HealthCheckCreate] = None
new_placement_group_models: list[PlacementGroupModel] = field(default_factory=list)
schedule_pg_deletion_fleet_id: Optional[uuid.UUID] = None
diff --git a/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py b/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py
index 9e4305c830..0f8a573992 100644
--- a/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py
+++ b/src/dstack/_internal/server/background/pipeline_tasks/instances/termination.py
@@ -1,5 +1,6 @@
+from dstack._internal.core.backends.base.compute import ComputeWithVolumeSupport
from dstack._internal.core.backends.features import get_backends_with_resource_listing_support
-from dstack._internal.core.errors import BackendError, NotYetTerminated
+from dstack._internal.core.errors import BackendError, NotYetTerminated, SSHError
from dstack._internal.core.models.backends.base import BackendType
from dstack._internal.core.models.backends.orphans import OrphanCleanupMode
from dstack._internal.core.models.instances import InstanceStatus
@@ -14,7 +15,10 @@
)
from dstack._internal.server.models import InstanceModel
from dstack._internal.server.services.backends import cache as backends_cache
-from dstack._internal.server.services.instances import get_instance_provisioning_data
+from dstack._internal.server.services.instances import (
+ get_instance_provisioning_data,
+ get_instance_ssh_private_keys,
+)
from dstack._internal.server.services.runner.pool import (
instance_connection_pool,
)
@@ -24,7 +28,9 @@
logger = get_logger(__name__)
-async def terminate_instance(instance_model: InstanceModel) -> ProcessResult:
+async def terminate_instance(
+ instance_model: InstanceModel, has_exclusive_volumes: bool
+) -> ProcessResult:
result = ProcessResult()
now = get_current_datetime()
if (
@@ -36,8 +42,19 @@ async def terminate_instance(instance_model: InstanceModel) -> ProcessResult:
job_provisioning_data = get_instance_provisioning_data(instance_model)
if job_provisioning_data is not None and job_provisioning_data.backend != BackendType.REMOTE:
try:
- await _terminate_in_backend(instance_model, job_provisioning_data)
+ await _terminate_in_backend(
+ instance_model, job_provisioning_data, has_exclusive_volumes
+ )
+ result.release_volume_attachments = has_exclusive_volumes
except Exception as exc:
+ if isinstance(exc, NotYetTerminated) and exc.instance_id is not None:
+ job_provisioning_data.instance_id = exc.instance_id
+ job_provisioning_data.backend_data = exc.backend_data
+ result.instance_update_map["job_provisioning_data"] = (
+ job_provisioning_data.model_dump_json()
+ )
+ result.instance_update_map["first_termination_retry_at"] = NOW_PLACEHOLDER
+ return result
first_retry_at = instance_model.first_termination_retry_at
if first_retry_at is None:
first_retry_at = now
@@ -58,6 +75,20 @@ async def terminate_instance(instance_model: InstanceModel) -> ProcessResult:
exc_info=not isinstance(exc, BackendError),
)
return result
+ if has_exclusive_volumes:
+ # Giving up here would release a single-writer volume while its VM may still exist.
+ if not isinstance(exc, NotYetTerminated) and (
+ instance_model.last_termination_retry_at is None
+ or next_termination_retry_at(instance_model.last_termination_retry_at)
+ < get_termination_deadline(first_retry_at)
+ ):
+ result.event_messages.append(
+ "Volume attachments retained until dstack confirms the VM is gone. "
+ "dstack will keep retrying. "
+ f"Last error: {_format_error(exc)}"
+ )
+ logger.warning("Instance %s termination pending: %r", instance_model.name, exc)
+ return result
next_step = "Please terminate the instance manually to avoid unexpected charges."
if _is_to_be_deleted_by_orphan_cleanup(instance_model, job_provisioning_data):
next_step = "Orphan cleanup will retry deleting the instance."
@@ -88,22 +119,43 @@ async def terminate_instance(instance_model: InstanceModel) -> ProcessResult:
async def _terminate_in_backend(
- instance_model: InstanceModel, job_provisioning_data: JobProvisioningData
+ instance_model: InstanceModel,
+ job_provisioning_data: JobProvisioningData,
+ has_exclusive_volumes: bool,
):
async with backends_cache.lease_project_backend_by_type(
project=instance_model.project,
backend_type=job_provisioning_data.backend,
) as backend:
if backend is None:
+ if has_exclusive_volumes:
+ raise BackendError("Backend unavailable while terminating a VM with volumes")
logger.error(
"Failed to terminate instance %s. Backend %s not available.",
instance_model.name,
job_provisioning_data.backend,
)
return
+ compute = backend.compute()
+ if job_provisioning_data.volume_mounts and job_provisioning_data.hostname:
+ assert isinstance(compute, ComputeWithVolumeSupport)
+ paths = await run_async(compute.get_volume_mounts_to_sync, job_provisioning_data)
+ if paths:
+ conn = await run_async(
+ instance_connection_pool.get_or_open,
+ get_instance_ssh_private_keys(instance_model),
+ job_provisioning_data,
+ None,
+ )
+ if conn is None:
+ raise BackendError("Could not connect to the VM to flush its volumes")
+ try:
+ await conn.sync_volume_mounts(paths)
+ except SSHError as e:
+ raise BackendError("Could not flush the VM's volume mounts") from e
logger.debug("Terminating runner instance %s", job_provisioning_data.hostname)
await run_async(
- backend.compute().terminate_instance,
+ compute.terminate_instance,
job_provisioning_data.instance_id,
job_provisioning_data.region,
job_provisioning_data.backend_data,
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 f303525ee0..09230490d3 100644
--- a/src/dstack/_internal/server/background/pipeline_tasks/jobs_submitted.py
+++ b/src/dstack/_internal/server/background/pipeline_tasks/jobs_submitted.py
@@ -6,7 +6,8 @@
from datetime import timedelta
from typing import Optional, Sequence, Union
-from sqlalchemy import and_, func, or_, select, update
+from sqlalchemy import and_, func, or_, select, tuple_, update
+from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import aliased, contains_eager, joinedload, load_only, selectinload
@@ -52,7 +53,7 @@
Requirements,
Run,
)
-from dstack._internal.core.models.volumes import Volume
+from dstack._internal.core.models.volumes import Volume, VolumeStatus
from dstack._internal.core.services.profiles import get_termination
from dstack._internal.server import settings
from dstack._internal.server.background.pipeline_tasks.base import (
@@ -284,6 +285,23 @@ async def fetch(self, limit: int) -> list[JobSubmittedPipelineItem]:
)
)
job_models = list(res.scalars().all())
+ # A worker can die after locking volume candidates but before applying its result.
+ # Release its related leases in the same transaction that replaces its job token.
+ expired_volume_leases = [
+ (_get_related_volume_lock_owner(job_model.id), job_model.lock_token)
+ for job_model in job_models
+ if job_model.lock_expires_at is not None and job_model.lock_token is not None
+ ]
+ if expired_volume_leases:
+ await session.execute(
+ update(VolumeModel)
+ .where(
+ tuple_(VolumeModel.lock_owner, VolumeModel.lock_token).in_(
+ expired_volume_leases
+ )
+ )
+ .values(lock_expires_at=None, lock_owner=None, lock_token=None)
+ )
lock_expires_at = get_current_datetime() + self._lock_timeout
lock_token = uuid.uuid4()
items = []
@@ -414,7 +432,8 @@ class _TerminateSubmittedJobResult:
@dataclass
class _VolumeAttachmentPayload:
volume_id: uuid.UUID
- attachment_data: str
+ attachment_data: Optional[str]
+ """None when the attachment was already recorded at launch."""
volume_name: str
@@ -1940,6 +1959,16 @@ async def _process_volume_attachments(
and volume_model.lock_owner != related_volume_lock_owner
):
raise ServerClientError("Cannot attach a volume locked for processing")
+ if volume.exclusive_at_launch:
+ if any(
+ a.instance_id == job_model.instance_id
+ for a in volume_model.attachments
+ ):
+ attachments.append(
+ _VolumeAttachmentPayload(volume.id, None, volume.name)
+ )
+ break
+ continue
if (
job_provisioning_data.get_base_backend() != volume.get_backend()
or job_provisioning_data.region.lower() != volume.get_region().lower()
@@ -2003,9 +2032,19 @@ async def _lock_related_volume_models(
return []
related_volume_lock_owner = _get_related_volume_lock_owner(item.id)
- volume_lock, _ = get_locker(get_db().dialect_name).get_lockset(VolumeModel.__tablename__)
- async with volume_lock:
+ locker = get_locker(get_db().dialect_name)
+ job_lock, _ = locker.get_lockset(JobModel.__tablename__)
+ volume_lock, _ = locker.get_lockset(VolumeModel.__tablename__)
+ async with job_lock, volume_lock:
async with get_session_ctx() as session:
+ # A provider call may have returned to a worker whose job was already reclaimed.
+ job_id = await session.scalar(
+ select(JobModel.id)
+ .where(JobModel.id == item.id, JobModel.lock_token == item.lock_token)
+ .with_for_update(key_share=True)
+ )
+ if job_id is None:
+ return None
# Persist related volume locks before attach because the attach call itself
# must run outside a DB transaction in the processing phase.
res = await session.execute(
@@ -2134,6 +2173,8 @@ async def _apply_volume_attachment_result(
.values(last_job_processed_at=now)
)
for attachment in volume_attachment_result.attachments:
+ if attachment.attachment_data is None:
+ continue
session.add(
VolumeAttachmentModel(
volume_id=attachment.volume_id,
@@ -2441,6 +2482,7 @@ async def _provision_new_capacity(
fleet_model=fleet_model,
)
multinode = requirements.multinode or is_multinode_job(job)
+ has_exclusive_volumes = any(v.exclusive_at_launch for vs in volumes for v in vs)
# New instances belong to the fleet's project, which differs from
# the job's project if the fleet is imported.
fleet_project = fleet_model.project
@@ -2527,6 +2569,10 @@ async def _provision_new_capacity(
use_group_provisioning = (
offer.backend in BACKENDS_WITH_GROUP_PROVISIONING_SUPPORT and len(jobs) > 1
)
+ if has_exclusive_volumes and job_model.instance_id is not None:
+ await _reserve_launch_volumes(job_model, offer_volumes)
+ elif any(v.exclusive_at_launch for v in offer_volumes):
+ raise SkipOffer("An exclusive volume requires an instance to reserve it")
if use_group_provisioning:
assert isinstance(compute, ComputeWithGroupProvisioningSupport)
compute_group_provisioning_data = await run_async(
@@ -2762,6 +2808,71 @@ def _get_effective_profile_and_requirements(
return effective_profile, requirements
+async def _reserve_launch_volumes(job: JobModel, volumes: list[Volume]) -> None:
+ """Reserve exclusive volumes on the job's placeholder before calling the cloud.
+
+ Retrying the same placement keeps its attachments. Trying another offer replaces them
+ atomically. The unique provider ID also excludes concurrent launches through an alias.
+ """
+ selected = {v.id: v for v in volumes if v.exclusive_at_launch}
+ ids = sorted(selected)
+ locker = get_locker(get_db().dialect_name)
+ job_lock, _ = locker.get_lockset(JobModel.__tablename__)
+ volume_lock, locked_ids = locker.get_lockset(VolumeModel.__tablename__)
+ async with job_lock, volume_lock, get_session_ctx() as session:
+ if any(volume_id in locked_ids for volume_id in ids):
+ raise SkipOffer("A requested volume is being processed")
+ # A worker whose lease was lost must not replace the successor's reservations.
+ owner = await session.scalar(
+ select(JobModel.instance_id)
+ .where(JobModel.id == job.id, JobModel.lock_token == job.lock_token)
+ .with_for_update(key_share=True)
+ )
+ if owner is None or owner != job.instance_id:
+ raise SkipOffer("The job no longer owns the instance for volume attachment")
+ available = await session.scalars(
+ select(VolumeModel.id)
+ .where(
+ VolumeModel.id.in_(ids),
+ VolumeModel.status == VolumeStatus.ACTIVE,
+ VolumeModel.deleted.is_(False),
+ VolumeModel.to_be_deleted.is_(False),
+ VolumeModel.lock_expires_at.is_(None),
+ )
+ .order_by(VolumeModel.id)
+ .with_for_update(key_share=True)
+ )
+ if set(available) != set(ids):
+ raise SkipOffer("A requested volume is no longer available")
+ owned = await session.scalars(
+ select(VolumeAttachmentModel).where(
+ VolumeAttachmentModel.instance_id == owner,
+ VolumeAttachmentModel.exclusive_volume_id.is_not(None),
+ )
+ )
+ for attachment in owned:
+ if attachment.volume_id in selected:
+ del selected[attachment.volume_id]
+ else:
+ await session.delete(attachment)
+ await session.flush()
+ reservations = [
+ VolumeAttachmentModel(
+ instance_id=owner,
+ volume_id=volume.id,
+ exclusive_volume_id=f"{volume.get_backend().value}/{get_or_error(volume.volume_id)}",
+ )
+ for volume in selected.values()
+ ]
+ # Aliases have different local IDs. Acquire the unique provider keys in the same order.
+ reservations.sort(key=lambda a: get_or_error(a.exclusive_volume_id))
+ session.add_all(reservations)
+ try:
+ await session.commit()
+ except IntegrityError as e:
+ raise SkipOffer("A requested volume is already reserved by another instance") from e
+
+
def _get_offer_volumes(
volumes: list[list[Volume]],
offer: InstanceOfferWithAvailability,
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 06853f9a4e..5f970abe7b 100644
--- a/src/dstack/_internal/server/background/pipeline_tasks/jobs_terminating.py
+++ b/src/dstack/_internal/server/background/pipeline_tasks/jobs_terminating.py
@@ -435,7 +435,11 @@ async def _load_job_volume_models(
volume_names = (
jrd.volume_names
if jrd and jrd.volume_names
- else [va.volume.name for va in instance_model.volume_attachments]
+ else [
+ va.volume.name
+ for va in instance_model.volume_attachments
+ if va.exclusive_volume_id is None or jrd is None or jrd.volume_names is None
+ ]
)
if len(volume_names) == 0:
return []
@@ -535,6 +539,19 @@ async def _apply_process_result(
await skip_gateway_replicas_min_processing_interval(session, job_model.run.gateway_id)
if instance_model is not None and result.delete_instance:
+ # Release a failed launch's reservations before removing its placeholder.
+ await session.execute(
+ delete(VolumeAttachmentModel).where(
+ VolumeAttachmentModel.exclusive_volume_id.is_not(None),
+ VolumeAttachmentModel.instance_id.in_(
+ select(InstanceModel.id).where(
+ InstanceModel.id == instance_model.id,
+ InstanceModel.lock_token == item.lock_token,
+ InstanceModel.lock_owner == related_instance_lock_owner,
+ )
+ ),
+ )
+ )
res = await session.execute(
delete(InstanceModel)
.where(
@@ -956,7 +973,6 @@ async def _detach_job_volumes(
if job_provisioning_data is None:
return volume_update_rows, _VolumeDetachResult(all_detached=True)
- logger.info("Detaching volumes: %s", [v.name for v in volume_models])
detach_result = await _detach_volumes_from_job_instance(
job_model=job_model,
instance_model=instance_model,
@@ -1055,6 +1071,23 @@ async def _detach_volumes_from_job_instance(
jpd: JobProvisioningData,
run_termination_reason: Optional[RunTerminationReason],
) -> _VolumeDetachResult:
+ # Launch-time attachments belong to the VM until termination. The job only releases
+ # its assignment, including when its backend is no longer configured.
+ volumes_to_detach = [
+ v
+ for v in volume_models
+ if not any(
+ a.instance_id == instance_model.id and a.exclusive_volume_id is not None
+ for a in v.attachments
+ )
+ ]
+ result = _VolumeDetachResult(
+ all_detached=True, set_volumes_detached_at=job_model.volumes_detached_at is None
+ )
+ if not volumes_to_detach:
+ return result
+
+ logger.info("Detaching volumes: %s", [v.name for v in volumes_to_detach])
job_spec = get_job_spec(job_model)
async with backends_cache.lease_project_backend_by_type(
project=instance_model.project,
@@ -1066,9 +1099,7 @@ async def _detach_volumes_from_job_instance(
)
return _VolumeDetachResult(all_detached=False)
- detached_volume_ids = set()
- all_detached = True
- for volume_model in volume_models:
+ for volume_model in volumes_to_detach:
detached = await _detach_volume_from_job_instance(
backend=backend,
job_model=job_model,
@@ -1079,15 +1110,11 @@ async def _detach_volumes_from_job_instance(
run_termination_reason=run_termination_reason,
)
if detached:
- detached_volume_ids.add(volume_model.id)
+ result.detached_volume_ids.add(volume_model.id)
else:
- all_detached = False
+ result.all_detached = False
- return _VolumeDetachResult(
- all_detached=all_detached,
- detached_volume_ids=detached_volume_ids,
- set_volumes_detached_at=job_model.volumes_detached_at is None,
- )
+ return result
async def _detach_volume_from_job_instance(
diff --git a/src/dstack/_internal/server/background/pipeline_tasks/orphan_cleanup.py b/src/dstack/_internal/server/background/pipeline_tasks/orphan_cleanup.py
index 121b6bfa1c..d3da0cda3c 100644
--- a/src/dstack/_internal/server/background/pipeline_tasks/orphan_cleanup.py
+++ b/src/dstack/_internal/server/background/pipeline_tasks/orphan_cleanup.py
@@ -728,7 +728,8 @@ def _get_instance_group_decision(
return _ResourceGroupDecision.IGNORE
if (
provisioning_data.get_base_backend() != resource_group.backend
- or provisioning_data.instance_id != resource_group.primary_id
+ or provisioning_data.instance_id
+ not in (resource_group.primary_id, resource_group.primary_name)
):
# The listing may predate the provisioning: the instance may be missing from it
# while its internal resources created earlier are listed.
diff --git a/src/dstack/_internal/server/background/pipeline_tasks/volumes.py b/src/dstack/_internal/server/background/pipeline_tasks/volumes.py
index 23189fd79d..e0229693d7 100644
--- a/src/dstack/_internal/server/background/pipeline_tasks/volumes.py
+++ b/src/dstack/_internal/server/background/pipeline_tasks/volumes.py
@@ -8,8 +8,12 @@
from sqlalchemy.orm import joinedload, load_only
from dstack._internal.core.backends.base.compute import ComputeWithVolumeSupport
-from dstack._internal.core.errors import BackendError
-from dstack._internal.core.models.volumes import VolumeStatus
+from dstack._internal.core.errors import (
+ BackendError,
+ VolumeDeletionPending,
+ VolumeProvisioningError,
+)
+from dstack._internal.core.models.volumes import VolumeProvisioningData, VolumeStatus
from dstack._internal.server.background.pipeline_tasks.base import (
NOW_PLACEHOLDER,
Fetcher,
@@ -274,7 +278,7 @@ async def _apply_process_result(
# TODO: Clean up volume.
pass
return
- if item.to_be_deleted:
+ if update_map.get("deleted"):
events.emit(
session,
"Volume deleted",
@@ -338,6 +342,16 @@ async def _process_submitted_volume(volume_model: VolumeModel) -> _ProcessResult
compute.create_volume,
volume=volume,
)
+ except VolumeProvisioningError as e:
+ return _ProcessResult(
+ update_map={
+ "status": VolumeStatus.FAILED,
+ "status_message": str(e),
+ "volume_provisioning_data": VolumeProvisioningData(
+ backend=volume.get_backend(), volume_id=e.volume_id, size_gb=None
+ ).model_dump_json(),
+ }
+ )
except BackendError as e:
logger.info("Failed to create volume %s: %s", volume_model.name, repr(e))
status_message = f"Backend error: {repr(e)}"
@@ -399,6 +413,9 @@ async def _process_to_be_deleted_volume(volume_model: VolumeModel) -> _ProcessRe
compute.delete_volume,
volume=volume,
)
+ except VolumeDeletionPending as e:
+ logger.info("Volume %s deletion pending: %s", volume.name, e)
+ return _ProcessResult(update_map={"status_message": str(e)})
except Exception:
# TODO: Retry deletion
logger.exception(
diff --git a/src/dstack/_internal/server/migrations/versions/2026/11_25_1606_48487e02b247_add_exclusive_volume_attachment_id.py b/src/dstack/_internal/server/migrations/versions/2026/11_25_1606_48487e02b247_add_exclusive_volume_attachment_id.py
new file mode 100644
index 0000000000..d21c44fa63
--- /dev/null
+++ b/src/dstack/_internal/server/migrations/versions/2026/11_25_1606_48487e02b247_add_exclusive_volume_attachment_id.py
@@ -0,0 +1,27 @@
+"""Add exclusive volume attachment ID
+
+Revision ID: 48487e02b247
+Revises: 17e6c7ef91dd
+Create Date: 2026-11-25 16:06:28.559512+00:00
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision = "48487e02b247"
+down_revision = "17e6c7ef91dd"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "volumes_attachments", sa.Column("exclusive_volume_id", sa.String(255), nullable=True)
+ )
+
+
+def downgrade() -> None:
+ with op.batch_alter_table("volumes_attachments") as batch_op:
+ batch_op.drop_column("exclusive_volume_id")
diff --git a/src/dstack/_internal/server/migrations/versions/2026/11_25_1607_fe7552e4c072_index_exclusive_volume_attachments.py b/src/dstack/_internal/server/migrations/versions/2026/11_25_1607_fe7552e4c072_index_exclusive_volume_attachments.py
new file mode 100644
index 0000000000..e6bb920b3a
--- /dev/null
+++ b/src/dstack/_internal/server/migrations/versions/2026/11_25_1607_fe7552e4c072_index_exclusive_volume_attachments.py
@@ -0,0 +1,32 @@
+"""Index exclusive volume attachments
+
+Revision ID: fe7552e4c072
+Revises: 48487e02b247
+Create Date: 2026-11-25 16:07:18.986578+00:00
+
+"""
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision = "fe7552e4c072"
+down_revision = "48487e02b247"
+branch_labels = None
+depends_on = None
+
+
+TABLE = "volumes_attachments"
+INDEX = "ix_volumes_attachments_exclusive_volume_id"
+
+
+def upgrade() -> None:
+ with op.get_context().autocommit_block():
+ op.drop_index(INDEX, table_name=TABLE, if_exists=True, postgresql_concurrently=True)
+ op.create_index(
+ INDEX, TABLE, ["exclusive_volume_id"], unique=True, postgresql_concurrently=True
+ )
+
+
+def downgrade() -> None:
+ with op.get_context().autocommit_block():
+ op.drop_index(INDEX, table_name=TABLE, if_exists=True, postgresql_concurrently=True)
diff --git a/src/dstack/_internal/server/migrations/versions/2026/11_25_1707_26bb6dd37157_index_exclusive_volumes_by_instance.py b/src/dstack/_internal/server/migrations/versions/2026/11_25_1707_26bb6dd37157_index_exclusive_volumes_by_instance.py
new file mode 100644
index 0000000000..7e79d69aac
--- /dev/null
+++ b/src/dstack/_internal/server/migrations/versions/2026/11_25_1707_26bb6dd37157_index_exclusive_volumes_by_instance.py
@@ -0,0 +1,39 @@
+"""Index exclusive volumes by instance
+
+Revision ID: 26bb6dd37157
+Revises: fe7552e4c072
+Create Date: 2026-11-25 17:07:38.094670+00:00
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision = "26bb6dd37157"
+down_revision = "fe7552e4c072"
+branch_labels = None
+depends_on = None
+
+
+TABLE = "volumes_attachments"
+INDEX = "ix_volumes_attachments_exclusive_instance_id"
+
+
+def upgrade() -> None:
+ condition = sa.text("exclusive_volume_id IS NOT NULL")
+ with op.get_context().autocommit_block():
+ op.drop_index(INDEX, table_name=TABLE, if_exists=True, postgresql_concurrently=True)
+ op.create_index(
+ INDEX,
+ TABLE,
+ ["instance_id"],
+ postgresql_where=condition,
+ sqlite_where=condition,
+ postgresql_concurrently=True,
+ )
+
+
+def downgrade() -> None:
+ with op.get_context().autocommit_block():
+ op.drop_index(INDEX, table_name=TABLE, if_exists=True, postgresql_concurrently=True)
diff --git a/src/dstack/_internal/server/models.py b/src/dstack/_internal/server/models.py
index 79a1a9f56e..d03c460fcc 100644
--- a/src/dstack/_internal/server/models.py
+++ b/src/dstack/_internal/server/models.py
@@ -1151,6 +1151,19 @@ class VolumeAttachmentModel(BaseModel):
instance_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("instances.id"), primary_key=True)
instance: Mapped[InstanceModel] = relationship(back_populates="volume_attachments")
attachment_data: Mapped[Optional[str]] = mapped_column(Text)
+ exclusive_volume_id: Mapped[Optional[str]] = mapped_column(
+ String(255), unique=True, index=True
+ )
+ """Backend and provider volume ID for an exclusive launch-time attachment, including external aliases."""
+
+ __table_args__ = (
+ Index(
+ "ix_volumes_attachments_exclusive_instance_id",
+ instance_id,
+ postgresql_where=exclusive_volume_id.is_not(None),
+ sqlite_where=exclusive_volume_id.is_not(None),
+ ),
+ )
class PlacementGroupModel(PipelineModelMixin, BaseModel):
diff --git a/src/dstack/_internal/server/schemas/runner.py b/src/dstack/_internal/server/schemas/runner.py
index 3a3aac4a0a..f31d104960 100644
--- a/src/dstack/_internal/server/schemas/runner.py
+++ b/src/dstack/_internal/server/schemas/runner.py
@@ -2,7 +2,7 @@
from enum import Enum
from typing import Any, Dict, List, Optional, Union
-from pydantic import field_validator
+from pydantic import Field, field_validator
from dstack._internal.core.models.common import CoreModel, NetworkMode
from dstack._internal.core.models.repos.remote import RemoteRepoCreds
@@ -198,6 +198,7 @@ class ShimVolumeInfo(CoreModel):
volume_id: str
init_fs: bool
device_name: Optional[str] = None
+ mount_path: Optional[str] = Field(default=None, exclude_if=lambda v: v is None)
class PortMapping(CoreModel):
diff --git a/src/dstack/_internal/server/services/instances.py b/src/dstack/_internal/server/services/instances.py
index 734fc63734..6e530af38f 100644
--- a/src/dstack/_internal/server/services/instances.py
+++ b/src/dstack/_internal/server/services/instances.py
@@ -671,6 +671,12 @@ def filter_instances(
continue
if volumes_locations is not None:
jpd = get_instance_provisioning_data(instance)
+ if (
+ jpd is None
+ and volumes
+ and any(all(v.exclusive_at_launch for v in candidates) for candidates in volumes)
+ ):
+ continue
# instance_matches_constraints() also skips filtering if JPD is not set
if jpd is not None:
instance_backend = jpd.get_base_backend()
@@ -685,6 +691,10 @@ def filter_instances(
and regionless_location not in volumes_locations
):
continue
+ if volumes and any(
+ not any(jpd.can_mount_volume(v) for v in candidates) for candidates in volumes
+ ):
+ continue
filtered_instances.append(instance)
return filtered_instances
diff --git a/src/dstack/_internal/server/services/jobs/__init__.py b/src/dstack/_internal/server/services/jobs/__init__.py
index a9dfc2dfe1..698c2875e7 100644
--- a/src/dstack/_internal/server/services/jobs/__init__.py
+++ b/src/dstack/_internal/server/services/jobs/__init__.py
@@ -600,9 +600,7 @@ def _get_job_mount_point_attached_volume(
Returns the volume attached to the job among the list of possible mount point volumes.
"""
for volume in volumes:
- if not volume.matches_location(
- job_provisioning_data.get_base_backend(), job_provisioning_data.region
- ):
+ if not job_provisioning_data.can_mount_volume(volume):
continue
if (
(volume_availability_zone := volume.get_availability_zone()) is not None
diff --git a/src/dstack/_internal/server/services/runner/client.py b/src/dstack/_internal/server/services/runner/client.py
index 10ae8ff138..0690f8d94f 100644
--- a/src/dstack/_internal/server/services/runner/client.py
+++ b/src/dstack/_internal/server/services/runner/client.py
@@ -846,12 +846,14 @@ def _volume_to_shim_volume_info(volume: Volume, instance_id: str) -> ShimVolumeI
attachment_data = volume.get_attachment_data_for_instance(instance_id)
if attachment_data is not None:
device_name = attachment_data.device_name
+ mount_path = volume.provisioning_data.mount_path if volume.provisioning_data else None
return ShimVolumeInfo(
backend=volume.configuration.backend.value,
name=volume.name,
volume_id=get_or_error(volume.volume_id),
- init_fs=not volume.external,
+ init_fs=not volume.external and mount_path is None,
device_name=device_name,
+ mount_path=mount_path,
)
diff --git a/src/dstack/_internal/server/services/runner/pool.py b/src/dstack/_internal/server/services/runner/pool.py
index 93ba015f70..694da3f98d 100644
--- a/src/dstack/_internal/server/services/runner/pool.py
+++ b/src/dstack/_internal/server/services/runner/pool.py
@@ -1,4 +1,5 @@
import os
+import shlex
import shutil
import threading
import time
@@ -238,6 +239,24 @@ def open(self) -> None:
self._tunnel.open()
self._last_verified_at = time.monotonic()
+ async def has_volume_mounts(self, paths: Collection[str]) -> bool:
+ """Check whether the host has mounted all requested filesystems."""
+ try:
+ await self._tunnel.aexec(
+ " && ".join(f"mountpoint -q -- {shlex.quote(p)}" for p in paths)
+ )
+ except SSHError:
+ return False
+ return True
+
+ async def sync_volume_mounts(self, paths: Collection[str]) -> None:
+ """Wait for each host mount to flush before releasing its VM."""
+ commands = [
+ f"mountpoint -q -- {shlex.quote(path)} && sync -- {shlex.quote(path)}"
+ for path in paths
+ ]
+ await self._tunnel.aexec(" && ".join(commands), timeout=60)
+
def is_alive(self) -> bool:
"""
Verifies that the connection's SSH master process is alive:
diff --git a/src/tests/_internal/core/backends/massedcompute/__init__.py b/src/tests/_internal/core/backends/massedcompute/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/src/tests/_internal/core/backends/massedcompute/test_api_client.py b/src/tests/_internal/core/backends/massedcompute/test_api_client.py
new file mode 100644
index 0000000000..a028ea1e3a
--- /dev/null
+++ b/src/tests/_internal/core/backends/massedcompute/test_api_client.py
@@ -0,0 +1,60 @@
+import traceback
+
+import pytest
+import requests
+
+from dstack._internal.core.backends.massedcompute.api_client import API_URL, MassedComputeAPIClient
+from dstack._internal.core.errors import ComputeError, VolumeDeletionPending
+
+
+class TestLaunch:
+ @pytest.mark.parametrize(
+ "response",
+ [
+ {"exc": requests.ReadTimeout},
+ {"status_code": 408},
+ {"status_code": 502},
+ {"status_code": 202, "json": {"response": "invalid"}},
+ ],
+ )
+ def test_unconfirmed_launch(self, requests_mock, response):
+ launch = requests_mock.post(f"{API_URL}/instance/launch", **response)
+ assert MassedComputeAPIClient("test").launch("worker", "product", "true") is None
+ assert launch.call_count == 1
+
+ @pytest.mark.parametrize("response", [{"status_code": 409}, {"exc": requests.ConnectTimeout}])
+ def test_rejected_or_unsent_launch(self, requests_mock, response):
+ requests_mock.post(f"{API_URL}/instance/launch", **response)
+ with pytest.raises(ComputeError):
+ MassedComputeAPIClient("test").launch("worker", "product", "true")
+
+
+class TestDeleteVolume:
+ def test_retries_until_provider_confirms_deletion(self, requests_mock):
+ requests_mock.delete(
+ f"{API_URL}/storage-volumes/vol-id",
+ [
+ {"status_code": 409},
+ {"status_code": 202, "json": {"result": {"deleted": False}}},
+ {"status_code": 200, "json": {"result": {"deleted": True}}},
+ {"status_code": 404},
+ ],
+ )
+ client = MassedComputeAPIClient("test")
+ for _ in range(2):
+ with pytest.raises(VolumeDeletionPending):
+ client.delete_volume("vol-id")
+ client.delete_volume("vol-id")
+ client.delete_volume("vol-id")
+
+
+class TestGetInstance:
+ def test_invalid_response_keeps_password_out_of_traceback(self, requests_mock):
+ requests_mock.get(
+ f"{API_URL}/instance/vm-id",
+ json={"runningInstances": [{"uuid": "vm-id", "password": "vm-login-secret"}]},
+ )
+ with pytest.raises(ComputeError, match="Unexpected response") as result:
+ MassedComputeAPIClient("test-key").get_instance("vm-id")
+
+ assert "vm-login-secret" not in "".join(traceback.format_exception(result.value))
diff --git a/src/tests/_internal/core/backends/massedcompute/test_compute.py b/src/tests/_internal/core/backends/massedcompute/test_compute.py
new file mode 100644
index 0000000000..bc7378b779
--- /dev/null
+++ b/src/tests/_internal/core/backends/massedcompute/test_compute.py
@@ -0,0 +1,199 @@
+from datetime import datetime, timezone
+
+import pytest
+import requests
+
+from dstack._internal.core.backends.massedcompute.api_client import API_URL
+from dstack._internal.core.backends.massedcompute.compute import MassedComputeCompute
+from dstack._internal.core.backends.massedcompute.models import (
+ MassedComputeConfig,
+ MassedComputeCreds,
+)
+from dstack._internal.core.errors import ComputeError, NotYetTerminated, ProvisioningError
+from dstack._internal.core.models.backends.base import BackendType
+from dstack._internal.core.models.backends.orphans import OwnerType
+from dstack._internal.server.testing.common import (
+ get_instance_configuration,
+ get_instance_offer_with_availability,
+ get_job_provisioning_data,
+)
+
+VM_ID = "465e97cc-77cc-47dd-bb7c-1835ee127f9f"
+
+
+@pytest.fixture
+def compute() -> MassedComputeCompute:
+ return MassedComputeCompute(MassedComputeConfig(creds=MassedComputeCreds(api_key="test")))
+
+
+class TestCreateInstance:
+ def test_reconciles_the_same_launch_after_a_lost_reply(
+ self, compute: MassedComputeCompute, requests_mock
+ ):
+ launch = requests_mock.post(f"{API_URL}/instance/launch", exc=requests.ReadTimeout)
+ data = compute.create_instance(
+ get_instance_offer_with_availability(backend=BackendType.MASSEDCOMPUTE),
+ get_instance_configuration(),
+ None,
+ )
+ name = launch.last_request.json()["instanceName"]
+ assert data.instance_id == name
+ vm = {
+ "uuid": VM_ID,
+ "name": name,
+ "status": "Running",
+ "os_booted": True,
+ "ip": "192.0.2.1",
+ "username": "Ubuntu",
+ }
+ requests_mock.get(
+ f"{API_URL}/instance",
+ [
+ {"status_code": 503},
+ {"json": {"runningInstances": [{**vm, "name": name + "-other"}]}},
+ {
+ "json": {
+ "runningInstances": [
+ vm,
+ {**vm, "uuid": "1a821471-d1d7-4c27-971d-10d3951ccce7"},
+ ]
+ }
+ },
+ {"json": {"runningInstances": [vm]}},
+ ],
+ )
+ requests_mock.get(f"{API_URL}/instance/{VM_ID}", json={"runningInstances": [vm]})
+ with pytest.raises(ComputeError, match="503"):
+ compute.update_provisioning_data(data, "", "")
+ compute.update_provisioning_data(data, "", "")
+ assert data.instance_id == name and data.hostname is None
+ with pytest.raises(ComputeError, match="Multiple"):
+ compute.update_provisioning_data(data, "", "")
+ assert data.instance_id == name and data.hostname is None
+ compute.update_provisioning_data(data, "", "")
+ assert data.instance_id == VM_ID and data.hostname == vm["ip"]
+ assert data.backend_data is None
+ assert launch.call_count == 1
+
+
+class TestUpdateProvisioningData:
+ @pytest.mark.parametrize(("attached", "hidden_count"), [(False, 0), (True, 1), (True, 0)])
+ def test_requires_exclusive_attachment_before_exposing_ssh(
+ self, compute: MassedComputeCompute, requests_mock, attached, hidden_count
+ ):
+ jpd = get_job_provisioning_data(hostname=None)
+ jpd.instance_id = VM_ID
+ volume_id = "78ee0ea9-4c18-4aa4-b0df-aa1212734d45"
+ jpd.volume_mounts = {volume_id: "/persistent/checkpoints"}
+ vm = {
+ "uuid": jpd.instance_id,
+ "name": "worker",
+ "status": "Running",
+ "os_booted": True,
+ "username": "Ubuntu",
+ "ip": "192.0.2.1",
+ }
+ requests_mock.get(f"{API_URL}/instance/{jpd.instance_id}", json={"runningInstances": [vm]})
+ requests_mock.get(
+ f"{API_URL}/storage-volumes",
+ json={
+ "storageVolumes": [
+ {
+ "id": volume_id,
+ "name": "checkpoints",
+ "status": "active",
+ "canManage": True,
+ "mountPath": "/persistent/checkpoints",
+ "hiddenAttachedCount": hidden_count,
+ "attachedTo": [{"uuid": jpd.instance_id.upper()}] if attached else [],
+ }
+ ]
+ },
+ )
+ if attached and hidden_count == 0:
+ compute.update_provisioning_data(jpd, "", "")
+ assert jpd.hostname == "192.0.2.1"
+ else:
+ with pytest.raises(ProvisioningError, match="failed to attach"):
+ compute.update_provisioning_data(jpd, "", "")
+ assert jpd.hostname is None
+
+
+class TestTerminateInstance:
+ @pytest.mark.parametrize("lost_reply", [False, True])
+ def test_waits_until_new_vm_has_been_seen_by_uuid(
+ self, compute: MassedComputeCompute, requests_mock, lost_reply
+ ):
+ reply = {"exc": requests.ReadTimeout} if lost_reply else {"json": {"response": VM_ID}}
+ launch = requests_mock.post(f"{API_URL}/instance/launch", **reply)
+ data = compute.create_instance(
+ get_instance_offer_with_availability(backend=BackendType.MASSEDCOMPUTE),
+ get_instance_configuration(),
+ None,
+ )
+ vm = {
+ "uuid": VM_ID,
+ "name": launch.last_request.json()["instanceName"],
+ "status": "Running",
+ }
+ if lost_reply:
+ requests_mock.get(f"{API_URL}/instance", json={"runningInstances": [vm]})
+ requests_mock.get(
+ f"{API_URL}/instance/{VM_ID}",
+ [
+ {"json": {"runningInstances": []}},
+ {"json": {"runningInstances": [vm]}},
+ ],
+ )
+ with pytest.raises(ComputeError, match="has not returned VM details"):
+ compute.terminate_instance(data.instance_id, "any", data.backend_data)
+ with pytest.raises(NotYetTerminated) as found:
+ compute.terminate_instance(data.instance_id, "any", data.backend_data)
+ assert found.value.instance_id == VM_ID
+ assert found.value.backend_data is None
+
+ def test_waits_for_disappearance_and_accepts_repeated_calls(
+ self, compute: MassedComputeCompute, requests_mock
+ ):
+ vm = {"uuid": VM_ID, "name": "vm", "status": "Stopped"}
+ requests_mock.get(
+ f"{API_URL}/instance/{VM_ID}",
+ [
+ {"json": {"runningInstances": [vm]}},
+ {"json": {"runningInstances": []}},
+ ],
+ )
+ terminate = requests_mock.post(f"{API_URL}/instance/terminate", status_code=202)
+
+ # A stopped VM on MassedCompute is still billable.
+ with pytest.raises(NotYetTerminated):
+ compute.terminate_instance(VM_ID, "any")
+ compute.terminate_instance(VM_ID, "any")
+ compute.terminate_instance(VM_ID, "any")
+
+ assert terminate.call_count == 1
+ assert terminate.last_request.json() == {"instanceUuids": [VM_ID]}
+
+
+class TestListResourceGroups:
+ def test_lists_only_instances_with_a_provider_ref(
+ self, compute: MassedComputeCompute, requests_mock
+ ):
+ vm = {
+ "uuid": VM_ID,
+ "name": "dstack-main-gpu-abcdefgh12345678",
+ "status": "Running",
+ "created": "2026-11-25T14:48:48.000Z",
+ }
+ requests_mock.get(
+ f"{API_URL}/instance",
+ json={"runningInstances": [vm, {**vm, "name": "manual"}]},
+ )
+
+ (group,) = compute.list_resource_groups().resource_groups
+
+ assert group.owner_type == OwnerType.INSTANCE
+ assert group.provider_ref == "abcdefgh1234"
+ assert group.primary_id == VM_ID
+ assert group.primary_name == vm["name"]
+ assert group.created_at == datetime(2026, 11, 25, 14, 48, 48, tzinfo=timezone.utc)
diff --git a/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py b/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py
index 47f6cc7a41..ad3cc7b2c6 100644
--- a/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py
+++ b/src/tests/_internal/server/background/pipeline_tasks/instances/test_check.py
@@ -1,7 +1,7 @@
import datetime as dt
import logging
from typing import ClassVar, Optional
-from unittest.mock import Mock
+from unittest.mock import AsyncMock, Mock
import pytest
import pytest_asyncio
@@ -180,6 +180,56 @@ async def test_cloudrift_waits_for_backend_within_timeout(
else:
backend.compute().update_provisioning_data.assert_called_once()
+ async def test_deletes_vm_if_volume_never_mounts(
+ self,
+ test_db,
+ session: AsyncSession,
+ worker: InstanceWorker,
+ monkeypatch: pytest.MonkeyPatch,
+ ):
+ project = await create_project(session)
+ data = get_job_provisioning_data(
+ backend=BackendType.MASSEDCOMPUTE, hostname=None, dockerized=True
+ )
+ data.volume_mounts = {"id": "/persistent/checkpoints"}
+ instance = await create_instance(
+ session, project, status=InstanceStatus.PROVISIONING, job_provisioning_data=data
+ )
+ instance.started_at = get_current_datetime()
+ backend = Mock()
+
+ def set_hostname(data: JobProvisioningData, *args) -> None:
+ data.hostname = "192.0.2.1"
+
+ backend.compute.return_value.update_provisioning_data.side_effect = set_hostname
+ monkeypatch.setattr(
+ "dstack._internal.server.services.backends.cache.lease_project_backend_by_type",
+ mock_lease(backend),
+ )
+ conn = AsyncMock()
+ conn.has_volume_mounts.return_value = False
+ monkeypatch.setattr(
+ instances_check.instance_connection_pool, "get_or_open", lambda *_: conn
+ )
+ await process_instance(session, worker, instance)
+ await session.refresh(instance)
+ conn.has_volume_mounts.assert_awaited_once()
+ assert instance.job_provisioning_data is not None
+ assert (
+ JobProvisioningData.model_validate_json(instance.job_provisioning_data).hostname
+ is None
+ )
+
+ instance.started_at = get_current_datetime() - dt.timedelta(hours=1)
+ await process_instance(session, worker, instance)
+ await session.refresh(instance)
+ assert instance.status == InstanceStatus.TERMINATING
+ await process_instance(session, worker, instance)
+ await session.refresh(instance)
+ backend.compute.return_value.terminate_instance.assert_called_once()
+ conn.sync_volume_mounts.assert_not_awaited()
+ assert instance.status == InstanceStatus.TERMINATED
+
async def test_check_shim_transitions_provisioning_on_busy(
self,
test_db,
diff --git a/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py b/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py
index da12aa36b1..0bc2dfccc6 100644
--- a/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py
+++ b/src/tests/_internal/server/background/pipeline_tasks/instances/test_termination.py
@@ -1,13 +1,14 @@
import datetime as dt
from contextlib import contextmanager
from typing import Optional
-from unittest.mock import Mock, patch
+from unittest.mock import AsyncMock, Mock, patch
import pytest
import time_machine
+from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from dstack._internal.core.errors import BackendError, NotYetTerminated
+from dstack._internal.core.errors import BackendError, NotYetTerminated, SSHError
from dstack._internal.core.models.backends.base import BackendType
from dstack._internal.core.models.backends.orphans import OrphanCleanupMode
from dstack._internal.core.models.instances import InstanceStatus, InstanceTerminationReason
@@ -16,10 +17,13 @@
from dstack._internal.server.background.pipeline_tasks.instances import (
termination as instances_termination,
)
-from dstack._internal.server.models import InstanceModel
+from dstack._internal.server.models import InstanceModel, VolumeAttachmentModel
from dstack._internal.server.testing.common import (
+ ComputeMockSpec,
create_instance,
create_project,
+ create_user,
+ create_volume,
get_job_provisioning_data,
list_events,
mock_lease,
@@ -112,7 +116,13 @@ async def test_terminates_terminating_deleted_instance(
assert instance.finished_at is not None
@pytest.mark.parametrize(
- "error", [BackendError("err"), RuntimeError("err"), NotYetTerminated("")]
+ "error",
+ [
+ BackendError("err"),
+ RuntimeError("err"),
+ NotYetTerminated(""),
+ NotYetTerminated("Found VM", instance_id="confirmed-id", backend_data='{"vm": 1}'),
+ ],
)
async def test_terminate_retry(
self,
@@ -147,7 +157,12 @@ async def test_terminate_retry(
self.mock_terminate_in_backend(error=None) as mock,
):
await process_instance(session, worker, instance)
- mock.assert_called_once()
+ if isinstance(error, NotYetTerminated) and error.instance_id:
+ mock.assert_called_once_with(
+ error.instance_id, instance.region, error.backend_data
+ )
+ else:
+ mock.assert_called_once()
await session.refresh(instance)
assert instance.status == InstanceStatus.TERMINATED
@@ -226,6 +241,62 @@ async def test_terminate_on_termination_deadline(
await session.refresh(instance)
assert instance.status == InstanceStatus.TERMINATED
+ async def test_retains_exclusive_volume_until_vm_is_gone(
+ self, test_db, session: AsyncSession, worker: InstanceWorker
+ ):
+ project = await create_project(session)
+ user = await create_user(session)
+ volume = await create_volume(session, project, user)
+ jpd = get_job_provisioning_data(backend=BackendType.MASSEDCOMPUTE)
+ jpd.volume_mounts = {"id": "/persistent/checkpoints"}
+ instance = await create_instance(
+ session,
+ project,
+ status=InstanceStatus.TERMINATING,
+ volumes=[volume],
+ job_provisioning_data=jpd,
+ )
+ instance.volume_attachments[0].exclusive_volume_id = "massedcompute/id"
+ now = dt.datetime(2025, 1, 1, tzinfo=dt.timezone.utc)
+ instance.first_termination_retry_at = now - dt.timedelta(minutes=16)
+ instance.last_termination_retry_at = instance.first_termination_retry_at
+ instance.termination_reason = InstanceTerminationReason.IDLE_TIMEOUT
+ await session.commit()
+
+ compute = Mock(spec=ComputeMockSpec)
+ compute.get_volume_mounts_to_sync.side_effect = [["/persistent/checkpoints"], []]
+ backend = Mock()
+ backend.compute.return_value = compute
+ conn = AsyncMock()
+ conn.sync_volume_mounts.side_effect = SSHError("flush failed")
+ with (
+ patch(
+ "dstack._internal.server.services.backends.cache.lease_project_backend_by_type",
+ mock_lease(backend),
+ ),
+ patch.object(
+ instances_termination.instance_connection_pool, "get_or_open", return_value=conn
+ ),
+ ):
+ with time_machine.travel(now, tick=False):
+ await process_instance(session, worker, instance)
+ compute.terminate_instance.assert_not_called()
+ await session.refresh(instance)
+ assert instance.status == InstanceStatus.TERMINATING
+ attachment = select(VolumeAttachmentModel.volume_id).where(
+ VolumeAttachmentModel.instance_id == instance.id
+ )
+ assert await session.scalar(attachment) == volume.id
+ assert any(
+ "Volume attachments retained" in e.message for e in await list_events(session)
+ )
+ with time_machine.travel(now + dt.timedelta(minutes=1), tick=False):
+ await process_instance(session, worker, instance)
+ compute.terminate_instance.assert_called_once()
+ assert await session.scalar(attachment) is None
+ await session.refresh(instance)
+ assert instance.status == InstanceStatus.TERMINATED
+
async def test_emits_event_if_all_termination_attempts_failed(
self,
test_db,
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 08f1ecd5f3..aa6dc191da 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
@@ -10,7 +10,7 @@
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload
-from dstack._internal.core.errors import BackendError
+from dstack._internal.core.errors import BackendError, SkipOffer
from dstack._internal.core.models.backends.base import BackendType
from dstack._internal.core.models.common import (
EntityReference,
@@ -39,6 +39,7 @@
from dstack._internal.core.models.runs import JobRuntimeData, JobStatus, JobTerminationReason
from dstack._internal.core.models.users import GlobalRole
from dstack._internal.core.models.volumes import (
+ MassedComputeVolumeConfiguration,
VolumeAttachmentData,
VolumeMountPoint,
VolumeStatus,
@@ -51,9 +52,11 @@
JobSubmittedWorker,
_get_new_capacity_failure_message,
_load_submitted_job_context,
+ _lock_related_volume_models,
_NewCapacityAttempts,
_OfferAttemptError,
_release_replica_jobs_from_master_wait,
+ _reserve_launch_volumes,
)
from dstack._internal.server.models import (
ComputeGroupModel,
@@ -87,6 +90,7 @@
get_remote_connection_info,
get_run_spec,
get_ssh_fleet_configuration,
+ get_volume,
get_volume_provisioning_data,
mock_lease,
)
@@ -111,6 +115,49 @@ def worker() -> JobSubmittedWorker:
return JobSubmittedWorker(queue=Mock(), heartbeater=Mock(), pipeline_hinter=Mock())
+@pytest.mark.asyncio
+@pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True)
+class TestReserveLaunchVolumes:
+ async def test_aliases_compete_for_one_attachment(self, test_db, session: AsyncSession):
+ project = await create_project(session=session)
+ user = await create_user(session=session)
+ repo = await create_repo(session=session, project_id=project.id)
+ vpd = get_volume_provisioning_data(backend=BackendType.MASSEDCOMPUTE)
+ vpd.exclusive_at_launch = True
+ jobs = []
+ volumes = []
+ for name in ("first", "second"):
+ config = MassedComputeVolumeConfiguration(name=name, volume_id=vpd.volume_id)
+ model = await create_volume(
+ session,
+ project,
+ user,
+ configuration=config,
+ status=VolumeStatus.ACTIVE,
+ volume_provisioning_data=vpd,
+ )
+ volumes.append(
+ get_volume(
+ id_=model.id,
+ configuration=config,
+ volume_id=vpd.volume_id,
+ provisioning_data=vpd,
+ )
+ )
+ run = await create_run(session, project, repo, user)
+ instance = await create_instance(session, project)
+ job = await create_job(session, run, instance=instance)
+ job.lock_token = uuid.uuid4()
+ await session.commit()
+ jobs.append(job)
+ await _reserve_launch_volumes(jobs[0], [volumes[0]])
+ await _reserve_launch_volumes(jobs[0], [volumes[0]])
+ with pytest.raises(SkipOffer, match="reserved"):
+ await _reserve_launch_volumes(jobs[1], [volumes[1]])
+ await _reserve_launch_volumes(jobs[0], [])
+ await _reserve_launch_volumes(jobs[1], [volumes[1]])
+
+
def _lock_job_foreign(job_model: JobModel) -> None:
job_model.lock_expires_at = get_current_datetime() + timedelta(minutes=1)
job_model.lock_token = uuid.uuid4()
@@ -2979,6 +3026,82 @@ async def test_reclaims_stale_related_volume_lock(
assert volume.lock_expires_at is None
backend_mock.compute.return_value.attach_volume.assert_called_once()
+ async def test_releases_expired_candidate_volume_locks_before_retrying_a_launch(
+ self,
+ test_db,
+ session: AsyncSession,
+ fetcher: JobSubmittedFetcher,
+ worker: JobSubmittedWorker,
+ ):
+ project = await create_project(session)
+ user = await create_user(session)
+ repo = await create_repo(session, project_id=project.id)
+ spec = get_fleet_spec()
+ spec.configuration.nodes = FleetNodesSpec(min=0, target=0, max=1)
+ await create_fleet(session, project, spec=spec)
+ data = get_volume_provisioning_data(backend=BackendType.MASSEDCOMPUTE)
+ data.exclusive_at_launch = True
+ volume = await create_volume(
+ session,
+ project,
+ user,
+ status=VolumeStatus.ACTIVE,
+ configuration=MassedComputeVolumeConfiguration(name="checkpoints"),
+ volume_provisioning_data=data,
+ )
+ alternative = await create_volume(
+ session,
+ project,
+ user,
+ status=VolumeStatus.ACTIVE,
+ volume_provisioning_data=get_volume_provisioning_data(backend=BackendType.AWS),
+ )
+ run_spec = get_run_spec(repo_id=repo.name)
+ run_spec.configuration.volumes = [
+ VolumeMountPoint(name=[volume.name, alternative.name], path="/checkpoints")
+ ]
+ run = await create_run(session, project, repo, user, run_spec=run_spec)
+ job = await create_job(session, run)
+ backend = Mock()
+ backend.TYPE = BackendType.MASSEDCOMPUTE
+ compute = backend.compute.return_value
+ compute.get_offers.return_value = [
+ get_instance_offer_with_availability(backend=backend.TYPE, region="any")
+ ]
+ compute.run_job.side_effect = BackendError("no capacity")
+ with patch(
+ "dstack._internal.server.services.backends.cache.lease_project_backends",
+ mock_lease([backend]),
+ ):
+ await _process_job(session, worker, job)
+ await session.refresh(job)
+ # A lost worker committed related locks but never applied the provisioning result.
+ _lock_job_expired_same_owner(job)
+ job.last_processed_at = get_or_error(job.lock_expires_at)
+ previous_item = _job_to_pipeline_item(job)
+ for candidate in (volume, alternative):
+ candidate.lock_owner = f"{JobSubmittedPipeline.__name__}:{job.id}"
+ candidate.lock_token = job.lock_token
+ candidate.lock_expires_at = job.lock_expires_at
+ await session.commit()
+ (item,) = await fetcher.fetch(limit=1)
+ assert item.prev_lock_expired
+ for candidate in (volume, alternative):
+ await session.refresh(candidate)
+ assert candidate.lock_owner is None
+ assert candidate.lock_token is None
+ assert candidate.lock_expires_at is None
+ # A delayed response from the previous launch must not recreate the cleared leases.
+ assert (
+ await _lock_related_volume_models(previous_item, [[volume.id, alternative.id]])
+ is None
+ )
+ await worker.process(item)
+
+ compute.run_job.assert_called_once()
+ await session.refresh(job)
+ assert job.status == JobStatus.TERMINATING
+
async def test_run_job_uses_server_default_registry(
self,
monkeypatch: pytest.MonkeyPatch,
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 6b36841c25..e80132a1d8 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
@@ -19,7 +19,7 @@
RunStatus,
RunTerminationReason,
)
-from dstack._internal.core.models.volumes import VolumeStatus
+from dstack._internal.core.models.volumes import MassedComputeVolumeConfiguration, VolumeStatus
from dstack._internal.core.services.ssh.tunnel import SSHTunnel
from dstack._internal.server.background.pipeline_tasks.jobs_terminating import (
JobTerminatingFetcher,
@@ -1155,6 +1155,58 @@ async def test_detaches_job_volumes(
await session.refresh(volume)
assert volume.last_job_processed_at is not None
+ async def test_finishes_job_with_exclusive_volume_without_backend(
+ self, test_db, session: AsyncSession, worker: JobTerminatingWorker
+ ):
+ project = await create_project(session)
+ user = await create_user(session)
+ volume = await create_volume(
+ session,
+ project,
+ user,
+ status=VolumeStatus.ACTIVE,
+ configuration=MassedComputeVolumeConfiguration(name="checkpoints"),
+ )
+ instance = await create_instance(
+ session,
+ project,
+ status=InstanceStatus.BUSY,
+ busy_blocks=1,
+ volumes=[volume],
+ backend=BackendType.MASSEDCOMPUTE,
+ )
+ attachment = instance.volume_attachments[0]
+ attachment.exclusive_volume_id = "massedcompute/provider-id"
+ repo = await create_repo(session, project_id=project.id)
+ run = await create_run(session, project=project, repo=repo, user=user)
+ job = await create_job(
+ session,
+ run,
+ status=JobStatus.TERMINATING,
+ termination_reason=JobTerminationReason.ABORTED_BY_USER,
+ job_provisioning_data=get_job_provisioning_data(
+ backend=BackendType.MASSEDCOMPUTE, dockerized=True, hostname=None
+ ),
+ job_runtime_data=get_job_runtime_data(volume_names=[volume.name]),
+ instance=instance,
+ )
+ _lock_job(job)
+ await session.commit()
+
+ await worker.process(_job_to_pipeline_item(job))
+
+ await session.refresh(job)
+ await session.refresh(instance)
+ await session.refresh(volume)
+ await session.refresh(attachment)
+ assert job.status == JobStatus.ABORTED
+ assert job.instance_id is None
+ assert job.volumes_detached_at is not None
+ assert instance.busy_blocks == 0
+ assert volume.last_job_processed_at is not None
+ assert attachment.instance_id == instance.id
+ assert attachment.exclusive_volume_id == "massedcompute/provider-id"
+
async def test_force_detaches_job_volumes(
self, test_db, session: AsyncSession, worker: JobTerminatingWorker
):
diff --git a/src/tests/_internal/server/background/pipeline_tasks/test_orphan_cleanup.py b/src/tests/_internal/server/background/pipeline_tasks/test_orphan_cleanup.py
index 554e317b77..1d0a0383ce 100644
--- a/src/tests/_internal/server/background/pipeline_tasks/test_orphan_cleanup.py
+++ b/src/tests/_internal/server/background/pipeline_tasks/test_orphan_cleanup.py
@@ -164,6 +164,16 @@ def test_tracks_group_matching_active_instance(self):
decision = _get_decision(_get_resource_group(), instance_model=instance_model)
assert decision == _ResourceGroupDecision.TRACKED
+ def test_tracks_provisional_name_after_listing_margin(self):
+ instance = _get_instance_model(
+ InstanceStatus.PROVISIONING, started_at=LISTED_AT - timedelta(hours=1)
+ )
+ group = _get_resource_group(primary_id="provider-uuid")
+ group.primary_name = "instance_id"
+ assert _get_decision(group, instance) == _ResourceGroupDecision.TRACKED
+ group.primary_name = "other-attempt"
+ assert _get_decision(group, instance) == _ResourceGroupDecision.ORPHAN
+
def test_orphans_group_with_other_primary_id_of_active_instance(self):
instance_model = _get_instance_model(InstanceStatus.BUSY)
resource_group = _get_resource_group(primary_id="other_instance_id")
diff --git a/src/tests/_internal/server/background/pipeline_tasks/test_volumes.py b/src/tests/_internal/server/background/pipeline_tasks/test_volumes.py
index 3cac7f3f05..040280c287 100644
--- a/src/tests/_internal/server/background/pipeline_tasks/test_volumes.py
+++ b/src/tests/_internal/server/background/pipeline_tasks/test_volumes.py
@@ -6,7 +6,7 @@
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
-from dstack._internal.core.errors import BackendError
+from dstack._internal.core.errors import BackendError, VolumeProvisioningError
from dstack._internal.core.models.backends.base import BackendType
from dstack._internal.core.models.volumes import VolumeProvisioningData, VolumeStatus
from dstack._internal.server.background.pipeline_tasks import volumes as volumes_pipeline
@@ -314,8 +314,9 @@ async def test_marks_volume_failed_if_backend_not_available(
== "Volume status changed SUBMITTED -> FAILED (Backend not available)"
)
+ @pytest.mark.parametrize("allocated_volume_id", [None, "allocated-volume"])
async def test_marks_volume_failed_if_backend_returns_error(
- self, test_db, session: AsyncSession, worker: VolumeWorker
+ self, test_db, session: AsyncSession, worker: VolumeWorker, allocated_volume_id
):
project = await create_project(session=session)
user = await create_user(session=session)
@@ -335,8 +336,10 @@ async def test_marks_volume_failed_if_backend_returns_error(
mock_lease(backend_mock),
) as get_backend_mock:
backend_mock.compute.return_value = Mock(spec=ComputeMockSpec)
- backend_mock.compute.return_value.create_volume.side_effect = BackendError(
- "Some error"
+ backend_mock.compute.return_value.create_volume.side_effect = (
+ BackendError("Some error")
+ if allocated_volume_id is None
+ else VolumeProvisioningError("Some error", allocated_volume_id)
)
await worker.process(_volume_to_pipeline_item(volume))
@@ -347,6 +350,14 @@ async def test_marks_volume_failed_if_backend_returns_error(
await session.refresh(volume)
assert volume.status == VolumeStatus.FAILED
assert volume.status_message == "Some error"
+ if allocated_volume_id is not None:
+ assert volume.volume_provisioning_data is not None
+ assert (
+ VolumeProvisioningData.model_validate_json(
+ volume.volume_provisioning_data
+ ).volume_id
+ == allocated_volume_id
+ )
events = await list_events(session)
assert len(events) == 1
assert events[0].message == "Volume status changed SUBMITTED -> FAILED (Some error)"
diff --git a/src/tests/_internal/server/routers/test_backends.py b/src/tests/_internal/server/routers/test_backends.py
index fcaf726e7a..f056dcc021 100644
--- a/src/tests/_internal/server/routers/test_backends.py
+++ b/src/tests/_internal/server/routers/test_backends.py
@@ -96,6 +96,7 @@ async def test_returns_backend_types(self, client: AsyncClient):
"kubernetes",
"lambda",
"lium",
+ "massedcompute",
"nebius",
"oci",
"runpod",
diff --git a/src/tests/_internal/server/services/test_instances.py b/src/tests/_internal/server/services/test_instances.py
index e54f0ad97d..ef259f85ee 100644
--- a/src/tests/_internal/server/services/test_instances.py
+++ b/src/tests/_internal/server/services/test_instances.py
@@ -23,7 +23,12 @@
Profile,
)
from dstack._internal.core.models.runs import JobStatus
-from dstack._internal.core.models.volumes import DaytonaVolumeConfiguration
+from dstack._internal.core.models.volumes import (
+ DaytonaVolumeConfiguration,
+ MassedComputeVolumeConfiguration,
+ VolumeAttachment,
+ VolumeInstance,
+)
from dstack._internal.server.models import InstanceModel
from dstack._internal.server.schemas.runner import TaskListItem, TaskListResponse, TaskStatus
from dstack._internal.server.services.runner.client import ShimClient
@@ -127,6 +132,41 @@ def test_preserves_volume_availability_zone_matching(
assert result == ([instance] if matches else [])
+ def test_exclusive_volume_reuses_only_its_instance(self):
+ backend = BackendType.MASSEDCOMPUTE
+ jpd = get_job_provisioning_data(backend=backend, region="any")
+ vpd = get_volume_provisioning_data(backend=backend)
+ vpd.exclusive_at_launch = True
+ attached = get_volume(
+ configuration=MassedComputeVolumeConfiguration(),
+ volume_id=vpd.volume_id,
+ provisioning_data=vpd,
+ attachments=[
+ VolumeAttachment(
+ instance=VolumeInstance(
+ name="worker", instance_num=0, instance_id=jpd.instance_id
+ )
+ )
+ ],
+ )
+ alias = attached.model_copy(update={"attachments": []})
+ jpd.volume_mounts = {vpd.volume_id: "/persistent/data"}
+ instance = InstanceModel(
+ unreachable=False,
+ health=HealthStatus.HEALTHY,
+ total_blocks=1,
+ job_provisioning_data=jpd.model_dump_json(),
+ )
+ assert instances_services.filter_instances([instance], Profile(), volumes=[[alias]]) == []
+ assert instances_services.filter_instances(
+ [instance], Profile(), volumes=[[alias, attached]]
+ ) == [instance]
+ jpd.instance_id = "different-vm"
+ instance.job_provisioning_data = jpd.model_dump_json()
+ assert (
+ instances_services.filter_instances([instance], Profile(), volumes=[[attached]]) == []
+ )
+
def test_global_volume_matches_cpu_and_gpu_regions(self):
instances = [
InstanceModel(