diff --git a/runpod/api/queries/apps.py b/runpod/api/queries/apps.py index c5b11ac3..0d8b63cb 100644 --- a/runpod/api/queries/apps.py +++ b/runpod/api/queries/apps.py @@ -9,6 +9,27 @@ } """ +QUERY_ENDPOINT_SNAPSHOT = """ +query EndpointSnapshot($id: String!) { + myself { + endpoint(id: $id) { + id name type instanceIds gpuIds gpuCount locations + workersMin workersMax workersPFBTarget idleTimeout + scalerType scalerValue executionTimeoutMs workerInitTimeoutMs + flashBootType minCudaVersion allowedCudaVersions + modelReferences env { key value } + networkVolumeIds { networkVolumeId } + volumes { volumeId volumeType } + template { + name imageName containerDiskInGb dockerArgs + env { key value } + ports containerRegistryAuthId advancedStart startScript config + } + } + } +} +""" + QUERY_FLASH_APP_BY_NAME = """ query getFlashAppByName($flashAppName: String!) { flashAppByName(flashAppName: $flashAppName) { diff --git a/runpod/apps/api.py b/runpod/apps/api.py index 49f5b35b..62775798 100644 --- a/runpod/apps/api.py +++ b/runpod/apps/api.py @@ -5,6 +5,7 @@ absent from rest. management verbs for the wider sdk stay in runpod.api.ctl_commands. """ +from copy import deepcopy from typing import Any, Dict, List, Optional, Set import aiohttp @@ -245,6 +246,39 @@ async def _execute( ) return response["data"] + async def snapshot_endpoint(self, endpoint_id: str) -> Dict[str, Any]: + """capture a saveable endpoint configuration in memory for rollback.""" + data = await self._execute( + app_queries.QUERY_ENDPOINT_SNAPSHOT, {"id": endpoint_id}, retry=True + ) + endpoint = (data.get("myself") or {}).get("endpoint") + template = (endpoint or {}).get("template") + if ( + not endpoint + or endpoint.get("id") != endpoint_id + or not template + or not template.get("imageName") + ): + raise RuntimeError( + f"endpoint {endpoint_id} has no restorable configuration" + ) + snapshot = deepcopy(endpoint) + template = snapshot["template"] + snapshot["template"]["containerRegistryAuthId"] = ( + template.get("containerRegistryAuthId") or "" + ) + snapshot["template"]["dockerArgs"] = template.get("dockerArgs") or "" + snapshot["template"]["env"] = template.get("env") or [] + snapshot["env"] = snapshot.get("env") or [] + snapshot["modelReferences"] = snapshot.get("modelReferences") or [] + snapshot["networkVolumeIds"] = snapshot.get("networkVolumeIds") or [] + snapshot["volumes"] = [ + volume + for volume in snapshot.get("volumes") or [] + if volume["volumeType"] == "OBJECT_STORE_VOLUME" + ] + return snapshot + async def save_endpoint(self, endpoint_input: Dict[str, Any]) -> Dict[str, Any]: """save via rest unless the input requires an unsupported capability.""" body = _rest_endpoint_input(endpoint_input) diff --git a/runpod/apps/deploy.py b/runpod/apps/deploy.py index fe2ea42d..e78a08fe 100644 --- a/runpod/apps/deploy.py +++ b/runpod/apps/deploy.py @@ -1,15 +1,20 @@ """deploy pipeline: discovered apps -> manifest -> artifact -> activated build.""" +import asyncio import json import logging import os import secrets +import shlex import tarfile import tempfile from dataclasses import dataclass, field from pathlib import Path, PurePosixPath from typing import Any, Dict, List, Optional, Set +import aiohttp + +from ..error import QueryError from .api import AppsApiClient from .app import App from .build import ( @@ -19,7 +24,11 @@ BuildResult, build_environment, ) -from .errors import InvalidResourceError, ScheduleNotSupported +from .errors import ( + EndpointReconciliationError, + InvalidResourceError, + ScheduleNotSupported, +) from .discovery import resolve_project, validate_apps from .schedule import SCHEDULES_ENABLED from .shim import runtime_launcher @@ -438,12 +447,13 @@ async def reconcile_endpoints( python_version: str, *, resolver=None, + activate_build: bool = False, + environment_created: bool = False, + events=None, ) -> Dict[str, str]: - """converge the environment's endpoints to the app's resources. + """snapshot and reconcile endpoints with best-effort rollback on failure. - resource name -> endpoint id for everything provisioned. existing - endpoints (matched by name) are updated in place; endpoints whose - resources disappeared are deleted. + obsolete endpoints are removed after the deployment commits. """ from .volume import VolumeResolver, attach_endpoint_volumes @@ -454,8 +464,6 @@ async def reconcile_endpoints( await resolver.preflight([handle.spec for handle in app.resources.values()]) existing_endpoints = environment.get("endpoints") or [] existing = {e["name"]: e["id"] for e in existing_endpoints} - # updates send the bound template's current name, so redeploying an - # existing endpoint sends the same template name as before. existing_templates = { e["name"]: (e.get("template") or {}).get("name") for e in existing_endpoints } @@ -470,47 +478,264 @@ async def reconcile_endpoints( from .registry import resolve_registry_auth endpoints: Dict[str, str] = {} - for name, handle in sorted(provisionable.items()): - members = None - if needs_gpu_catalog(handle.spec.gpu): - members = await client.gpu_pool_members() - if name in existing: - template_name = existing_templates.get(name) - else: - template_name = _new_template_name(app, handle.spec, template_token) - payload = _deployed_endpoint_input( - app, - handle.spec, - environment["id"], - build_id, - python_version, - env_name=environment["name"], - pool_members=members or {}, - template_name=template_name, - ) - await attach_endpoint_volumes(payload, handle.spec, resolver, app) - auth_id = await resolve_registry_auth(handle.spec.registry_auth, api=client) - if auth_id: - payload["template"]["containerRegistryAuthId"] = auth_id - if handle.spec.model: - from .model import model_reference - - payload["modelReferences"] = [model_reference(handle.spec.model)] - if name in existing: - payload["id"] = existing[name] - result = await client.save_endpoint(payload) - endpoints[name] = result["id"] - log.info( - "%s endpoint %s (%s)", - "updated" if name in existing else "provisioned", - name, - result["id"], - ) + snapshots = {} + undo = [] + activation_attempted = False + creating = False + action = "prepare deployment" + try: + if provisionable.keys() & existing.keys(): + _phase(events, "snapshot") + for name in sorted(provisionable.keys() & existing.keys()): + action = f"read '{name}'" + snapshots[name] = await client.snapshot_endpoint(existing[name]) + snapshots[name]["flashEnvironmentId"] = environment["id"] + if activate_build: + action = "activate the build" + _phase(events, "activate") + activation_attempted = True + await client.deploy_build(environment["id"], build_id) + _phase(events, "endpoints") + for name, handle in sorted(provisionable.items()): + action = f"prepare '{name}'" + creating = False + members = None + if needs_gpu_catalog(handle.spec.gpu): + members = await client.gpu_pool_members() + if name in existing: + template_name = existing_templates.get(name) + else: + template_name = _new_template_name(app, handle.spec, template_token) + payload = _deployed_endpoint_input( + app, + handle.spec, + environment["id"], + build_id, + python_version, + env_name=environment["name"], + pool_members=members or {}, + template_name=template_name, + ) + await attach_endpoint_volumes(payload, handle.spec, resolver, app) + auth_id = await resolve_registry_auth(handle.spec.registry_auth, api=client) + if auth_id: + payload["template"]["containerRegistryAuthId"] = auth_id + if handle.spec.model: + from .model import model_reference + + payload["modelReferences"] = [model_reference(handle.spec.model)] + if name in existing: + payload["id"] = existing[name] + undo.append((name, existing[name], snapshots[name])) + action = f"deploy '{name}'" + creating = name not in existing + result = await client.save_endpoint(payload) + endpoints[name] = result["id"] + if creating: + undo.append((name, result["id"], None)) + creating = False + log.info("saved endpoint %s (%s)", name, result["id"]) + + except (Exception, asyncio.CancelledError, KeyboardInterrupt) as exc: + lines = [f"Couldn't {action}: {str(exc) or type(exc).__name__}"] + if resolver.created_volumes: + lines.extend( + [ + "New storage retained:", + *( + f" {volume['kind']} volume '{volume['name']}' ({volume['id']})" + for volume in resolver.created_volumes + ), + "Volumes may contain shared data and still incur charges. " + + "Inspect them in the Runpod console and delete only if unused.", + ] + ) + rollback_errors = [] + rollback_progress = [] + rollback_action = "start cleanup" + + async def rollback(): + nonlocal rollback_action + rollback_allowed = True + if activation_attempted: + rollback_action = "check deployment ownership" + try: + current = await client.get_environment_by_name( + app.name, environment["name"] + ) + if not isinstance(current, dict) or "activeBuildId" not in current: + raise RuntimeError("activation status unknown") + if current["activeBuildId"] != build_id and ( + undo + or current["activeBuildId"] != environment.get("activeBuildId") + ): + raise RuntimeError("environment changed during deployment") + except Exception as ownership_exc: + rollback_errors.append( + f"build: {str(ownership_exc) or type(ownership_exc).__name__}" + ) + rollback_allowed = False + if rollback_allowed and activation_attempted and not environment_created: + rollback_action = "restore the previous build" + try: + previous_build = environment.get("activeBuildId") + if previous_build: + await client.deploy_build(environment["id"], previous_build) + rollback_progress.append(f"Restored build {previous_build}.") + else: + current = await client.get_environment_by_name( + app.name, environment["name"] + ) + if ( + not isinstance(current, dict) + or "activeBuildId" not in current + ): + raise RuntimeError("activation status unknown") + if current["activeBuildId"]: + raise RuntimeError("no previous build to restore") + except Exception as restore_exc: + rollback_errors.append( + f"build: {str(restore_exc) or type(restore_exc).__name__}" + ) + if rollback_allowed and creating: + rollback_action = f"locate '{name}' after an interrupted create" + try: + current = await client.get_environment_by_name( + app.name, environment["name"] + ) + if not isinstance(current, dict) or not isinstance( + current.get("endpoints"), list + ): + raise RuntimeError("creation status unknown") + matches = [ + endpoint + for endpoint in (current or {}).get("endpoints", []) + if (endpoint.get("template") or {}).get("name") == template_name + and endpoint["id"] not in existing.values() + ] + if len(matches) == 1: + undo.append((name, matches[0]["id"], None)) + elif ( + matches + or isinstance( + exc, + ( + aiohttp.ClientError, + OSError, + asyncio.TimeoutError, + asyncio.CancelledError, + KeyboardInterrupt, + ), + ) + or ( + isinstance(exc, QueryError) + and ( + exc.status_code == 408 or (exc.status_code or 0) >= 500 + ) + ) + ): + raise RuntimeError("creation status unknown") + except Exception: + rollback_errors.append(f"{name}: creation status unknown") + for resource, endpoint_id, snapshot in ( + reversed(undo) if rollback_allowed else [] + ): + rollback_action = ( + f"{'restore' if snapshot is not None else 'delete'} " + f"'{resource}' ({endpoint_id})" + ) + try: + if snapshot is not None: + await client.save_endpoint(snapshot) + elif not await client.delete_endpoint(endpoint_id): + raise RuntimeError("endpoint deletion was not confirmed") + rollback_progress.append( + f"{'Restored' if snapshot is not None else 'Deleted'} " + f"endpoint '{resource}' ({endpoint_id})." + ) + except Exception as cleanup_exc: + rollback_errors.append( + f"{resource} ({endpoint_id}): {str(cleanup_exc) or type(cleanup_exc).__name__}" + ) + if environment_created and not rollback_errors: + rollback_action = f"remove environment {environment['id']}" + try: + current = await client.get_environment_by_name( + app.name, environment["name"] + ) + if ( + not isinstance(current, dict) + or "endpoints" not in current + or current["endpoints"] + ): + raise RuntimeError("couldn't confirm the environment is empty") + if current.get("activeBuildId") not in (None, build_id): + raise RuntimeError("environment changed during deployment") + if not await client.delete_environment(environment["id"]): + raise RuntimeError("environment deletion was not confirmed") + except Exception as cleanup_exc: + rollback_errors.append( + f"environment {environment['id']}: {str(cleanup_exc) or type(cleanup_exc).__name__}" + ) + if rollback_errors: + lines.extend( + [ + "Rollback incomplete:", + *(f" {error}" for error in rollback_errors), + ] + ) + lines.append( + f"Check `rp flash env get {shlex.quote(environment['name'])} " + f"--app {shlex.quote(app.name)}`. Remaining workers may still incur charges." + ) + elif undo or activation_attempted: + lines.append( + "Best-effort endpoint and build rollback completed." + if resolver.created_volumes + else "Best-effort rollback completed." + ) - for name, endpoint_id in existing.items(): - if name not in provisionable: - await client.delete_endpoint(endpoint_id) - log.info("deleted removed endpoint %s (%s)", name, endpoint_id) + cleanup = asyncio.create_task(rollback()) + interrupted = isinstance(exc, (asyncio.CancelledError, KeyboardInterrupt)) + try: + while not cleanup.done(): + try: + await asyncio.shield(cleanup) + except asyncio.CancelledError: + interrupted = True + cleanup.result() + except BaseException: + lines.extend(rollback_progress) + lines.append(f"Rollback interrupted while attempting to {rollback_action}.") + lines.extend(f" {error}" for error in rollback_errors) + lines.append( + f"Check `rp flash env get {shlex.quote(environment['name'])} " + f"--app {shlex.quote(app.name)}`. Remaining workers may still incur charges." + ) + log.warning("\n".join(lines)) + raise + if interrupted: + log.warning("\n".join(lines)) + if isinstance(exc, (asyncio.CancelledError, KeyboardInterrupt)): + raise + raise asyncio.CancelledError() from exc + raise EndpointReconciliationError("\n".join(lines)) from exc + + obsolete = existing.keys() - provisionable.keys() + if obsolete: + _phase(events, "cleanup") + for name in sorted(obsolete): + endpoint_id = existing[name] + try: + if not await client.delete_endpoint(endpoint_id): + raise RuntimeError("endpoint deletion was not confirmed") + except Exception as exc: + raise EndpointReconciliationError( + f"Deployed, but couldn't remove '{name}' ({endpoint_id}): {exc}\n" + f"Check `rp flash env get {shlex.quote(environment['name'])} " + f"--app {shlex.quote(app.name)}`." + ) from exc + log.info("deleted removed endpoint %s (%s)", name, endpoint_id) return endpoints @@ -618,6 +843,7 @@ async def deploy_app( environments = {e["name"]: e for e in remote_app.get("flashEnvironments") or []} environment = environments.get(env_name) + environment_created = environment is None if environment is None: environment = await client.create_environment(app_id, env_name) log.info("created environment %s (%s)", env_name, environment["id"]) @@ -643,12 +869,35 @@ async def deploy_app( ) log.info("uploaded build %s", build["id"]) - await client.deploy_build(environment["id"], build["id"]) - log.info("activated build %s on %s/%s", build["id"], app.name, env_name) + current = await client.get_environment_by_name(app.name, env_name) + if ( + not isinstance(current, dict) + or current.get("id") != environment["id"] + or current.get("name") != env_name + or "activeBuildId" not in current + or not isinstance(current.get("endpoints"), list) + ): + raise EndpointReconciliationError( + "Couldn't read the deployment baseline after upload. " + "The environment is missing, changed, or incomplete." + ) + environment_created = ( + environment_created + and not current["activeBuildId"] + and not current["endpoints"] + ) + environment = current - _phase(events, "endpoints") endpoints = await reconcile_endpoints( - client, app, environment, build["id"], python_version, resolver=resolver + client, + app, + environment, + build["id"], + python_version, + resolver=resolver, + activate_build=True, + environment_created=environment_created, + events=events, ) endpoint_ready = getattr(events, "endpoint_ready", None) if endpoint_ready is not None: diff --git a/runpod/apps/discovery.py b/runpod/apps/discovery.py index 3d42edf4..2f424eaf 100644 --- a/runpod/apps/discovery.py +++ b/runpod/apps/discovery.py @@ -128,6 +128,9 @@ def _import_module(path: Path, project: Project) -> None: "or standard-library module." ) except (Exception, SystemExit) as exc: + if isinstance(exc, InvalidResourceError): + relative = path.relative_to(project.source_root) + raise DiscoveryError(f"{relative}: {exc}") from exc hint = "" if isinstance(exc, ModuleNotFoundError) and ( project.source_root != project.import_root diff --git a/runpod/apps/errors.py b/runpod/apps/errors.py index 39a177b5..0aef65a3 100644 --- a/runpod/apps/errors.py +++ b/runpod/apps/errors.py @@ -58,3 +58,7 @@ def __init__(self) -> None: class InvalidResourceError(AppError): """a decorator was applied to an unsupported target or with bad config.""" + + +class EndpointReconciliationError(AppError): + """endpoint reconciliation failed with rollback results and remaining changes.""" diff --git a/runpod/apps/source.py b/runpod/apps/source.py index 671e7cca..d6172d93 100644 --- a/runpod/apps/source.py +++ b/runpod/apps/source.py @@ -132,7 +132,7 @@ def iter_source_files( or (discovery and is_discovery_skipped_dir(path)) ): if not discovery: - log.warning("excluded source path %r from deployment artifact", rel) + log.debug("excluded source path %r from deployment artifact", rel) continue kept_dirs.append(name) dirs[:] = kept_dirs @@ -148,6 +148,6 @@ def iter_source_files( or (discovery and (path.suffix != ".py" or name == "setup.py")) ): if not discovery: - log.warning("excluded source path %r from deployment artifact", rel) + log.debug("excluded source path %r from deployment artifact", rel) continue yield path diff --git a/runpod/apps/spec.py b/runpod/apps/spec.py index 57c99fc4..91472231 100644 --- a/runpod/apps/spec.py +++ b/runpod/apps/spec.py @@ -126,6 +126,13 @@ def normalize_cpu( ) if not cpu or any(not isinstance(c, str) or not c.strip() for c in cpu): raise InvalidResourceError("cpu must contain non-empty instance ids") + from ..api.ctl_commands import _cpu_config + + for instance_id in cpu: + try: + _cpu_config(instance_id) + except ValueError as exc: + raise InvalidResourceError(f"unknown cpu {instance_id!r}. {exc}") from exc return list(cpu) @@ -260,6 +267,14 @@ def validate(self) -> None: raise InvalidResourceError( f"resource '{self.name}': gpu_count must be >= 1" ) + if ( + isinstance(self.idle_timeout, bool) + or not isinstance(self.idle_timeout, int) + or not 1 <= self.idle_timeout <= 3600 + ): + raise InvalidResourceError( + f"'{self.name}': idle_timeout must be a whole number from 1 to 3600 seconds" + ) if self.max_concurrency < 1: raise InvalidResourceError( f"resource '{self.name}': max_concurrency must be >= 1, " diff --git a/runpod/apps/volume.py b/runpod/apps/volume.py index 066d1d42..ba824e11 100644 --- a/runpod/apps/volume.py +++ b/runpod/apps/volume.py @@ -292,6 +292,7 @@ def __init__(self, api=None, events: Optional[object] = None): self._api = api self.events = events self._resolved: Dict[Tuple[str, str], Dict[str, Any]] = {} + self.created_volumes: List[Dict[str, str]] = [] self._planned: Dict[Tuple[str, str], Tuple[Dict[str, Any], List]] = {} self._stock = None self._volume_datacenters: Optional[Set[str]] = None @@ -322,12 +323,18 @@ async def resolve( client = await self._client() if isinstance(volume, GlobalVolume): record = await client.create_global_volume(name=volume.name) + self.created_volumes.append( + {"kind": volume.kind, "name": volume.name, "id": record["id"]} + ) log.info("created global volume %s (%s)", volume.name, record["id"]) else: dc = planned["dataCenterId"] record = await client.create_network_volume( name=volume.name, size=volume.size, data_center_id=dc ) + self.created_volumes.append( + {"kind": volume.kind, "name": volume.name, "id": record["id"]} + ) emit(self.events, "volume_created", volume.name, volume.size, dc) log.info( "created volume %s (%s, %dGB, %s)", diff --git a/runpod/rp_cli/console.py b/runpod/rp_cli/console.py index 3bb10b7b..3cb24fb6 100644 --- a/runpod/rp_cli/console.py +++ b/runpod/rp_cli/console.py @@ -14,11 +14,13 @@ from rich.progress import ( Progress, SpinnerColumn, + Task, TaskID, TextColumn, ) from rich.spinner import SPINNERS from rich.theme import Theme +from rich.text import Text from runpod._hosts import console_url @@ -258,7 +260,10 @@ def reload_banner(module: str = "") -> None: "vendor": "resolving dependencies", "package": "packaging artifact", "upload": "uploading build", - "endpoints": "reconciling endpoints", + "endpoints": "deploying endpoints", + "snapshot": "saving current settings", + "activate": "activating build", + "cleanup": "removing unused endpoints", } @@ -275,6 +280,13 @@ def _bar(fraction: float) -> str: ) +class _DeploySpinnerColumn(SpinnerColumn): + def render(self, task: Task) -> Text: + if task.fields.get("failed"): + return Text("✗", style="err") + return super().render(task) + + class DeployEvents: """deploy_app event sink: animated phase list with live progress. @@ -285,7 +297,9 @@ class DeployEvents: def __init__(self) -> None: self._progress = Progress( - _spinner_column(), + _DeploySpinnerColumn( + RUNPOD_SAND_SPINNER, style=ACCENT, finished_text="[ok]✓[/ok]" + ), TextColumn("[white]{task.description}[/white]"), TextColumn("{task.fields[detail]}"), console=console, @@ -358,8 +372,13 @@ def endpoint_ready(self, name: str, endpoint_id: str) -> None: self.endpoints: Dict[str, str] = getattr(self, "endpoints", {}) self.endpoints[name] = endpoint_id - def close(self) -> None: - self._finish_current() + def close(self, *, failed: bool = False) -> None: + if failed and self._current is not None: + self._progress.update(self._current, failed=True, detail="") + self._progress.stop_task(self._current) + self._current = None + else: + self._finish_current() if self._started: self._progress.stop() self._started = False diff --git a/runpod/rp_cli/main.py b/runpod/rp_cli/main.py index 094b5c69..f1036bdb 100644 --- a/runpod/rp_cli/main.py +++ b/runpod/rp_cli/main.py @@ -225,6 +225,7 @@ def deploy(target, env, python_version, exclude, build_only): for found in apps: ui.set_name_width(list(found.resources)) events = ui.DeployEvents() + succeeded = False try: artifact = build_artifact( found, @@ -234,10 +235,11 @@ def deploy(target, env, python_version, exclude, build_only): events=events, output=Path.cwd() / f"{found.name}-artifact.tar.gz", ) + succeeded = True except Exception as exc: # noqa: BLE001 - surface engine errors cleanly raise click.ClickException(str(exc)) from exc finally: - events.close() + events.close(failed=not succeeded) size_mb = artifact.stat().st_size / (1024 * 1024) ui.success( f"built [white]{found.name}[/white] " @@ -268,6 +270,7 @@ def deploy(target, env, python_version, exclude, build_only): source=_app_source(found, project_root), ) events = ui.DeployEvents() + succeeded = False with ui.Timer() as t: try: result = asyncio.run( @@ -280,10 +283,11 @@ def deploy(target, env, python_version, exclude, build_only): events=events, ) ) + succeeded = True except Exception as exc: # noqa: BLE001 - surface engine errors cleanly raise click.ClickException(str(exc)) from exc finally: - events.close() + events.close(failed=not succeeded) ui.success( f"[bold white]{result.app_name}/{env or found.env}[/bold white] " f"is live [dim]{t.elapsed:.1f}s[/dim]" diff --git a/tests/test_apps/test_deploy.py b/tests/test_apps/test_deploy.py index 3ca87fe7..78d1e893 100644 --- a/tests/test_apps/test_deploy.py +++ b/tests/test_apps/test_deploy.py @@ -196,6 +196,7 @@ def test_credential_like_source_paths_are_included(self, tmp_path): assert f"src/{name}" in tar.getnames() def test_excluded_paths_are_logged_without_contents(self, tmp_path, caplog): + caplog.set_level("DEBUG", logger="runpod.apps.source") for name in (".env", "private.key", "private.pem", "local.txt", ".aws/config"): path = tmp_path / name path.parent.mkdir(parents=True, exist_ok=True) @@ -210,6 +211,14 @@ def test_excluded_paths_are_logged_without_contents(self, tmp_path, caplog): ) assert "sensitive-file-contents" not in caplog.text + def test_excluded_paths_are_quiet_at_normal_log_levels(self, tmp_path, caplog): + (tmp_path / "__pycache__").mkdir() + (tmp_path / ".env").write_text("sensitive-file-contents") + with tarfile.open(package_project(tmp_path, {})) as tar: + assert set(tar.getnames()) == {"runpod_manifest.json"} + assert "excluded source path" not in caplog.text + assert "sensitive-file-contents" not in caplog.text + def test_vendored_env_included_under_env(self, tmp_path): _write_project(tmp_path) env_dir = tmp_path / "built-env" @@ -292,6 +301,12 @@ async def test_deploy_app_full_flow(self, tmp_path): api.get_app_by_name.return_value = None api.create_app.return_value = {"id": "app-1", "flashEnvironments": []} api.create_environment.return_value = {"id": "env-1", "name": "default"} + api.get_environment_by_name.return_value = { + "id": "env-1", + "name": "default", + "activeBuildId": None, + "endpoints": [], + } api.prepare_artifact_upload.return_value = { "uploadUrl": "https://upload", "objectKey": "key-1", @@ -320,6 +335,12 @@ async def test_deploy_reuses_existing_app_and_env(self, tmp_path): "id": "app-1", "flashEnvironments": [{"id": "env-1", "name": "default"}], } + api.get_environment_by_name.return_value = { + "id": "env-1", + "name": "default", + "activeBuildId": None, + "endpoints": [], + } api.prepare_artifact_upload.return_value = { "uploadUrl": "https://upload", "objectKey": "key-1", @@ -347,6 +368,12 @@ async def test_deploy_environment_is_used_for_nested_calls( "id": "app-1", "flashEnvironments": [{"id": "env-prod", "name": "prod"}], } + api.get_environment_by_name.return_value = { + "id": "env-prod", + "name": "prod", + "activeBuildId": None, + "endpoints": [], + } api.prepare_artifact_upload.return_value = { "uploadUrl": "https://upload", "objectKey": "key-1", diff --git a/tests/test_apps/test_deploy_cancellation.py b/tests/test_apps/test_deploy_cancellation.py new file mode 100644 index 00000000..511718ac --- /dev/null +++ b/tests/test_apps/test_deploy_cancellation.py @@ -0,0 +1,126 @@ +"""interrupted deployment rollback and recovery diagnostics.""" + +import asyncio +from unittest.mock import AsyncMock, patch + +import pytest + +from runpod.apps import App +from runpod.apps.app import _clear_registry +from runpod.apps.deploy import reconcile_endpoints + + +@pytest.fixture(autouse=True) +def clean_registry(): + _clear_registry() + yield + _clear_registry() + + +@pytest.mark.parametrize("interrupt", [asyncio.CancelledError, KeyboardInterrupt]) +async def test_interrupt_restores_build_and_updates_then_propagates(interrupt, caplog): + app = App("demo") + for name in ("alpha", "beta"): + app.queue(name=name, cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + api.snapshot_endpoint.side_effect = [ + {"id": "ep-alpha", "name": "alpha"}, + {"id": "ep-beta", "name": "beta"}, + ] + api.save_endpoint.side_effect = [{"id": "ep-alpha"}, interrupt(), {}, {}] + api.get_environment_by_name.return_value = {"activeBuildId": "new-build"} + environment = { + "id": "env", + "name": "prod", + "activeBuildId": "old-build", + "endpoints": [{"id": f"ep-{name}", "name": name} for name in ("alpha", "beta")], + } + with pytest.raises(interrupt): + await reconcile_endpoints( + api, app, environment, "new-build", "3.12", activate_build=True + ) + assert api.deploy_build.await_args_list[-1].args == ("env", "old-build") + assert [call.args[0]["id"] for call in api.save_endpoint.await_args_list[-2:]] == [ + "ep-beta", + "ep-alpha", + ] + assert "Best-effort rollback completed." in caplog.text + + +@pytest.mark.parametrize("delete_succeeds", [True, False]) +async def test_repeated_cancellation_waits_for_lost_create_cleanup( + delete_succeeds, caplog +): + app = App("demo") + app.queue(name="worker", cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + creating = asyncio.Event() + deleting = asyncio.Event() + finish_cleanup = asyncio.Event() + + async def save(payload): + creating.set() + await asyncio.Future() + + async def delete(endpoint_id): + deleting.set() + await finish_cleanup.wait() + return delete_succeeds + + api.save_endpoint.side_effect = save + api.delete_endpoint.side_effect = delete + api.get_environment_by_name.return_value = { + "activeBuildId": "new-build", + "endpoints": [ + {"id": "ep-created", "template": {"name": "demo-worker-template-token"}} + ], + } + with patch("runpod.apps.deploy.secrets.token_hex", return_value="token"): + deployment = asyncio.create_task( + reconcile_endpoints( + api, + app, + {"id": "env", "name": "prod", "activeBuildId": "old-build"}, + "new-build", + "3.12", + activate_build=True, + ) + ) + await asyncio.wait_for(creating.wait(), timeout=2) + deployment.cancel() + await asyncio.wait_for(deleting.wait(), timeout=2) + deployment.cancel() + await asyncio.sleep(0) + assert not deployment.done() + finish_cleanup.set() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(deployment, timeout=2) + api.delete_endpoint.assert_awaited_once_with("ep-created") + api.deploy_build.assert_awaited_with("env", "old-build") + if delete_succeeds: + assert "Best-effort rollback completed." in caplog.text + else: + assert "Rollback incomplete:" in caplog.text + assert "rp flash env get prod --app demo" in caplog.text + assert "Remaining workers may still incur charges." in caplog.text + + +async def test_cancellation_preserves_other_deployment(caplog): + app = App("demo") + app.queue(name="worker", cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + api.save_endpoint.side_effect = asyncio.CancelledError() + api.get_environment_by_name.return_value = {"activeBuildId": "other-build"} + with pytest.raises(asyncio.CancelledError): + await reconcile_endpoints( + api, + app, + {"id": "env", "name": "prod", "activeBuildId": "old-build"}, + "new-build", + "3.12", + activate_build=True, + ) + api.deploy_build.assert_awaited_once_with("env", "new-build") + api.delete_endpoint.assert_not_awaited() + assert "environment changed during deployment" in caplog.text + assert "rp flash env get prod --app demo" in caplog.text diff --git a/tests/test_apps/test_deploy_event_failure.py b/tests/test_apps/test_deploy_event_failure.py new file mode 100644 index 00000000..2b3e379c --- /dev/null +++ b/tests/test_apps/test_deploy_event_failure.py @@ -0,0 +1,45 @@ +"""reconciliation errors before endpoint operations begin.""" + +from unittest.mock import AsyncMock + +import pytest + +from runpod.apps import App +from runpod.apps.app import _clear_registry +from runpod.apps.deploy import reconcile_endpoints +from runpod.apps.errors import EndpointReconciliationError + + +@pytest.fixture(autouse=True) +def clean_registry(): + _clear_registry() + yield + _clear_registry() + + +@pytest.mark.parametrize("existing", [False, True]) +async def test_phase_lookup_failure_preserves_original_error(existing): + error = RuntimeError("phase handler unavailable") + + class Events: + @property + def phase(self): + raise error + + app = App("demo") + app.queue(name="worker", cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + environment = { + "id": "env", + "name": "prod", + "endpoints": [{"id": "ep-old", "name": "worker"}] if existing else [], + } + + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints( + api, app, environment, "new-build", "3.12", events=Events() + ) + + assert str(caught.value) == "Couldn't prepare deployment: phase handler unavailable" + assert caught.value.__cause__ is error + assert api.mock_calls == [] diff --git a/tests/test_apps/test_deploy_recovery.py b/tests/test_apps/test_deploy_recovery.py new file mode 100644 index 00000000..9ac9b1e2 --- /dev/null +++ b/tests/test_apps/test_deploy_recovery.py @@ -0,0 +1,344 @@ +import asyncio +import json +from copy import deepcopy +from pathlib import Path +from unittest.mock import AsyncMock, patch + +import pytest + +from runpod.apps import App +from runpod.apps.api import AppsApiClient +from runpod.apps.app import _clear_registry +from runpod.apps.build import BuildResult +from runpod.apps.deploy import deploy_app, reconcile_endpoints +from runpod.apps.errors import EndpointReconciliationError +from runpod.apps.volume import GlobalVolume, NetworkVolume, VolumeResolver +from runpod.error import QueryError + + +@pytest.fixture(autouse=True) +def clean_registry(): + _clear_registry() + yield + _clear_registry() + + +@pytest.mark.parametrize( + "error", + [ + QueryError("model reconciliation failed"), + json.JSONDecodeError("invalid response", "", 0), + RuntimeError("response processing failed"), + ], +) +async def test_postcommit_create_errors_recover_the_committed_endpoint(error): + app = App("demo") + app.queue(name="worker", gpu="AMPERE_24", model="owner/model")(lambda: None) + api = AppsApiClient() + environment = {"id": "env", "name": "prod", "activeBuildId": "old", "endpoints": []} + state = deepcopy(environment) + + async def execute(query, variables=None, **kwargs): + state["endpoints"].append( + { + "id": "created", + "name": "worker", + "template": variables["input"]["template"], + } + ) + raise error + + async def activate(environment_id, build_id): + state["activeBuildId"] = build_id + + async def delete(endpoint_id): + state["endpoints"] = [e for e in state["endpoints"] if e["id"] != endpoint_id] + return True + + api._execute = AsyncMock(side_effect=execute) + api.deploy_build = AsyncMock(side_effect=activate) + api.get_environment_by_name = AsyncMock(side_effect=lambda *args: deepcopy(state)) + api.delete_endpoint = AsyncMock(side_effect=delete) + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints( + api, app, environment, "new", "3.12", activate_build=True + ) + assert caught.value.__cause__ is error + assert state == environment + api.delete_endpoint.assert_awaited_once_with("created") + assert "Best-effort rollback completed." in str(caught.value) + + +@pytest.mark.parametrize("current", [None, {}, {"endpoints": []}, {"endpoints": None}]) +async def test_unconfirmed_create_never_claims_complete_rollback(current): + app = App("demo") + app.queue(name="worker", cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + api.save_endpoint.side_effect = asyncio.TimeoutError("request timed out") + api.get_environment_by_name.return_value = current + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints( + api, app, {"id": "env", "name": "prod"}, "new", "3.12" + ) + assert "creation status unknown" in str(caught.value) + assert "Best-effort rollback completed." not in str(caught.value) + api.delete_endpoint.assert_not_awaited() + + +async def test_multiple_create_matches_are_not_deleted(): + app = App("demo") + app.queue(name="worker", cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + + async def save(payload): + api.get_environment_by_name.return_value = { + "endpoints": [ + {"id": endpoint_id, "template": payload["template"]} + for endpoint_id in ("first", "second") + ] + } + raise QueryError("request failed") + + api.save_endpoint.side_effect = save + with pytest.raises(EndpointReconciliationError, match="creation status unknown"): + await reconcile_endpoints( + api, app, {"id": "env", "name": "prod"}, "new", "3.12" + ) + api.delete_endpoint.assert_not_awaited() + + +@pytest.mark.parametrize("environment_created", [False, True]) +async def test_upload_intervening_deployment_is_the_rollback_baseline( + tmp_path, environment_created +): + app = App("demo") + for name in ("alpha", "beta"): + app.queue(name=name, cpu="cpu3c-1-2")(lambda: None) + original = { + "id": "env", + "name": "prod", + "activeBuildId": None if environment_created else "old", + "endpoints": [], + } + state = deepcopy(original) + endpoint_build = "old" + api = AsyncMock() + api.get_app_by_name.return_value = { + "id": "app", + "flashEnvironments": [] if environment_created else [deepcopy(original)], + } + api.create_environment.return_value = deepcopy(original) + api.prepare_artifact_upload.return_value = { + "uploadUrl": "unused", + "objectKey": "unused", + } + api.finalize_artifact_upload.return_value = {"id": "new"} + + async def upload(*args, **kwargs): + nonlocal endpoint_build + endpoint_build = "successful-other-deploy" + state.update( + activeBuildId=endpoint_build, + endpoints=[ + { + "id": "ep-alpha", + "name": "alpha", + "template": {"name": "other-template"}, + } + ], + ) + + async def snapshot(endpoint_id): + return { + "id": endpoint_id, + "name": "alpha", + "template": {"env": [{"key": "RUNPOD_BUILD_ID", "value": endpoint_build}]}, + } + + async def activate(environment_id, build_id): + state["activeBuildId"] = build_id + + async def save(payload): + nonlocal endpoint_build + if payload["name"] == "beta": + raise QueryError("quota exceeded") + endpoint_build = next( + e["value"] + for e in payload["template"]["env"] + if e["key"] == "RUNPOD_BUILD_ID" + ) + return {"id": "ep-alpha"} + + api.upload_tarball.side_effect = upload + api.snapshot_endpoint.side_effect = snapshot + api.deploy_build.side_effect = activate + api.save_endpoint.side_effect = save + api.get_environment_by_name.side_effect = lambda *args: deepcopy(state) + artifact = tmp_path / "artifact.tar.gz" + artifact.write_bytes(b"synthetic") + with ( + patch( + "runpod.apps.deploy.build_environment", + return_value=BuildResult(tmp_path, []), + ), + patch("runpod.apps.deploy.package_project", return_value=artifact), + ): + with pytest.raises(EndpointReconciliationError): + await deploy_app(app, tmp_path, env_name="prod", api=api) + assert state["activeBuildId"] == endpoint_build == "successful-other-deploy" + api.snapshot_endpoint.assert_awaited_once_with("ep-alpha") + assert api.save_endpoint.await_args_list[0].args[0]["id"] == "ep-alpha" + assert ( + api.save_endpoint.await_args_list[0].args[0]["template"]["name"] + == "other-template" + ) + api.delete_environment.assert_not_awaited() + calls = [call[0] for call in api.mock_calls] + assert ( + calls.index("finalize_artifact_upload") + < calls.index("get_environment_by_name") + < calls.index("snapshot_endpoint") + < calls.index("deploy_build") + ) + + +@pytest.mark.parametrize( + "current", + [ + None, + {}, + { + "id": "replacement", + "name": "prod", + "activeBuildId": "other", + "endpoints": [], + }, + ], +) +async def test_missing_or_replaced_postupload_baseline_stops_before_writes( + tmp_path, current +): + app = App("demo") + app.queue(name="worker", cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + api.get_app_by_name.return_value = { + "id": "app", + "flashEnvironments": [{"id": "env", "name": "prod"}], + } + api.prepare_artifact_upload.return_value = { + "uploadUrl": "unused", + "objectKey": "unused", + } + api.finalize_artifact_upload.return_value = {"id": "new"} + api.get_environment_by_name.return_value = current + artifact = tmp_path / "artifact.tar.gz" + artifact.write_bytes(b"synthetic") + with ( + patch( + "runpod.apps.deploy.build_environment", + return_value=BuildResult(tmp_path, []), + ), + patch("runpod.apps.deploy.package_project", return_value=artifact), + ): + with pytest.raises(EndpointReconciliationError, match="baseline after upload"): + await deploy_app(app, tmp_path, env_name="prod", api=api) + api.deploy_build.assert_not_awaited() + api.save_endpoint.assert_not_awaited() + api.delete_endpoint.assert_not_awaited() + api.delete_environment.assert_not_awaited() + + +@pytest.mark.parametrize("volume_type", [GlobalVolume, NetworkVolume]) +@pytest.mark.parametrize("reused", [False, True]) +@pytest.mark.parametrize("task_storage", [False, True]) +async def test_retained_storage_reports_only_new_volumes( + volume_type, reused, task_storage +): + app = App("demo") + volume = volume_type("data") + if task_storage: + app.task(name="task", gpu="AMPERE_24", mounts={"/data": volume})(lambda: None) + app.queue( + name="alpha", + gpu="AMPERE_24", + mounts={} if task_storage else {"/runpod-volume": volume}, + )(lambda: None) + app.queue(name="beta", cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + record = {"id": "retained-volume", "name": "data", "dataCenter": "EU-RO-1"} + api.list_global_volumes.return_value = [record] if reused else [] + api.list_network_volumes.return_value = [record] if reused else [] + api.create_global_volume.return_value = record + api.create_network_volume.return_value = record + api.network_volume_datacenters.return_value = {"EU-RO-1"} + api.gpu_stock_status.return_value = "High" + api.delete_endpoint.return_value = True + api.get_environment_by_name.return_value = {"endpoints": []} + resolver = VolumeResolver(api) + if task_storage: + from runpod.apps.deploy import _prepare_task_resources, build_manifest + + manifest = build_manifest(app, Path.cwd()) + await _prepare_task_resources(app, manifest, api, resolver=resolver) + api.snapshot_endpoint.return_value = {"id": "ep-beta", "name": "beta"} + api.save_endpoint.side_effect = [ + {"id": "ep-alpha"}, + QueryError("quota exceeded"), + {"id": "ep-beta"}, + ] + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints( + api, + app, + { + "id": "env", + "name": "prod", + "endpoints": [{"id": "ep-beta", "name": "beta"}], + }, + "new", + "3.12", + resolver=resolver, + ) + message = str(caught.value) + assert ("New storage retained:" in message) is not reused + assert ("retained-volume" in message) is not reused + assert ("Best-effort rollback completed." in message) is reused + if not reused: + assert "Best-effort endpoint and build rollback completed." in message + assert f"{volume.kind} volume 'data' (retained-volume)" in message + assert "delete only if unused" in message + assert resolver.created_volumes == [ + {"kind": volume.kind, "name": "data", "id": "retained-volume"} + ] + await resolver.resolve(volume) + assert len(resolver.created_volumes) == 1 + api.delete_endpoint.assert_awaited_once_with("ep-alpha") + api.delete_global_volume.assert_not_awaited() + api.delete_network_volume.assert_not_awaited() + + +@pytest.mark.parametrize("cleanup_cancelled", [False, True]) +async def test_retained_volume_diagnostic_survives_cancellation( + cleanup_cancelled, caplog +): + app = App("demo") + app.queue( + name="alpha", gpu="AMPERE_24", mounts={"/runpod-volume": GlobalVolume("data")} + )(lambda: None) + app.queue(name="beta", cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + api.list_global_volumes.return_value = [] + api.create_global_volume.return_value = {"id": "retained-volume"} + api.get_environment_by_name.return_value = {"endpoints": []} + api.save_endpoint.side_effect = [{"id": "ep-alpha"}, asyncio.CancelledError()] + api.delete_endpoint.side_effect = ( + asyncio.CancelledError() if cleanup_cancelled else None + ) + api.delete_endpoint.return_value = True + with pytest.raises(asyncio.CancelledError): + await reconcile_endpoints( + api, app, {"id": "env", "name": "prod"}, "new", "3.12" + ) + assert "global volume 'data' (retained-volume)" in caplog.text + assert "delete only if unused" in caplog.text + api.delete_global_volume.assert_not_awaited() diff --git a/tests/test_apps/test_deploy_rejected_create.py b/tests/test_apps/test_deploy_rejected_create.py new file mode 100644 index 00000000..dc7406a3 --- /dev/null +++ b/tests/test_apps/test_deploy_rejected_create.py @@ -0,0 +1,138 @@ +"""confirmed rejection and in-flight uncertainty during first deployment.""" + +import asyncio +from copy import deepcopy +from unittest.mock import AsyncMock + +import aiohttp +import pytest + +from runpod.apps import App +from runpod.apps.app import _clear_registry +from runpod.apps.deploy import reconcile_endpoints +from runpod.apps.errors import EndpointReconciliationError +from runpod.error import QueryError + + +@pytest.fixture(autouse=True) +def clean_registry(): + _clear_registry() + yield + _clear_registry() + + +@pytest.mark.parametrize( + "error,uncertain_when_missing", + [ + (QueryError("request failed"), False), + (RuntimeError("request failed"), False), + (aiohttp.ClientConnectionError("request failed"), True), + (OSError("request failed"), True), + (TimeoutError("request failed"), True), + (asyncio.TimeoutError("request failed"), True), + (asyncio.CancelledError("request failed"), True), + (KeyboardInterrupt("request failed"), True), + pytest.param(QueryError("bad request", status_code=400), False, id="http-400"), + pytest.param( + QueryError("request timeout", status_code=408), True, id="http-408" + ), + pytest.param( + QueryError("quota exceeded", status_code=429), False, id="http-429" + ), + pytest.param(QueryError("server error", status_code=500), True, id="http-500"), + pytest.param(QueryError("bad gateway", status_code=502), True, id="http-502"), + pytest.param(QueryError("unavailable", status_code=503), True, id="http-503"), + pytest.param( + QueryError("gateway timeout", status_code=504), True, id="http-504" + ), + ], +) +@pytest.mark.parametrize("matches", [0, 1, 2]) +async def test_create_failure_cleanup_depends_on_listing_and_error( + error, uncertain_when_missing, matches, caplog +): + app = App("demo") + for name in ("a_ok", "b_bad"): + app.queue(name=name, cpu="cpu3c-1-2")(lambda: None) + environment = {"id": "env", "name": "prod", "endpoints": []} + state = {**deepcopy(environment), "activeBuildId": "new-build"} + api = AsyncMock() + + async def save(payload): + if payload["name"] == "a_ok": + state["endpoints"].append( + {"id": "ep-ok", "name": "a_ok", "template": payload["template"]} + ) + return {"id": "ep-ok"} + for index in range(matches): + state["endpoints"].append( + { + "id": f"ep-bad-{index}", + "name": "b_bad", + "template": payload["template"], + } + ) + raise error + + async def delete(endpoint_id): + state["endpoints"] = [ + item for item in state["endpoints"] if item["id"] != endpoint_id + ] + return True + + api.save_endpoint.side_effect = save + api.delete_endpoint.side_effect = delete + api.get_environment_by_name.side_effect = lambda *args: deepcopy(state) + api.delete_environment.return_value = True + interrupted = isinstance(error, (asyncio.CancelledError, KeyboardInterrupt)) + with pytest.raises( + type(error) if interrupted else EndpointReconciliationError + ) as caught: + await reconcile_endpoints( + api, + app, + environment, + "new-build", + "3.12", + activate_build=True, + environment_created=True, + ) + message = caplog.text if interrupted else str(caught.value) + uncertain = matches > 1 or (matches == 0 and uncertain_when_missing) + if uncertain: + api.delete_environment.assert_not_awaited() + assert "b_bad: creation status unknown" in message + assert "Rollback incomplete:" in message + assert "Best-effort rollback completed." not in message + else: + api.delete_environment.assert_awaited_once_with("env") + assert state["endpoints"] == [] + assert "Best-effort rollback completed." in message + assert "creation status unknown" not in message + assert "Remaining workers may still incur charges." not in message + expected_deletes = [("ep-bad-0",), ("ep-ok",)] if matches == 1 else [("ep-ok",)] + assert [ + call.args for call in api.delete_endpoint.await_args_list + ] == expected_deletes + if not interrupted: + assert caught.value.__cause__ is error + + +@pytest.mark.parametrize("current", [None, {}, {"endpoints": None}, {"endpoints": {}}]) +async def test_rejected_create_with_invalid_listing_remains_unknown(current): + app = App("demo") + app.queue(name="worker", cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + api.save_endpoint.side_effect = QueryError("quota exceeded") + api.get_environment_by_name.return_value = current + with pytest.raises(EndpointReconciliationError, match="creation status unknown"): + await reconcile_endpoints( + api, + app, + {"id": "env", "name": "prod"}, + "new-build", + "3.12", + environment_created=True, + ) + api.delete_endpoint.assert_not_awaited() + api.delete_environment.assert_not_awaited() diff --git a/tests/test_apps/test_deploy_review_feedback.py b/tests/test_apps/test_deploy_review_feedback.py new file mode 100644 index 00000000..72bb83a4 --- /dev/null +++ b/tests/test_apps/test_deploy_review_feedback.py @@ -0,0 +1,113 @@ +"""cpu compatibility and deployment rollback safety.""" + +import asyncio +from unittest.mock import AsyncMock, patch + +import pytest + +from runpod.apps import App +from runpod.apps.app import _clear_registry +from runpod.apps.deploy import reconcile_endpoints +from runpod.apps.errors import EndpointReconciliationError, InvalidResourceError + + +@pytest.fixture(autouse=True) +def clean_registry(): + _clear_registry() + yield + _clear_registry() + + +@pytest.mark.parametrize("kind", ["queue", "api", "task"]) +@pytest.mark.parametrize("cpu", ["cpu5g-4-16", "cpu3c-16-32", "cpu9z-32-64"]) +def test_cpu_instance_shapes_are_not_limited_to_enum_members(kind, cpu): + app = App("demo") + handle = getattr(app, kind)(name="worker", cpu=cpu)(lambda: None) + assert handle.spec.cpu == [cpu] + + +@pytest.mark.parametrize( + "cpu", + ["cpu5g", "cpu5g-0-16", "cpu5g-4-0", "cpu5g-4", "cpu5g-4-16-extra", " cpu5g-4-16"], +) +def test_malformed_cpu_instance_ids_fail_before_deployment(cpu): + app = App("demo") + with pytest.raises(InvalidResourceError, match="unknown cpu"): + app.queue(name="worker", cpu=cpu)(lambda: None) + + +async def test_asyncio_timeout_recovers_created_endpoint(): + app = App("demo") + app.queue(name="worker", cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + error = asyncio.TimeoutError("response lost") + api.save_endpoint.side_effect = error + api.get_environment_by_name.return_value = { + "endpoints": [ + { + "id": "ep-created", + "name": "worker", + "template": {"name": "demo-worker-template-token"}, + } + ] + } + with patch("runpod.apps.deploy.secrets.token_hex", return_value="token"): + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints( + api, app, {"id": "env", "name": "prod"}, "new-build", "3.12" + ) + assert caught.value.__cause__ is error + assert ( + str(caught.value) + == "Couldn't deploy 'worker': response lost\nBest-effort rollback completed." + ) + api.delete_endpoint.assert_awaited_once_with("ep-created") + + +@pytest.mark.parametrize("environment_created", [False, True]) +@pytest.mark.parametrize("current", [{"activeBuildId": "other-build"}, {}, None]) +async def test_unconfirmed_ownership_prevents_rollback_writes( + current, environment_created +): + app = App("demo") + for name in ("alpha", "beta", "gamma"): + app.queue(name=name, cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + api.snapshot_endpoint.return_value = {"id": "ep-alpha", "name": "alpha"} + api.save_endpoint.side_effect = [ + {"id": "ep-alpha"}, + {"id": "ep-beta"}, + RuntimeError("quota exceeded"), + ] + api.get_environment_by_name.return_value = current + environment = { + "id": "env", + "name": "prod", + "activeBuildId": None if environment_created else "old-build", + "endpoints": ( + [] if environment_created else [{"id": "ep-alpha", "name": "alpha"}] + ), + } + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints( + api, + app, + environment, + "new-build", + "3.12", + activate_build=True, + environment_created=environment_created, + ) + message = str(caught.value) + assert "Rollback incomplete:" in message + assert "Best-effort rollback completed." not in message + assert "rp flash env get prod --app demo" in message + assert "may still incur charges" in message + if current: + assert "environment changed during deployment" in message + else: + assert "activation status unknown" in message + api.deploy_build.assert_awaited_once_with("env", "new-build") + assert api.save_endpoint.await_count == 3 + api.delete_endpoint.assert_not_awaited() + api.delete_environment.assert_not_awaited() diff --git a/tests/test_apps/test_deploy_rollback.py b/tests/test_apps/test_deploy_rollback.py new file mode 100644 index 00000000..0d18a814 --- /dev/null +++ b/tests/test_apps/test_deploy_rollback.py @@ -0,0 +1,378 @@ +"""endpoint snapshots and deployment rollback ordering.""" + +from copy import deepcopy +from unittest.mock import AsyncMock, patch + +import pytest + +from runpod.api.queries.apps import QUERY_ENDPOINT_SNAPSHOT +from runpod.api.mutations.apps import MUTATION_SAVE_ENDPOINT +from runpod.apps import App +from runpod.apps.api import AppsApiClient +from runpod.apps.app import _clear_registry +from runpod.apps.deploy import reconcile_endpoints +from runpod.apps.errors import EndpointReconciliationError + + +@pytest.fixture(autouse=True) +def clean_registry(): + _clear_registry() + yield + _clear_registry() + + +def snapshot(name="worker", endpoint_id="ep-old"): + return { + "id": endpoint_id, + "name": name, + "type": "QB", + "instanceIds": ["cpu3c-1-2"], + "gpuIds": None, + "gpuCount": 1, + "locations": "EU-RO-1", + "workersMin": 1, + "workersMax": 2, + "workersPFBTarget": 0, + "idleTimeout": 120, + "scalerType": "QUEUE_DELAY", + "scalerValue": 5, + "executionTimeoutMs": 5000, + "workerInitTimeoutMs": 10000, + "flashBootType": "OFF", + "minCudaVersion": None, + "allowedCudaVersions": "", + "modelReferences": [], + "env": [{"key": "CUSTOM", "value": "synthetic-private-value"}], + "networkVolumeIds": [{"networkVolumeId": "volume-old"}], + "volumes": [{"volumeId": "volume-old", "volumeType": "NETWORK_VOLUME"}], + "template": { + "name": "old-template", + "imageName": "old-image", + "containerDiskInGb": 10, + "dockerArgs": "old-command", + "env": [{"key": "RUNPOD_BUILD_ID", "value": "old-build"}], + "ports": None, + "containerRegistryAuthId": None, + "advancedStart": False, + "startScript": None, + "config": None, + }, + } + + +async def test_snapshot_is_a_restorable_copy_of_endpoint_and_template(): + original = snapshot() + client = AppsApiClient() + client._execute = AsyncMock(return_value={"myself": {"endpoint": original}}) + saved = await client.snapshot_endpoint("ep-old") + client._execute.assert_awaited_once_with( + QUERY_ENDPOINT_SNAPSHOT, {"id": "ep-old"}, retry=True + ) + assert saved == { + **original, + "template": {**original["template"], "containerRegistryAuthId": ""}, + "volumes": [], + } + saved["template"]["env"][0]["value"] = "modified" + assert original["template"]["env"][0]["value"] == "old-build" + assert original["template"]["containerRegistryAuthId"] is None + + +async def test_snapshot_retains_global_volumes_and_empty_values(): + original = snapshot() + original.update(env=None, modelReferences=None, networkVolumeIds=None) + original["template"].update(env=None, dockerArgs=None) + original["volumes"] = [ + {"volumeId": "global-old", "volumeType": "OBJECT_STORE_VOLUME"} + ] + client = AppsApiClient() + client._execute = AsyncMock(return_value={"myself": {"endpoint": original}}) + saved = await client.snapshot_endpoint("ep-old") + assert saved["volumes"] == original["volumes"] + assert saved["env"] == saved["modelReferences"] == saved["networkVolumeIds"] == [] + assert saved["template"]["env"] == [] + assert saved["template"]["dockerArgs"] == "" + + +async def test_snapshot_can_be_saved_through_the_control_plane_client(): + client = AppsApiClient() + client._execute = AsyncMock( + side_effect=[ + {"myself": {"endpoint": snapshot()}}, + {"saveEndpoint": {"id": "ep-old"}}, + ] + ) + saved = await client.snapshot_endpoint("ep-old") + assert await client.save_endpoint(saved) == {"id": "ep-old"} + client._execute.assert_awaited_with(MUTATION_SAVE_ENDPOINT, {"input": saved}) + + +@pytest.mark.parametrize( + "current", [None, {"activeBuildId": "new-build"}, {"activeBuildId": None}] +) +async def test_first_activation_failure_reports_unrestorable_build_state(current): + app = App("demo") + app.queue(name="worker", cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + api.deploy_build.side_effect = TimeoutError("response lost") + api.get_environment_by_name.return_value = current + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints( + api, + app, + {"id": "env", "name": "prod"}, + "new-build", + "3.12", + activate_build=True, + ) + if current == {"activeBuildId": None}: + assert "Best-effort rollback completed." in str(caught.value) + else: + assert "Rollback incomplete:\n build:" in str(caught.value) + api.save_endpoint.assert_not_awaited() + + +@pytest.mark.parametrize( + "endpoint", [None, {"id": "other"}, {"id": "ep-old", "template": None}] +) +async def test_snapshot_fails_closed_when_current_state_is_unavailable(endpoint): + client = AppsApiClient() + client._execute = AsyncMock(return_value={"myself": {"endpoint": endpoint}}) + with pytest.raises(RuntimeError, match="no restorable configuration"): + await client.snapshot_endpoint("ep-old") + + +def app_and_environment(): + app = App("demo") + for name in ("alpha", "beta", "gamma"): + app.queue(name=name, cpu="cpu3c-1-2")(lambda x: x) + environment = { + "id": "env", + "name": "prod", + "activeBuildId": "old-build", + "endpoints": [ + {"id": "ep-alpha", "name": "alpha"}, + {"id": "ep-beta", "name": "beta"}, + ], + } + return app, environment + + +async def test_restores_full_state_of_successful_and_failed_updates_in_reverse_order(): + app, environment = app_and_environment() + alpha = snapshot("alpha", "ep-alpha") + beta = snapshot("beta", "ep-beta") + api = AsyncMock() + api.get_environment_by_name.return_value = {"activeBuildId": "new-build"} + api.snapshot_endpoint.side_effect = [deepcopy(alpha), deepcopy(beta)] + api.save_endpoint.side_effect = [ + {"id": "ep-alpha"}, + TimeoutError("response lost"), + {"id": "ep-beta"}, + {"id": "ep-alpha"}, + ] + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints( + api, app, environment, "new-build", "3.12", activate_build=True + ) + assert ( + str(caught.value) + == "Couldn't deploy 'beta': response lost\nBest-effort rollback completed." + ) + calls = api.save_endpoint.await_args_list + assert calls[2].args[0] == {**beta, "flashEnvironmentId": "env"} + assert calls[3].args[0] == {**alpha, "flashEnvironmentId": "env"} + assert [call[0] for call in api.mock_calls[:3]] == [ + "snapshot_endpoint", + "snapshot_endpoint", + "deploy_build", + ] + assert [call.args for call in api.deploy_build.await_args_list] == [ + ("env", "new-build"), + ("env", "old-build"), + ] + assert api.mock_calls[-3][0] == "deploy_build" + api.delete_endpoint.assert_not_awaited() + assert "synthetic-private-value" not in str(caught.value) + + +async def test_snapshot_failure_stops_before_any_writes(): + app, environment = app_and_environment() + api = AsyncMock() + api.snapshot_endpoint.side_effect = [snapshot(), RuntimeError("access denied")] + with pytest.raises( + EndpointReconciliationError, match="Couldn't read 'beta': access denied" + ): + await reconcile_endpoints( + api, app, environment, "new-build", "3.12", activate_build=True + ) + api.save_endpoint.assert_not_awaited() + api.deploy_build.assert_not_awaited() + api.delete_endpoint.assert_not_awaited() + + +@pytest.mark.parametrize("restore_failure", [False, True]) +async def test_activation_failure_restores_endpoints_and_previous_build( + restore_failure, +): + app, environment = app_and_environment() + api = AsyncMock() + api.get_environment_by_name.return_value = {"activeBuildId": "new-build"} + api.snapshot_endpoint.side_effect = [ + snapshot("alpha", "ep-alpha"), + snapshot("beta", "ep-beta"), + ] + api.save_endpoint.side_effect = lambda payload: { + "id": payload.get("id", "ep-gamma") + } + api.deploy_build.side_effect = [ + TimeoutError("activation timed out"), + RuntimeError("build restore denied") if restore_failure else {"id": "env"}, + ] + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints( + api, app, environment, "new-build", "3.12", activate_build=True + ) + assert [call.args for call in api.deploy_build.await_args_list] == [ + ("env", "new-build"), + ("env", "old-build"), + ] + api.delete_endpoint.assert_not_awaited() + api.save_endpoint.assert_not_awaited() + if restore_failure: + assert "Rollback incomplete:\n build: build restore denied" in str( + caught.value + ) + else: + assert ( + str(caught.value) + == "Couldn't activate the build: activation timed out\nBest-effort rollback completed." + ) + + +async def test_restore_failure_does_not_skip_other_endpoints(): + app, environment = app_and_environment() + api = AsyncMock() + api.snapshot_endpoint.side_effect = [ + snapshot("alpha", "ep-alpha"), + snapshot("beta", "ep-beta"), + ] + api.save_endpoint.side_effect = [ + {"id": "ep-alpha"}, + RuntimeError("update failed"), + RuntimeError("restore denied"), + {"id": "ep-alpha"}, + ] + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints(api, app, environment, "new-build", "3.12") + assert "Rollback incomplete:\n beta (ep-beta): restore denied" in str(caught.value) + assert api.save_endpoint.await_args.args[0]["id"] == "ep-alpha" + + +async def test_lost_create_response_is_recovered_by_unique_template_name(): + app = App("demo") + app.queue(name="worker", cpu="cpu3c-1-2")(lambda: None) + environment = {"id": "env", "name": "prod", "endpoints": []} + api = AsyncMock() + api.save_endpoint.side_effect = TimeoutError("response lost") + api.get_environment_by_name.return_value = { + "endpoints": [ + { + "id": "ep-created", + "name": "worker", + "template": {"name": "demo-worker-template-token"}, + }, + { + "id": "ep-other", + "name": "worker", + "template": {"name": "another-deploy"}, + }, + ] + } + with patch("runpod.apps.deploy.secrets.token_hex", return_value="token"): + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints(api, app, environment, "new-build", "3.12") + api.delete_endpoint.assert_awaited_once_with("ep-created") + assert ( + str(caught.value) + == "Couldn't deploy 'worker': response lost\nBest-effort rollback completed." + ) + + +async def test_activation_precedes_irreversible_cleanup(): + app, environment = app_and_environment() + environment["endpoints"].append({"name": "obsolete", "id": "ep-obsolete"}) + api = AsyncMock() + api.save_endpoint.side_effect = lambda payload: { + "id": payload.get("id", "ep-gamma") + } + await reconcile_endpoints( + api, app, environment, "new-build", "3.12", activate_build=True + ) + calls = [call[0] for call in api.mock_calls] + assert calls.index("deploy_build") < min( + i for i, name in enumerate(calls) if name == "save_endpoint" + ) + assert calls.index("delete_endpoint") > max( + i for i, name in enumerate(calls) if name == "save_endpoint" + ) + + +@pytest.mark.parametrize("cleanup_fails", [False, True]) +async def test_new_environment_is_removed_after_endpoint_rollback(cleanup_fails): + app = App("demo") + app.queue(name="alpha", cpu="cpu3c-1-2")(lambda: None) + app.queue(name="beta", cpu="cpu3c-1-2")(lambda: None) + environment = {"id": "env", "name": "prod", "endpoints": []} + api = AsyncMock() + api.get_environment_by_name.return_value = { + "id": "env", + "endpoints": [], + "activeBuildId": "new-build", + } + + async def save(payload): + endpoint_id = f"ep-{payload['name']}" + api.get_environment_by_name.return_value["endpoints"].append( + {"id": endpoint_id, "name": payload["name"], "template": payload["template"]} + ) + if payload["name"] == "alpha": + return {"id": endpoint_id} + raise RuntimeError("quota exceeded") + + async def delete(endpoint_id): + current = api.get_environment_by_name.return_value + current["endpoints"] = [ + endpoint for endpoint in current["endpoints"] if endpoint["id"] != endpoint_id + ] + return True + + api.save_endpoint.side_effect = save + api.delete_endpoint.side_effect = delete + if cleanup_fails: + api.delete_endpoint.side_effect = RuntimeError("delete denied") + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints( + api, + app, + environment, + "new-build", + "3.12", + activate_build=True, + environment_created=True, + ) + if cleanup_fails: + api.delete_environment.assert_not_awaited() + assert "Rollback incomplete:" in str(caught.value) + else: + api.delete_environment.assert_awaited_once_with("env") + assert [call.args for call in api.delete_endpoint.await_args_list] == [ + ("ep-beta",), + ("ep-alpha",), + ] + calls = [call[0] for call in api.mock_calls] + assert calls.index("delete_endpoint") < calls.index("delete_environment") + assert ( + str(caught.value) + == "Couldn't deploy 'beta': quota exceeded\nBest-effort rollback completed." + ) diff --git a/tests/test_apps/test_deploy_sigint.py b/tests/test_apps/test_deploy_sigint.py new file mode 100644 index 00000000..b892b58f --- /dev/null +++ b/tests/test_apps/test_deploy_sigint.py @@ -0,0 +1,158 @@ +"""rollback diagnostics during asyncio runner shutdown.""" + +import asyncio +import subprocess +import sys +import textwrap +from pathlib import Path +from unittest.mock import AsyncMock + +import pytest + +from runpod.apps import App +from runpod.apps.app import _clear_registry +from runpod.apps.deploy import reconcile_endpoints + + +@pytest.fixture(autouse=True) +def clean_registry(): + _clear_registry() + yield + _clear_registry() + + +@pytest.mark.skipif( + sys.version_info < (3, 11), reason="requires asyncio.Runner SIGINT handling" +) +@pytest.mark.parametrize("interrupt_cleanup", [False, True]) +def test_sigint_reports_rollback_progress(interrupt_cleanup): + script = textwrap.dedent(""" + import asyncio + import logging + import signal + import sys + from unittest.mock import AsyncMock + + from runpod.apps import App + from runpod.apps.deploy import reconcile_endpoints + + logging.basicConfig(level=logging.WARNING) + app = App("demo") + names = ("alpha", "beta", "gamma") + for name in names: + app.queue(name=name, cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + api.snapshot_endpoint.side_effect = [ + {"id": f"ep-{name}", "name": name} for name in names + ] + api.get_environment_by_name.return_value = {"activeBuildId": "new-build"} + + async def save(payload): + if "template" in payload: + if payload["name"] == "gamma": + asyncio.get_running_loop().call_soon(signal.raise_signal, signal.SIGINT) + await asyncio.Future() + else: + if payload["name"] == "beta" and sys.argv[1] == "True": + asyncio.get_running_loop().call_soon(signal.raise_signal, signal.SIGINT) + await asyncio.Future() + print("RESTORED " + payload["name"], flush=True) + return {"id": payload["id"]} + + api.save_endpoint.side_effect = save + environment = { + "id": "env", + "name": "prod", + "activeBuildId": "old-build", + "endpoints": [{"id": f"ep-{name}", "name": name} for name in names], + } + try: + asyncio.run(reconcile_endpoints( + api, app, environment, "new-build", "3.12", activate_build=True + )) + except KeyboardInterrupt: + print("INTERRUPT PROPAGATED", flush=True) + else: + raise AssertionError("SIGINT did not propagate") + """) + result = subprocess.run( + [sys.executable, "-c", script, str(interrupt_cleanup)], + cwd=Path(__file__).resolve().parents[2], + capture_output=True, + text=True, + timeout=15, + ) + assert result.returncode == 0, result.stderr + assert "INTERRUPT PROPAGATED" in result.stdout + assert "RESTORED gamma" in result.stdout + if interrupt_cleanup: + assert "RESTORED beta" not in result.stdout + assert "RESTORED alpha" not in result.stdout + assert "Rollback interrupted" in result.stderr + assert "restore 'beta' (ep-beta)" in result.stderr + assert "Restored build old-build." in result.stderr + assert "Restored endpoint 'gamma' (ep-gamma)." in result.stderr + assert "rp flash env get prod --app demo" in result.stderr + assert "Remaining workers may still incur charges." in result.stderr + assert "Best-effort rollback completed." not in result.stderr + else: + assert "RESTORED beta" in result.stdout + assert "RESTORED alpha" in result.stdout + assert "Best-effort rollback completed." in result.stderr + assert "Rollback interrupted" not in result.stderr + + +async def test_cleanup_cancellation_preserves_completed_deletes_and_prior_errors( + caplog, +): + app = App("demo") + for name in ("alpha", "beta", "gamma", "omega"): + app.queue(name=name, cpu="cpu3c-1-2")(lambda: None) + api = AsyncMock() + api.save_endpoint.side_effect = [ + {"id": "ep-alpha"}, + {"id": "ep-beta"}, + {"id": "ep-gamma"}, + RuntimeError("quota exceeded"), + ] + api.delete_endpoint.side_effect = [ + True, + RuntimeError("delete denied"), + asyncio.CancelledError(), + ] + with pytest.raises(asyncio.CancelledError): + await reconcile_endpoints( + api, app, {"id": "env", "name": "prod"}, "new-build", "3.12" + ) + assert "Couldn't deploy 'omega': quota exceeded" in caplog.text + assert "Deleted endpoint 'gamma' (ep-gamma)." in caplog.text + assert "beta (ep-beta): delete denied" in caplog.text + assert ( + "Rollback interrupted while attempting to delete 'alpha' (ep-alpha)." + in caplog.text + ) + assert "rp flash env get prod --app demo" in caplog.text + assert "Best-effort rollback completed." not in caplog.text + + +async def test_cleanup_cancellation_during_ownership_read_reports_hint(caplog): + app = App("demo") + api = AsyncMock() + api.deploy_build.side_effect = RuntimeError("activation response lost") + api.get_environment_by_name.side_effect = asyncio.CancelledError() + with pytest.raises(asyncio.CancelledError): + await reconcile_endpoints( + api, + app, + {"id": "env", "name": "prod"}, + "new-build", + "3.12", + activate_build=True, + ) + assert ( + "Rollback interrupted while attempting to check deployment ownership." + in caplog.text + ) + assert "rp flash env get prod --app demo" in caplog.text + assert "Best-effort rollback completed." not in caplog.text + api.delete_endpoint.assert_not_awaited() diff --git a/tests/test_apps/test_deployed_tasks.py b/tests/test_apps/test_deployed_tasks.py index 45478ab3..30e835da 100644 --- a/tests/test_apps/test_deployed_tasks.py +++ b/tests/test_apps/test_deployed_tasks.py @@ -450,6 +450,12 @@ def work(): "id": "app", "flashEnvironments": [{"id": "env", "name": "default"}], } + api.get_environment_by_name.return_value = { + "id": "env", + "name": "default", + "activeBuildId": None, + "endpoints": [], + } api.prepare_artifact_upload.return_value = { "uploadUrl": "upload", "objectKey": "key", diff --git a/tests/test_apps/test_deployment_validation.py b/tests/test_apps/test_deployment_validation.py index 7853c852..16ed0256 100644 --- a/tests/test_apps/test_deployment_validation.py +++ b/tests/test_apps/test_deployment_validation.py @@ -36,6 +36,12 @@ def deployment_api(): "id": "app", "flashEnvironments": [{"id": "env", "name": "default"}], } + api.get_environment_by_name.return_value = { + "id": "env", + "name": "default", + "activeBuildId": None, + "endpoints": [], + } api.prepare_artifact_upload.return_value = { "uploadUrl": "upload", "objectKey": "key", diff --git a/tests/test_apps/test_partial_deploy.py b/tests/test_apps/test_partial_deploy.py new file mode 100644 index 00000000..7543f82e --- /dev/null +++ b/tests/test_apps/test_partial_deploy.py @@ -0,0 +1,267 @@ +"""partial deployment diagnostics and preflight validation.""" + +import io +from unittest.mock import AsyncMock, Mock, patch + +import pytest +from click.testing import CliRunner +from rich.console import Console + +from runpod.apps import App +from runpod.apps.app import _clear_registry +from runpod.apps.build import BuildResult +from runpod.apps.deploy import deploy_app, reconcile_endpoints +from runpod.apps.errors import EndpointReconciliationError, InvalidResourceError +from runpod.apps.gpu import CpuInstanceType +from runpod.rp_cli import console as ui +from runpod.rp_cli.main import cli + + +@pytest.fixture(autouse=True) +def clean_registry(): + _clear_registry() + yield + _clear_registry() + + +def make_app(): + app = App("partial") + for name in ("c_later", "b_bad", "a_ok"): + app.queue(name=name, cpu="cpu3c-1-2")(lambda x: x) + return app + + +def environment(endpoints=None): + return { + "id": "env-1", + "name": "prod", + "endpoints": endpoints or [], + "activeBuildId": "build-old", + } + + +@pytest.mark.parametrize("updating", [False, True]) +@pytest.mark.parametrize( + "cause", [RuntimeError("quota exceeded"), TimeoutError("timed out")] +) +async def test_reports_confirmed_changes_and_failed_request(updating, cause): + api = AsyncMock() + snapshot = {"id": "ep-ok", "name": "a_ok", "workersMin": 2} + api.snapshot_endpoint.return_value = snapshot.copy() + api.get_environment_by_name.return_value = environment() + api.save_endpoint.side_effect = [{"id": "ep-ok"}, cause, {"id": "ep-ok"}] + existing = [{"name": "a_ok", "id": "ep-ok"}] if updating else [] + existing.append({"name": "obsolete", "id": "ep-old"}) + + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints( + api, make_app(), environment(existing), "build-1", "3.12" + ) + + message = str(caught.value) + assert caught.value.__cause__ is cause + assert f"Couldn't deploy 'b_bad': {cause}" in message + if isinstance(cause, TimeoutError): + assert "Rollback incomplete:\n b_bad: creation status unknown" in message + assert "rp flash env get prod --app partial" in message + assert "Best-effort rollback completed." not in message + else: + assert ( + message + == "Couldn't deploy 'b_bad': quota exceeded\nBest-effort rollback completed." + ) + assert [call.args[0]["name"] for call in api.save_endpoint.await_args_list[:2]] == [ + "a_ok", + "b_bad", + ] + if updating: + api.delete_endpoint.assert_not_awaited() + assert api.save_endpoint.await_args.args[0] == { + **snapshot, + "flashEnvironmentId": "env-1", + } + else: + api.delete_endpoint.assert_awaited_once_with("ep-ok") + + +async def test_first_update_failure_identifies_existing_endpoint(): + api = AsyncMock() + snapshot = {"id": "ep-old", "name": "a_ok", "workersMin": 2} + api.snapshot_endpoint.return_value = snapshot + api.save_endpoint.side_effect = [RuntimeError("rejected"), {"id": "ep-old"}] + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints( + api, + make_app(), + environment([{"name": "a_ok", "id": "ep-old"}]), + "build-1", + "3.12", + ) + assert str(caught.value) == "Couldn't deploy 'a_ok': rejected\nBest-effort rollback completed." + api.delete_endpoint.assert_not_awaited() + assert api.save_endpoint.await_count == 2 + assert api.save_endpoint.await_args.args[0] == snapshot + + +async def test_preparation_failure_reports_earlier_changes(): + api = AsyncMock() + api.save_endpoint.return_value = {"id": "ep-ok"} + with patch( + "runpod.apps.volume.attach_endpoint_volumes", + AsyncMock(side_effect=[None, RuntimeError("volume unavailable")]), + ): + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints(api, make_app(), environment(), "build-1", "3.12") + assert ( + str(caught.value) + == "Couldn't prepare 'b_bad': volume unavailable\nBest-effort rollback completed." + ) + api.save_endpoint.assert_awaited_once() + api.delete_endpoint.assert_awaited_once_with("ep-ok") + + +async def test_deletion_failure_reports_creates_updates_and_deletes(): + api = AsyncMock() + api.save_endpoint.side_effect = lambda payload: {"id": f"ep-{payload['name']}"} + api.delete_endpoint.side_effect = [True, RuntimeError("delete denied"), True, True] + existing = [ + {"name": name, "id": f"ep-{name}"} for name in ("b_bad", "old1", "old2", "old3") + ] + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints( + api, make_app(), environment(existing), "build-1", "3.12" + ) + message = str(caught.value) + assert "Deployed, but couldn't remove 'old2' (ep-old2): delete denied" in message + assert "rolled back" not in message + assert api.save_endpoint.await_count == 3 + assert [call.args for call in api.delete_endpoint.await_args_list] == [ + ("ep-old1",), + ("ep-old2",), + ] + + +@pytest.mark.parametrize("cleanup_result", [RuntimeError("cleanup denied"), False]) +async def test_rollback_continues_after_cleanup_failure(cleanup_result): + api = AsyncMock() + cause = RuntimeError("quota exceeded") + api.save_endpoint.side_effect = [{"id": "ep-a"}, {"id": "ep-b"}, cause] + api.delete_endpoint.side_effect = [cleanup_result, True] + with pytest.raises(EndpointReconciliationError) as caught: + await reconcile_endpoints(api, make_app(), environment(), "build-1", "3.12") + message = str(caught.value) + assert caught.value.__cause__ is cause + assert "Couldn't deploy 'c_later': quota exceeded" in message + assert "Rollback incomplete:\n c_later: creation status unknown" in message + assert "\n b_bad (ep-b):" in message + assert "a_ok" not in message + assert "may still incur charges" in message + assert [call.args for call in api.delete_endpoint.await_args_list] == [ + ("ep-b",), + ("ep-a",), + ] + + +async def test_success_keeps_created_endpoints(): + api = AsyncMock() + api.save_endpoint.side_effect = lambda payload: {"id": f"ep-{payload['name']}"} + result = await reconcile_endpoints( + api, make_app(), environment(), "build-1", "3.12" + ) + assert result == {"a_ok": "ep-a_ok", "b_bad": "ep-b_bad", "c_later": "ep-c_later"} + api.delete_endpoint.assert_not_awaited() + + +def test_cli_reports_partial_deploy_and_failed_phase(tmp_path, monkeypatch): + (tmp_path / "main.py").write_text( + 'from runpod import App\napp = App("partial")\n' + '@app.queue(name="a_ok", cpu="cpu3c-1-2")\n' + "def a_ok(x): return x\n" + '@app.queue(name="b_bad", cpu="cpu3c-1-2")\n' + "def b_bad(x): return x\n" + ) + env_dir = tmp_path / "vendor" + env_dir.mkdir() + api = AsyncMock() + api.get_app_by_name.return_value = { + "id": "app-1", + "flashEnvironments": [environment()], + } + api.prepare_artifact_upload.return_value = { + "uploadUrl": "https://upload.invalid", + "objectKey": "key", + } + api.finalize_artifact_upload.return_value = {"id": "build-1"} + api.get_environment_by_name.side_effect = [ + environment(), + {**environment(), "activeBuildId": "build-1"}, + environment(), + ] + api.save_endpoint.side_effect = [{"id": "ep-ok"}, RuntimeError("quota exceeded")] + buffer = io.StringIO() + monkeypatch.setattr(ui, "console", Console(file=buffer, theme=ui.theme, width=120)) + with ( + patch("runpod.apps.deploy.AppsApiClient", return_value=api), + patch( + "runpod.apps.deploy.build_environment", + return_value=BuildResult(env_dir, []), + ), + ): + result = CliRunner().invoke( + cli, ["flash", "deploy", str(tmp_path), "-e", "prod"] + ) + assert result.exit_code == 1, result.output + assert ( + result.output == "Error: Couldn't deploy 'b_bad': quota exceeded\n" + "Best-effort rollback completed.\n" + ) + assert "✗ deploying endpoints" in buffer.getvalue() + assert "✓ deploying endpoints" not in buffer.getvalue() + assert "is live" not in buffer.getvalue() + assert [call.args for call in api.deploy_build.await_args_list] == [ + ("env-1", "build-1"), + ("env-1", "build-old"), + ] + api.delete_endpoint.assert_awaited_once_with("ep-ok") + + +@pytest.mark.parametrize("kind", ["queue", "api"]) +@pytest.mark.parametrize("timeout", [0, -1, 3601, 5000, 99999, 1.5, True, "60", None]) +def test_idle_timeout_rejected_at_decoration(kind, timeout): + app = App("invalid") + with pytest.raises(InvalidResourceError, match="idle_timeout"): + getattr(app, kind)(name="worker", cpu="cpu3c-1-2", idle_timeout=timeout)( + lambda: None + ) + + +@pytest.mark.parametrize("timeout", [1, 3600]) +@pytest.mark.parametrize("cpu", list(CpuInstanceType)) +def test_accepts_timeout_boundaries_and_supported_cpu_flavors(timeout, cpu): + app = App("valid") + handle = app.queue(name="worker", cpu=cpu, idle_timeout=timeout)(lambda: None) + assert handle.spec.idle_timeout == timeout + assert handle.spec.cpu == [cpu.value] + + +@pytest.mark.parametrize("kind", ["queue", "api", "task"]) +@pytest.mark.parametrize("cpu", ["cpu9z", ["cpu3c-1-2", "cpu9z"]]) +def test_cpu_flavor_rejected_at_decoration(kind, cpu): + app = App("invalid") + with pytest.raises(InvalidResourceError, match="unknown cpu 'cpu9z'"): + getattr(app, kind)(name="worker", cpu=cpu)(lambda: None) + + +@pytest.mark.parametrize("field,value", [("idle_timeout", 5000), ("cpu", ["cpu9z"])]) +async def test_mutated_invalid_spec_fails_before_build_and_remote_calls( + tmp_path, field, value +): + app = make_app() + setattr(app.resources["b_bad"].spec, field, value) + api = AsyncMock() + build = Mock() + with patch("runpod.apps.deploy.build_environment", build): + with pytest.raises(InvalidResourceError): + await deploy_app(app, tmp_path, api=api) + build.assert_not_called() + assert not api.mock_calls diff --git a/tests/test_apps/test_volume_preflight.py b/tests/test_apps/test_volume_preflight.py index c4b82282..e5db2568 100644 --- a/tests/test_apps/test_volume_preflight.py +++ b/tests/test_apps/test_volume_preflight.py @@ -98,6 +98,7 @@ async def test_preflight_plans_shared_storage_without_creating(api): await resolver.preflight(specs) + assert resolver.created_volumes == [] api.create_network_volume.assert_not_awaited() api.list_network_volumes.assert_awaited_once() api.network_volume_datacenters.assert_awaited_once() @@ -110,17 +111,24 @@ async def test_preflight_plans_shared_storage_without_creating(api): api.create_network_volume.assert_awaited_once_with( name="shared", size=50, data_center_id="EU-RO-1" ) + assert resolver.created_volumes == [ + {"kind": "network", "name": "shared", "id": "nv-new"} + ] async def test_global_creation_is_deferred_until_resolution(api): resolver = VolumeResolver(api) volume = GlobalVolume("global") await resolver.preflight([_spec("a", volume)]) + assert resolver.created_volumes == [] api.create_global_volume.assert_not_awaited() assert await resolver.resolve(volume) == {"id": "gv-new"} api.create_global_volume.assert_awaited_once_with(name="global") assert api.list_global_volumes.await_count == 2 api.network_volume_datacenters.assert_not_awaited() + assert resolver.created_volumes == [ + {"kind": "global", "name": "global", "id": "gv-new"} + ] @pytest.mark.parametrize("datacenter", ["EU-RO-1", "US-MO-2"])