diff --git a/README.md b/README.md index 91c3740a..90cfecca 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,25 @@ rp flash dev main.py # live dev session: edit, re-run, logs stream back rp flash deploy # deploy production endpoints ``` +To run a worker image you already built, declare it with `app.worker_image`. +The image's own handler serves the jobs, and `args` replaces its start command +(leave it out to keep the image's own). Keyword arguments become the job input: + +```python +echo = app.worker_image( + name="echo", + image="runpod/mock-worker:latest", + args="python3 -u /handler.py --generator", + gpu="ADA_24", + workers=(0, 3), +) + +echo.remote(mock_return="hello") +``` + +`rp flash dev`, `rp flash deploy` and `rp flash undeploy` manage it like any +other queue resource. + Recurring schedules are not supported by `runpod.apps`. For periodic jobs, use an external scheduler to invoke a deployed queue function with `.spawn()`. diff --git a/runpod/apps/__init__.py b/runpod/apps/__init__.py index 8420361a..7f8d095e 100644 --- a/runpod/apps/__init__.py +++ b/runpod/apps/__init__.py @@ -13,7 +13,7 @@ RemoteExecutionError, ScheduleNotSupported, ) -from .handles import ApiHandle, FunctionHandle +from .handles import ApiHandle, FunctionHandle, WorkerImageHandle from .job import Job from .markers import delete, get, init, patch, post, put from .model import Model @@ -46,6 +46,7 @@ "ResourceKind", "ResourceSpec", "RouteSpec", + "WorkerImageHandle", "ScheduleNotSupported", "current_context", "delete", diff --git a/runpod/apps/app.py b/runpod/apps/app.py index 18f100ba..f35ec00b 100644 --- a/runpod/apps/app.py +++ b/runpod/apps/app.py @@ -23,7 +23,7 @@ async def transcribe(audio_url: str): ... from .context import Context, current_context from .errors import EndpointNotFound, InvalidResourceError from .gpu import GpuLike -from .handles import ApiHandle, FunctionHandle +from .handles import ApiHandle, FunctionHandle, WorkerImageHandle from .spec import ( DEFAULT_SCALER_VALUE, ResourceKind, @@ -32,6 +32,8 @@ async def transcribe(audio_url: str): ... from .targets import InvocationTarget, PodTarget, SentinelTarget from .volume import Volume +Handle = FunctionHandle | ApiHandle | WorkerImageHandle + DEFAULT_ENV = "default" _REGISTRY: list["App"] = [] @@ -61,16 +63,16 @@ def __init__(self, name: str, *, env: str = DEFAULT_ENV): self.name = name self.env = env self._source_file = Path(sys._getframe(1).f_code.co_filename).resolve() - self._resources: dict[str, FunctionHandle | ApiHandle] = {} + self._resources: dict[str, Handle] = {} self._dev_events: object | None = None self._dev_targets: dict[str, InvocationTarget] = {} _REGISTRY.append(self) @property - def resources(self) -> dict[str, FunctionHandle | ApiHandle]: + def resources(self) -> dict[str, Handle]: return dict(self._resources) - def _register(self, name: str, handle: FunctionHandle | ApiHandle) -> None: + def _register(self, name: str, handle: Handle) -> None: if name in self._resources: raise InvalidResourceError( f"duplicate resource name '{name}' in app '{self.name}'" @@ -141,6 +143,72 @@ def decorator(fn: Callable) -> FunctionHandle: return decorator + def worker_image( + self, + *, + name: str, + image: str, + args: str | None = None, + gpu: GpuLike | list[GpuLike] | None = None, + cpu: str | list[str] | None = None, + gpu_count: int = 1, + workers: int | tuple[int, int] | None = None, + idle_timeout: int = 60, + mounts: Mapping[str, Volume] | None = None, + env: dict[str, Any] | None = None, + datacenter: str | list[str] | None = None, + registry_auth: str | None = None, + max_concurrency: int = 1, + execution_timeout_ms: int = 0, + flashboot: bool = True, + scaler_type: str | None = None, + scaler_value: int = DEFAULT_SCALER_VALUE, + min_cuda_version: str | None = None, + container_disk_gb: int | None = None, + ) -> WorkerImageHandle: + """declare a queue endpoint that runs a prebuilt worker image. + + the image's own handler serves jobs; nothing from this project + runs on the worker. args replaces the image's start command + (the container's docker args); omit it to keep the image's own. + + mock = app.worker_image( + name="mock-worker", + image="runpod/mock-worker:latest", + args="python3 -u /handler.py --generator", + gpu="ADA_24", + ) + mock.remote(mock_return="hello") + + calls send their keyword arguments as the job input. + """ + spec = ResourceSpec( + kind=ResourceKind.QUEUE, + name=name, + gpu=gpu, + cpu=cpu, + gpu_count=gpu_count, + workers=workers, + idle_timeout=idle_timeout, + mounts=mounts, + env=env, + datacenter=datacenter, + image=image, + registry_auth=registry_auth, + max_concurrency=max_concurrency, + execution_timeout_ms=execution_timeout_ms, + flashboot=flashboot, + scaler_type=scaler_type, + scaler_value=scaler_value, + min_cuda_version=min_cuda_version, + container_disk_gb=container_disk_gb, + image_only=True, + docker_args=args, + ) + handle = WorkerImageHandle(self, spec) + self._register(spec.name, handle) + return handle + def task( self, *, diff --git a/runpod/apps/deploy.py b/runpod/apps/deploy.py index beaf6cf6..0dee1e6c 100644 --- a/runpod/apps/deploy.py +++ b/runpod/apps/deploy.py @@ -406,7 +406,10 @@ def _deployed_endpoint_input( if spec.flashboot: payload["flashBootType"] = "FLASHBOOT" - if spec.image: + if spec.image_only: + # a prebuilt worker image runs its own handler, not the runtime + payload["template"]["dockerArgs"] = spec.docker_args or "" + elif spec.image: # custom images install the runtime before attaching the artifact payload["template"]["env"].append( {"key": "RUNPOD_RUNTIME_KIND", "value": spec.kind.value} diff --git a/runpod/apps/dev.py b/runpod/apps/dev.py index 5177b6c4..8bcf996a 100644 --- a/runpod/apps/dev.py +++ b/runpod/apps/dev.py @@ -147,9 +147,11 @@ def _endpoint_input( # nested .remote() calls from inside a dev worker need # credentials and the dev-session marker to resolve # sibling dev endpoints by name + # prebuilt worker images run third-party handlers that + # make no nested calls, so they never get the account key *( [{"key": "RUNPOD_API_KEY", "value": key}] - if (key := _client_api_key()) + if not spec.image_only and (key := _client_api_key()) else [] ), {"key": "RUNPOD_DEV_APP", "value": app.name}, @@ -173,7 +175,10 @@ def _endpoint_input( if spec.flashboot: payload["flashBootType"] = "FLASHBOOT" - if spec.image: + if spec.image_only: + # a prebuilt worker image runs its own handler, not the runtime + payload["template"]["dockerArgs"] = spec.docker_args or "" + elif spec.image: # custom images install and start the independently released runtime payload["template"]["env"].append( {"key": "RUNPOD_RUNTIME_KIND", "value": spec.kind.value} @@ -339,6 +344,7 @@ async def start(self) -> None: spec.name, events=self.events, api=self.api, + raw=spec.image_only, ) self._emit("session_started") @@ -428,6 +434,7 @@ async def refresh(self, apps: list[App]) -> None: handle.spec.name, events=self.events, api=self.api, + raw=handle.spec.image_only, ) spec = handle.spec diff --git a/runpod/apps/handles.py b/runpod/apps/handles.py index 8e507131..4d53eba1 100644 --- a/runpod/apps/handles.py +++ b/runpod/apps/handles.py @@ -40,6 +40,7 @@ def load_model(): ... # worker startup hook from .job import Job from .markers import INIT_ATTR, is_init, route_of from .spec import ResourceKind, ResourceSpec, RouteSpec +from .stubs import Queue if TYPE_CHECKING: from .app import App @@ -467,3 +468,31 @@ def __repr__(self) -> str: f"" ) + + +class WorkerImageHandle(Queue): + """handle for a prebuilt worker image deployed as a queue endpoint. + + the image runs its own handler, so calls send plain job input the + way the queue client does, and resolve through the owning app so the + same handle reaches a dev session or a deployed environment. + """ + + def __init__(self, app: "App", spec: ResourceSpec): + super().__init__(app=app.name, name=spec.name, env=app.env) + self._app = app + self.spec = spec + + def _clone(self) -> "WorkerImageHandle": + return WorkerImageHandle(self._app, self.spec) + + async def _resolve_target(self): + if in_discovery(): + raise DiscoveryInvocationError(self.spec.name) + return await self._app._resolve(self.spec) + + def __repr__(self) -> str: + return ( + f"" + ) diff --git a/runpod/apps/spec.py b/runpod/apps/spec.py index 97de2d7e..45714200 100644 --- a/runpod/apps/spec.py +++ b/runpod/apps/spec.py @@ -226,6 +226,8 @@ class ResourceSpec: container_disk_gb: int | None = None routes: list[RouteSpec] = field(default_factory=list) asgi_factory: str | None = None + image_only: bool = False + docker_args: str | None = None def __post_init__(self) -> None: self.validate() @@ -304,6 +306,7 @@ def validate(self) -> None: f"available on queue and api resources; tasks download " f"weights themselves" ) + self._validate_image_only() if self.schedule is not None and ( not isinstance(self.schedule, str) or not self.schedule ): @@ -325,6 +328,28 @@ def validate(self) -> None: ) seen.add(key) + def _validate_image_only(self) -> None: + """image-only resources run a prebuilt worker image's own handler.""" + if not self.image_only: + if self.docker_args is not None: + raise InvalidResourceError( + f"resource '{self.name}': args are only supported on " + f"worker image resources" + ) + return + if self.kind is not ResourceKind.QUEUE: + raise InvalidResourceError( + f"resource '{self.name}': worker image resources are queue endpoints" + ) + if not isinstance(self.image, str) or not self.image.strip(): + raise InvalidResourceError( + f"resource '{self.name}': worker image resources need an image" + ) + if self.docker_args is not None and not isinstance(self.docker_args, str): + raise InvalidResourceError( + f"resource '{self.name}': args must be a string start command" + ) + @property def is_cpu(self) -> bool: return self.cpu is not None @@ -410,4 +435,8 @@ def to_manifest(self, *, include_env: bool = True) -> dict[str, Any]: ] if self.asgi_factory: data["asgiFactory"] = self.asgi_factory + if self.image_only: + data["imageOnly"] = True + if self.docker_args: + data["dockerArgs"] = self.docker_args return data diff --git a/runpod/apps/stubs.py b/runpod/apps/stubs.py index aeab8516..2af55971 100644 --- a/runpod/apps/stubs.py +++ b/runpod/apps/stubs.py @@ -86,14 +86,20 @@ def with_options( new_options = build_job_options( webhook, execution_timeout, ttl, low_priority, s3_config ) - clone = Queue( + clone = self._clone() + clone._job_options = merge_job_options(self._job_options, new_options) + return clone + + def _clone(self) -> "Queue": + return Queue( app=self.app_name, name=self.resource_name, id=self.resource_id, env=self.env, ) - clone._job_options = merge_job_options(self._job_options, new_options) - return clone + + async def _resolve_target(self): + return self._target() def _payload(self, kwargs: dict) -> dict: payload = {"input": kwargs or {"__empty": True}} @@ -102,15 +108,16 @@ def _payload(self, kwargs: dict) -> dict: return payload async def _remote_async(self, **kwargs: Any) -> Any: - return await self._target().invoke(self._payload(kwargs)) + target = await self._resolve_target() + return await target.invoke(self._payload(kwargs)) async def _spawn_async(self, **kwargs: Any) -> Job: - target = self._target() + target = await self._resolve_target() data = await target.submit(self._payload(kwargs)) return Job(data, target) async def _stream_async(self, **kwargs: Any) -> AsyncIterator[Any]: - target = self._target() + target = await self._resolve_target() data = await target.submit(self._payload(kwargs)) stream = target.stream_job(data["id"]) try: @@ -122,7 +129,7 @@ async def _stream_async(self, **kwargs: Any) -> AsyncIterator[Any]: async def _job_async(self, job_id: str) -> Job: return Job( {"id": job_id, "status": "UNKNOWN"}, - self._target(), + await self._resolve_target(), ) def __repr__(self) -> str: diff --git a/runpod/apps/targets.py b/runpod/apps/targets.py index bed30ad6..1d453cbe 100644 --- a/runpod/apps/targets.py +++ b/runpod/apps/targets.py @@ -679,11 +679,15 @@ def __init__( resource_name: str = "", events: object | None = None, api=None, + raw: bool = False, ): self.endpoint_id = endpoint_id self.resource_name = resource_name self.events = events self.api = api + # raw endpoints run a prebuilt worker image's own handler, so + # job output is returned as the worker produced it + self.raw = raw self._client = QueueClient(endpoint_id, _headers) self._source_target: Any | None = None self._source_resource: str = "" @@ -753,6 +757,8 @@ def build_payload( def unwrap(self, data: dict[str, Any]) -> Any: output = unwrap_job_output(data) + if self.raw: + return output # the live handler is a generator handler, so job output is an # aggregated list: one plain response for normal functions, # __stream__-marked chunk envelopes for generator functions diff --git a/tests/test_apps/test_worker_image.py b/tests/test_apps/test_worker_image.py new file mode 100644 index 00000000..385f789d --- /dev/null +++ b/tests/test_apps/test_worker_image.py @@ -0,0 +1,233 @@ +"""worker image resources: an existing worker image runs its own handler. + +app.worker_image deploys a prebuilt worker image as a queue endpoint +without a decorated function. the image's own start command (or the one +given in args) runs; jobs carry plain input the image's handler reads. +""" + +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 _deployed_endpoint_input, build_manifest +from runpod.apps.dev import DevSession, _endpoint_input +from runpod.apps.errors import InvalidResourceError +from runpod.apps.spec import ResourceKind, ResourceSpec +from runpod.apps.targets import LiveTarget + +IMAGE = "runpod/mock-worker:latest" +START_COMMAND = "python3 -u /handler.py --generator" + + +@pytest.fixture(autouse=True) +def clean_registry(): + _clear_registry() + yield + _clear_registry() + + +def _env(payload): + return {e["key"]: e["value"] for e in payload["template"]["env"]} + + +class FakeTarget: + """records submitted payloads and answers like a completed queue job.""" + + def __init__(self, output=None): + self.payloads = [] + self.output = output if output is not None else {"ok": True} + + async def invoke(self, payload, *, timeout=None): + self.payloads.append(payload) + return self.output + + async def submit(self, payload): + self.payloads.append(payload) + return {"id": "job-1", "status": "IN_QUEUE"} + + +class TestRegistration: + def test_registers_queue_resource_for_the_image(self): + app = App("e2e") + + worker = app.worker_image(name="mock", image=IMAGE, gpu="ADA_24") + + assert app.resources["mock"] is worker + assert worker.spec.kind is ResourceKind.QUEUE + assert worker.spec.image == IMAGE + assert worker.spec.image_only is True + assert worker.spec.docker_args is None + + def test_keeps_start_command(self): + app = App("e2e") + + worker = app.worker_image(name="mock", image=IMAGE, args=START_COMMAND) + + assert worker.spec.docker_args == START_COMMAND + + def test_passes_scaling_settings_through(self): + app = App("e2e") + + worker = app.worker_image( + name="mock", image=IMAGE, workers=(0, 3), idle_timeout=5 + ) + + assert worker.spec.workers == (0, 3) + assert worker.spec.idle_timeout == 5 + + @pytest.mark.parametrize("image", [None, "", " "]) + def test_requires_an_image(self, image): + app = App("e2e") + + with pytest.raises(InvalidResourceError, match="image"): + app.worker_image(name="mock", image=image) + + def test_start_command_needs_an_image_only_resource(self): + with pytest.raises(InvalidResourceError, match="args"): + ResourceSpec( + kind=ResourceKind.QUEUE, name="mock", image=IMAGE, docker_args="x" + ) + + def test_image_only_resources_are_queues(self): + with pytest.raises(InvalidResourceError, match="queue"): + ResourceSpec( + kind=ResourceKind.API, name="mock", image=IMAGE, image_only=True + ) + + +class TestDeployPayload: + def test_runs_the_start_command_instead_of_the_runtime(self): + app = App("e2e") + worker = app.worker_image(name="mock", image=IMAGE, args=START_COMMAND) + + payload = _deployed_endpoint_input(app, worker.spec, "env-1", "b-1", "3.12") + + assert payload["template"]["imageName"] == IMAGE + assert payload["template"]["dockerArgs"] == START_COMMAND + assert "RUNPOD_RUNTIME_KIND" not in _env(payload) + + def test_without_args_keeps_the_image_command(self): + app = App("e2e") + worker = app.worker_image(name="mock", image=IMAGE) + + payload = _deployed_endpoint_input(app, worker.spec, "env-1", "b-1", "3.12") + + assert payload["template"]["dockerArgs"] == "" + + def test_carries_user_env(self): + app = App("e2e") + worker = app.worker_image(name="mock", image=IMAGE, env={"MODE": "fast"}) + + payload = _deployed_endpoint_input(app, worker.spec, "env-1", "b-1", "3.12") + + assert _env(payload)["MODE"] == "fast" + + def test_manifest_marks_the_resource_image_only(self, tmp_path: Path): + app = App("e2e") + app.worker_image(name="mock", image=IMAGE, args=START_COMMAND) + + manifest = build_manifest(app, tmp_path) + + (entry,) = manifest["resources"] + assert entry["imageOnly"] is True + assert entry["dockerArgs"] == START_COMMAND + assert "module" not in entry + + +class TestDevPayload: + def test_runs_the_start_command_instead_of_the_runtime(self): + app = App("e2e") + worker = app.worker_image(name="mock", image=IMAGE, args=START_COMMAND) + + payload = _endpoint_input(app, worker.spec) + + assert payload["template"]["imageName"] == IMAGE + assert payload["template"]["dockerArgs"] == START_COMMAND + assert "RUNPOD_RUNTIME_KIND" not in _env(payload) + + def test_does_not_hand_the_account_key_to_the_image(self, monkeypatch): + monkeypatch.setenv("RUNPOD_API_KEY", "secret-key") + app = App("e2e") + worker = app.worker_image(name="mock", image=IMAGE) + + payload = _endpoint_input(app, worker.spec) + + assert "RUNPOD_API_KEY" not in _env(payload) + + async def test_session_registers_a_raw_target(self): + app = App("e2e") + app.worker_image(name="mock", image=IMAGE) + api = AsyncMock() + api.list_my_endpoints.return_value = [] + api.save_endpoint.return_value = {"id": "ep-new"} + + await DevSession([app], api=api).start() + + target = app._dev_targets["mock"] + assert target.endpoint_id == "ep-new" + assert target.raw is True + + +class TestRawLiveTarget: + def test_returns_worker_output_unchanged(self): + target = LiveTarget("ep-1", "mock", raw=True) + output = {"success": True, "value": 3} + + assert target.unwrap({"status": "COMPLETED", "output": output}) == output + + +class TestInvocation: + async def test_remote_sends_plain_input(self, monkeypatch): + app = App("e2e") + worker = app.worker_image(name="mock", image=IMAGE) + target = FakeTarget(output={"echo": "hi"}) + monkeypatch.setattr(app, "_resolve", AsyncMock(return_value=target)) + + result = await worker.remote.aio(prompt="hi") + + assert result == {"echo": "hi"} + assert target.payloads == [{"input": {"prompt": "hi"}}] + + async def test_spawn_returns_a_job(self, monkeypatch): + app = App("e2e") + worker = app.worker_image(name="mock", image=IMAGE) + target = FakeTarget() + monkeypatch.setattr(app, "_resolve", AsyncMock(return_value=target)) + + job = await worker.spawn.aio(prompt="hi") + + assert job.id == "job-1" + assert target.payloads == [{"input": {"prompt": "hi"}}] + + async def test_options_ride_with_the_job(self, monkeypatch): + app = App("e2e") + worker = app.worker_image(name="mock", image=IMAGE) + target = FakeTarget() + monkeypatch.setattr(app, "_resolve", AsyncMock(return_value=target)) + + await worker.with_options(execution_timeout=30).remote.aio(prompt="hi") + + assert target.payloads == [ + {"input": {"prompt": "hi"}, "policy": {"executionTimeout": 30}} + ] + + async def test_resolves_through_the_app(self, monkeypatch): + app = App("e2e") + worker = app.worker_image(name="mock", image=IMAGE) + resolve = AsyncMock(return_value=FakeTarget()) + monkeypatch.setattr(app, "_resolve", resolve) + + await worker.remote.aio(prompt="hi") + + resolve.assert_awaited_once_with(worker.spec) + + def test_remote_blocks_for_the_result_outside_async(self, monkeypatch): + app = App("e2e") + worker = app.worker_image(name="mock", image=IMAGE) + target = FakeTarget(output="hello") + monkeypatch.setattr(app, "_resolve", AsyncMock(return_value=target)) + + assert worker.remote(mock_return="hello") == "hello"