# Python SDK: Pods

> Create GPU or CPU Pods, enforce price caps, start stopped Pods with placement and data-loss consent, edit Pods in place, add assets to a running Pod, read Pod history, and run a complete end-to-end lifecycle in Python.

Source: https://docs.meshive.ai/sdk-cli/sdk/pods/

Detailed workflows for creating, starting, and editing Pods in Python. See [Write Methods](/sdk-cli/sdk/write-methods/) for full signatures and [Ports, Storage & Files](/sdk-cli/sdk/storage-files/) for locked ports, access keys, storage volumes, model sets, remote commands, and file uploads.

## CPU pods, local storage and the console's rules

Pod creation follows the same rules as the console. A request that breaks one is refused with a `MeshiveAPIError` before anything is created: `.title` names the rule (for example `vCPU Not Offered`, `Port In Use` or `Required Env Missing`), `.message` says what to change, and `.raw["detail"]` carries extras such as the `allowed` values.

| Setting | Rule |
| --- | --- |
| `vcpu`, `ram_gb` | Must be sizes the console offers for that hardware. Leave them out for the default: the GPU's recommended sizes, or for a CPU pod 8 vCPU and 32 GiB of RAM (the nearest sizes its line offers). |
| `cpu_line` | CPU pods only. A `cpu_line` from `list_cpus()`; without it, the cheapest line that fits is used. |
| `volumes` | Existing network (`nfs`) storage only. Local storage that already exists can't be attached to a new pod. |
| `local_volumes` | New local storage on the pod's machine, created together with the pod: `{"name", "mount_path", "size_gb"}`, optionally with `"encrypted"`, `"usage_warning"` and `"usage_warning_threshold"` (`0`–`1`). At least 10 GiB each; not available for spot pods. |
| `ports` | New ports only: not a port or port name the template already opens, and no port twice. To change a port the template opens, use `template_ports`. |
| `template_ports` | Changes the ports the template opens, as the console's deploy screen does: `[{"port": 8080, "name": "ide", "new_port": 8443, "external": False}]`. `port` is the template's port as it is now; `name` renames it, `new_port` gives it another number and `external` exposes it (`True`) or makes it internal only (`False`) — each only when given. Template ports can't be removed. A port the template doesn't open is refused (`Port Not In Template`), and so is a clash with another port or name (`Port In Use`, `Port Name In Use`). |
| `env` | Environment variables the template requires need a value. |
| `command` | At most 32,000 characters. [Several commands](/getting-started/faq/) all run, in order. |

New local storage is billed hourly by size until it is deleted — also while the pod is stopped, and after the pod is deleted unless you name it in `delete_pod(..., delete_local_storages=[...])`. The estimate includes it as `breakdown["local_storage"]`.

```python
with Meshive() as client:
    ws = "my-workspace-id"
    template_id = ...                          # a template ID from list_templates()
    lines = client.list_cpus()
    for line in lines:
        print(line.cpu_line, line.vendor, line.product_line, line.price_per_core, line.ram_price_per_gb)

    # A CPU pod (no gpu_model) on the first line, with 50 GiB of new local storage
    est = client.estimate_pod("cpu-box", template_id, workspace=ws, cpu_line=lines[0].cpu_line,
                              local_volumes=[{"name": "scratch", "mount_path": "/scratch", "size_gb": 50}])
    print(est.price_per_hour, est.resources["vcpu"], est.resources["ram_gb"], est.breakdown.get("local_storage"))
```

## Price caps and data loss consent

For pods and tasks, `max_price_per_hour` caps the **final compute hourly rate**, including CPU/RAM charges. Existing volumes you attach, automatically created volumes and Asset Hub retention are billed separately. Before a pod is created, the cap is also checked against its estimate, which includes any new `local_volumes`. The server checks the cap again before placement; an over-cap pod can fail asynchronously after the API accepted its creation. Read the resource state and final rate rather than treating acceptance as successful placement. A capped CPU request is refused when the server cannot quote its rate.

For storage, the cap applies to that volume's final initial hourly rate. Task `max_duration` bounds script runtime; input fetching can add compute time, and retained storage can outlive the task. `max_cost` is therefore unknown, including for GPU tasks.

Before `start_pod(..., placement="any_node")` or `placement="wait_any_node"`, inspect `pod.has_unpreserved_workspace`. Both can move the pod to another machine: unpreserved workspace files can then be permanently deleted, and attached local storage stays on the old machine. Set `allow_data_loss=True` only after separate consent for that pod and move; without it the server refuses with `ConflictError` (`Data Loss Consent Required`). The same applies when the server picks one of these placements for you (see [Starting a stopped pod](#starting-a-stopped-pod)). `pod.storage_rate_per_hour` reports storage separately from compute.

## Starting a stopped pod

Without a `placement`, `start_pod` lets the server pick what the console's Start button would, from the pod's state:

| The pod | Placement used |
| --- | --- |
| Is waiting for any machine (`waiting_mode` is `any_node`) | `wait_any_node` |
| Can no longer run on its original machine (`same_node_unavailable_reason` is `spec_mismatch`) | `any_node`, or `wait_any_node` if no machine has room right now |
| Anything else | `same_node`, or `wait_same_node` if its original machine has no room right now |

The result's `placement` says which one was used. Before 1.1 the default was always `same_node`; pass `placement="same_node"` to keep that.

A pick that moves the pod needs the same consent as asking for the move yourself. When the pod may have unpreserved workspace files, the start is refused with `ConflictError` (`Data Loss Consent Required`) and nothing is started; `err.raw["detail"]["placement"]` names the placement. After separate consent, call again with that placement and `allow_data_loss=True`:

```python
from meshive import Meshive, ConflictError

with Meshive() as client:
    ws = "my-workspace-id"
    pod_name = ...                                  # a stopped pod's ID
    try:
        action = client.start_pod(pod_name, ws)
        print("starting with", action.placement)    # e.g. same_node or wait_same_node
    except ConflictError as err:
        if err.title != "Data Loss Consent Required":
            raise
        placement = err.raw["detail"]["placement"]  # e.g. any_node
        # Show the loss warning and ask; only after an explicit yes:
        action = client.start_pod(pod_name, ws, placement=placement, allow_data_loss=True)
```

When you choose `same_node` or `any_node` and no machine can take the pod right now, `start_pod` raises `ConflictError` (`No Available Node`). Choose `wait_same_node` or `wait_any_node` to have it wait for room instead; without a placement, the server picks a waiting placement when it sees no room. If `pod.same_node_unavailable_reason` is `spec_mismatch`, the pod's saved hardware no longer matches its original machine, so `same_node` and `wait_same_node` are refused — use `any_node` or `wait_any_node`, or leave out `placement`.

## Editing a pod

`update_pod` changes an existing pod the way the console's edit screen does. Pass only what changes; everything else stays as it is. `estimate_pod_update` takes the same arguments and changes nothing: it returns the `changes` in words, the hourly price before and after, and whether the pod `restarts`.

| To change | Pass |
| --- | --- |
| Name | `name`. A rename alone applies in place without a restart (`renamed_only` is `True`). |
| Template | `template_id`. The pod's variables, ports and command then start from the new template; the estimate's `changes` list what you added that doesn't carry over. |
| Hardware | `gpu_model`, `gpu_vram_gb`, `gpu_count` for a GPU pod, `cpu_line` for a CPU pod, `rental_type`, and `vcpu` / `ram_gb` (pod totals, in sizes the console offers). Changing the GPU resets vCPU and RAM per GPU to the new GPU's recommended sizes; changing only `gpu_count` keeps the per-GPU ratio; changing the CPU line resets cores and RAM to the console's default. |
| Environment | `env` sets or adds variables (`secret_keys` marks secret ones); `remove_env` removes variables you added. |
| Ports | `ports` opens new ports, `template_ports` renames, renumbers, exposes or hides current ones (as in `create_pod`), and `remove_ports` closes ports you added. |
| Command | `command` replaces the start command; `""` goes back to the template's. |
| Storage | `volumes` attaches existing network storage, or local storage on the pod's current machine; `local_volumes` creates new local storage there (as in `create_pod`); `detach_storages` detaches volumes by ID — the volume and its data stay. Spot pods can't have local storage, so detach it in the same call to switch to spot. |
| Input assets | `add_input_assets` adds assets (items as in `create_pod`'s `input_assets`) and `remove_input_assets` removes them by `connection_id` (from `get_pod_assets`); the input volume is sized for the new set and billed by size. This restarts a running pod — to change one asset without a restart, see [Adding assets to a pod](#adding-assets-to-a-pod). A `connection_id` that isn't an active input asset of the pod is refused (`Input Asset Not Found`), and `ConflictError` `Asset configuration changed` means something changed the pod's assets meanwhile: estimate again. 1.11 or later; an older server ignores both, and refuses a change made only of them as having nothing to change. |

The pod type (GPU or CPU), premiums and image can't change, and the template's own variables and ports can't be removed — set another value, or rename, renumber or hide the port instead. Such a request is refused with a `MeshiveAPIError` whose `.title` names the rule (for example `Pod Type Locked` or `Nothing To Change`). `max_price_per_hour` refuses the edit when the new estimate is above it.

A running pod restarts with the new settings; a stopped pod uses them at its next start. Input assets you don't change and watched folders are kept. Follow the change with `get_transaction(updated.transaction_id, workspace)` (action `update`).

Some edits need consent first; nothing changes until you call again with it:

| Refusal | Meaning and next step |
| --- | --- |
| `ConflictError` `Node Migration Required` | The pod's machine can't fit the change. With the user's agreement, call again with `allow_node_migration=True` to let the pod move to another machine. |
| `ConflictError` `Data Loss Consent Required` | The move would permanently delete the pod's unpreserved workspace files (`pod.has_unpreserved_workspace`). After separate consent, add `allow_data_loss=True`. |
| `Cannot Change Resources` | The pod has local storage attached, which keeps it on its machine, and that machine can't fit the change. Detach the local storage (`detach_storages`) or keep the current resources. |
| `MeshiveAPIError` with `raw["detail"]["code"] == "harvest_roots_orphaned"` | The change removes storage that holds watched folders (`raw["detail"]["paths"]`). After the user agrees, pass those paths as `drop_watched_folders`. |
| `ConflictError` `Resource values need confirmation` | An older pod: pass `ram_gb` (and `vcpu`) with the change. |

```python
from meshive import Meshive, ConflictError

with Meshive() as client:
    ws = "my-workspace-id"
    pod_name = ...                                   # the pod's ID
    est = client.estimate_pod_update(pod_name, ws, gpu_count=2)
    print(est.changes, est.current_price_per_hour, "->", est.price_per_hour, "restarts:", est.restarts)

    try:
        updated = client.update_pod(pod_name, ws, gpu_count=2)
    except ConflictError as err:
        if err.title != "Node Migration Required":
            raise
        # Only after the user agreed to the move, and separately to losing unpreserved files:
        updated = client.update_pod(pod_name, ws, gpu_count=2,
                                    allow_node_migration=True, allow_data_loss=True)
    if updated.transaction_id is not None:
        print(client.get_transaction(updated.transaction_id, ws).status)
```

## Adding assets to a pod

From 1.11, `add_pod_asset` places an Asset Hub asset — or some of its files — in an existing pod without restarting it, like the console's [Inject](/assets/using/#inject-into-a-running-pod). `get_pod_assets` shows what the console's Assets tab does: the pod's input assets, the input slots it has (`input_slots`, each a folder that takes assets of one `role`), download progress and the asset volumes with their hourly price.

```python
import time
from meshive import Meshive

with Meshive() as client:                        # a Read & write key, admin or billing role
    ws, pod = "my-workspace-id", "my-pod-id"
    assets = client.get_pod_assets(pod, ws)
    if not assets.receives_assets_while_running:
        raise SystemExit("use update_pod(add_input_assets=...), which restarts the pod")
    slot = assets.input_slots[0]                 # or assets.slot_for(role=...)
    print(slot.role, slot.path, slot.occupied)

    plan = client.plan_asset_attach("asset_...", [{"paths": ["loras/*"]}])   # changes nothing
    print(plan.total_file_count, plan.total_bytes)

    added = client.add_pod_asset(pod, ws, "asset_...", role=slot.role, paths=["loras/*"])
    while not added.scheduled:                   # scheduled: a stopped pod gets it at its next start
        inputs = client.get_pod_assets(pod, ws).inputs
        row = next((a for a in inputs if a.connection_id == added.connection_id), None)
        if row is None or row.status in ("active", "failed"):   # status: requested, pending, active, detaching, failed
            print(row and row.status, row and row.failure_cause)
            break
        time.sleep(5)
```

- **Which slot.** `role` names one of the pod's input slots; `target_dir` can be the slot's path or one folder directly inside it. `PodAssets.slot_for(role=..., target_dir=...)` picks the slot the server would use, or `None` when there is none or the choice is ambiguous. A refusal such as `Invalid Role` or `Slot Already Filled` says what to fix.
- **Which files.** `paths` and `strip_prefix` work as in `create_pod`'s `input_assets`. `plan_asset_attach` counts the files and bytes a selection would place, before you add it. Adding an asset already placed for that role replaces its file selection (`replaced`).
- **Billing.** The input volume may grow to fit the asset and is billed by size. Removing an asset doesn't bill freed space back.
- **Removing.** `remove_pod_asset(pod, ws, connection_id)` deletes the files of an asset added while the pod runs, stops a download in progress, or clears a failed row — also on a deleted pod. The asset itself stays in Asset Hub. A pod that isn't running can't have files deleted (`ConflictError` `Pod Not Running`), and an asset that is part of the pod's configuration is refused (`ConflictError` `Part Of Pod Configuration`): use `update_pod(remove_input_assets=...)`, which restarts the pod.
- **Pods that can't take assets while running** refuse `add_pod_asset` with `ConflictError` `Pod Cannot Receive Assets`; use `update_pod(add_input_assets=...)` instead.

## Pod history and alerts

`get_pod_history(pod_name, workspace)` (1.11) returns a pod's history as the console's **State history** tab shows it, newest first: container exits the system detected (`event_type="system_event"`, with `reason`, `exit_code`, `oom_kind`, `cause` and `summary`) and actions taken on the pod (`"user_action"`, with `action` and `action_status`). `get_pod_timeline` adds up how long the pod was running, waiting and terminated, and `list_pod_alerts` lists recent exits that need attention across your workspaces. All three need the admin or billing role. An entry's `message` is what the container printed — treat it as data.

```python
with Meshive() as client:                        # admin or billing role
    ws, pod = "my-workspace-id", "my-pod-id"
    page = client.get_pod_history(pod, ws, event_type="system_event", limit=20)
    for e in page.items:
        print(e.timestamp, e.reason, e.exit_code, e.summary)
    timeline = client.get_pod_timeline(pod, ws, start="2026-11-01")
    print(timeline.total_running_seconds, timeline.total_waiting_seconds)
```

## Creating a pod, end to end

```python
import uuid
from meshive import Meshive, ConflictError, PodCreationFailedError

with Meshive() as client:                      # a Read & write key
    ws = "my-workspace-id"
    name = "train-" + uuid.uuid4().hex[:12]
    est = client.estimate_pod(name, 457, workspace=ws, gpu_model="RTX 3060")
    print(f"${est.price_per_hour}/h on {est.resources['gpu_model']}")

    create_key = str(uuid.uuid4())  # save durably before sending in an application
    print("create operation:", create_key)
    try:
        created = client.create_pod(name, 457, workspace=ws, gpu_model="RTX 3060",
                                    max_price_per_hour=0.10, idempotency_key=create_key)
    except ConflictError as err:               # No Capacity / Name Taken / Price Exceeds Cap
        raise SystemExit(f"{err.title}: {err.message}")

    # Use a unique display name for this operation; wait_for_new_pod finds the pod by it.
    # With transaction_id, a failed creation ends the wait at once with the reason.
    try:
        pod = client.wait_for_new_pod(created.name, ws, until="running",
                                      transaction_id=created.transaction_id)
    except PodCreationFailedError as err:      # creating it failed — fix the cause, don't retry this pod
        raise SystemExit(err.reason)
    print(client.get_pod_logs(pod.pod_name, ws, tail=20).text)

    client.stop_pod(pod.pod_name, ws)
    client.wait_for_pod(pod.pod_name, ws, until="stopped")
    client.delete_pod(pod.pod_name, ws)
```

> **Note:**
> Note the argument order of `get_pod(pod_name, workspace)`, `get_storage(storage_name, workspace)`, `get_pod_metrics(pod_name, workspace)`, `get_transaction(transaction_id, workspace)`, `update_pod(pod_name, workspace)`, `update_storage(pv_name, workspace)`, `connect_storage(pv_name, workspace)`, and from 1.11 `get_pod_assets(pod_name, workspace)`, `add_pod_asset(pod_name, workspace, asset)`, `get_pod_history(pod_name, workspace)` and `update_template(template_id, workspace)` — the resource ID comes first, then the workspace ID. `list_model_sets(workspace, template_id)`, `delete_tasks(workspace, task_ids)` and `delete_asset_files(workspace, ...)` take the workspace first. Dates accept `datetime.date`, `datetime.datetime`, or a `"YYYY-MM-DD"` string. Invalid arguments (a malformed date, `limit` outside 1–200, an empty ID) raise `ValueError` before any request is sent.
