Metadata-Version: 2.5
Name: 3lc-compute-plugin-azure
Version: 0.1.1
Summary: Microsoft Azure infrastructure plugin for the 3LC compute service: disposable GPU virtual machines and Blob containers as storage.
License: Apache-2.0
Requires-Python: >=3.10
Requires-Dist: 3lc-compute-plugin-sdk<0.6.0,>=0.5.0
Requires-Dist: 3lc<4.0.0,>=3.5.0.dev149866
Provides-Extra: azure
Requires-Dist: azure-identity>=1.17; extra == 'azure'
Requires-Dist: azure-mgmt-compute>=30; extra == 'azure'
Requires-Dist: azure-mgmt-network>=25; extra == 'azure'
Requires-Dist: azure-mgmt-resource-subscriptions>=1.0.0; extra == 'azure'
Requires-Dist: azure-mgmt-resource>=23; extra == 'azure'
Requires-Dist: azure-mgmt-storage>=21; extra == 'azure'
Requires-Dist: azure-storage-blob>=12.19; extra == 'azure'
Requires-Dist: requests>=2.31; extra == 'azure'
Description-Content-Type: text/markdown

# 3lc-compute-plugin-azure

Microsoft Azure infrastructure plugin for the 3LC compute service (`kind = "infrastructure"`). It creates
disposable **GPU virtual machines** in your Azure subscription for the Hub and tears them down, and it
offers **Azure Blob containers** as storage. It answers the plugin SDK's typed `InfrastructurePlugin`
contract, so the Hub drives it as it drives every other provider.

- **GPU nodes** — Azure VMs (`Standard_NC…`, `ND…`, `NV…` sizes) running the 3LC node agent; the host
  dispatches training jobs to them and deletes them when idle. The image is the Data Science VM (Ubuntu
  22.04, NVIDIA drivers and CUDA preinstalled), `image` in the settings overrides it (a URN or an image id).
  Each node gets a static public IP, a NIC and an OS disk that are deleted with the VM, a system-assigned
  managed identity, no password and a throwaway SSH key (port 22 is never opened). A managed network
  security group (`3lc-gpu-nodes`) opens the agent port 8800 and the app ports the host asks for (8888) to this
  controller's current egress IP only; SDK workers listen on the node's loopback and are reached through the
  agent's proxy, so no worker port is opened. There is one rule per controller (replaced on every launch, so a
  moved controller never locks itself out and two controllers sharing a group leave each other alone).
  Azure's default rules deny everything else inbound. Nodes attach to a managed VNet (`3lc-gpu-nodes`,
  10.42.0.0/16) unless `subnet_id` names one of yours.
- **Storage** — one storage account (`storage_account`); its containers are the plugin's storage, as
  `abfs://<container>/<path>` URLs, which is the form `tlc` reads (it takes the account from
  `AZURE_STORAGE_ACCOUNT_NAME`). Nodes land in the storage account's region.

**Credentials.** The plugin keeps no credential in its settings and acts in Azure only through the
**Connection** a call names (the host sends its binding; the SDK resolves it before the plugin runs).
`AMBIENT` is the one kind honoured today: this deployment's own identity through `DefaultAzureCredential` —
`az login`, a managed identity or the `AZURE_*` environment on the controller. The plugin never falls back to
that identity for a call that names no Connection: such a call is answered with "No Connection named — Azure
acts only through a Connection, and this deployment's own identity (AMBIENT) is the one kind honoured today"
— capabilities with `ready: false` and that sentence as `not_ready_reason`, every management route with 409,
and the catalogs and preflight in their answer, as they carry every failure. Cached Azure clients are keyed
by the Connection's kind and id, so one Connection never reuses another's. The one other path is the legacy
owner-credentials facet: a request that carries a service principal
(`credentials: {tenant_id, client_id, client_secret, subscription_id}`) acts in that subscription with it,
and nothing it carries is stored. `subscription_id` names the plugin's subscription
(`AZURE_SUBSCRIPTION_ID` in the environment when empty); `resource_group` (default `3lc-compute`) is created
in `location` when missing.

A settings file saved by an earlier version that kept credentials (`tlc_api_key`, `tenant_id`, `client_id`,
`client_secret`, `sign_in_client_id`, `storage_account_key`, `node_storage_credential`, `node_sas_hours`)
still loads: those keys are ignored. Their old values — plaintext secrets among them — stay in
`~/.3lc-plugin-configs/azure/default.json` until the settings are next saved (a save writes only the current
fields) or you remove them by hand. The browser sign-in is gone too: `signin.json` next to the settings and
azure-identity's `3lc-azure` token cache (kept by msal-extensions: under `~/.IdentityService/` as a plain file
on a headless Linux controller, in the OS keyring elsewhere) are no longer read; delete them to forget that
sign-in.

**Upgrading.** GPU nodes created by an earlier version may not be deletable from the Hub without a
Connection: delete your Azure nodes before upgrading, or remove the leftovers (VM, NIC, public IP, OS disk,
all named `3lc-<node id>…`) in the Azure portal.

**What the plugin's identity needs.** To run nodes: `Microsoft.Compute/*`, `Microsoft.Network/*` on the
resource group (Contributor on the group is the simple answer), `Microsoft.Compute/skus/read` and
`Microsoft.Compute/locations/usages/read` for the size table. For storage: Storage Account Contributor on the
account (or `listKeys`), or Storage Blob Data Contributor plus Storage Blob Delegator when the plugin signs
links with a user delegation key instead of the account key. The plugin never assigns roles itself.

## Trust model

- The node's environment carries no credential: the storage account name, `extra_env` (not for secrets) and
  the agent's own control values (`TLC_NODE_*`) from the host. It is the same trust class as the VM itself:
  anything running on the VM can read its own environment, and Azure's Instance Metadata Service hands custom
  data back to any process on the VM. The agent gives its workers everything but its own control secrets.
- **A node has no 3LC identity and no Blob credential.** It acts in Azure only as its own system-assigned
  managed identity, which is created with the VM and has no role until one is granted to it; the plugin grants
  none. Until node credentials arrive with the Config Service, a node cannot sign in to 3LC, and it reads and
  writes Blob storage only if its identity has been given Storage Blob Data Contributor on the account.
- **Self-termination.** When idle, the agent runs `/opt/3lc-agent/terminate.py`: IMDS names the VM, and
  `DefaultAzureCredential` — the VM's own system-assigned managed identity — asks Compute to delete it
  (`force_deletion`; disk, NIC and IP go with it). That needs **Virtual Machine Contributor** on the resource
  group for the VM's identity. Without it the agent exits and the VM keeps billing, which is why the
  controller's idle teardown and heartbeat handling are the other two layers.
- Browser uploads and downloads use per-blob SAS links (one hour; upload links allow create + write only,
  download links read only). Server-side copies pass the source as a URL with a one-hour read SAS.
- Error text shown to people has subscription, tenant and object ids, resource scopes, principals, request
  ids and endpoints removed; the code and the action stay. The plugin's `describe_error` does this for every
  failure the SDK answers, a transfer or bundle job's included. Request values (container and account names,
  locations, GUIDs, VM sizes and names, resource ids, environment keys and values) are checked before they
  reach Azure and answer 400 with what to change.

## Routes

`AzurePlugin` is an `InfrastructurePlugin` with the SDK's **storage**, **catalog** and legacy
**owner-credentials** facets (`capabilities.facets: ["storage", "catalog", "legacy-owner-credentials"]`). The
SDK mounts the `/infra/*` routes and `/settings` from its typed methods and its settings dataclass; the plugin
adds its own region route. A call that names no Connection is answered 409 with the sentence under
*Credentials* by every route below except these: `GET /infra/capabilities` and `GET /ui` (200; capabilities
report `ready: false` with `not_ready_reason`), `/settings`, the catalogs and preflight (200 with the sentence
in their answer), `/infra/datacenters`, and the legacy owner-credentials calls
(`POST /infra/nodes/{id}/terminate`, `POST /infra/storage/discover`, and `POST /infra/storage` with
`credentials`), which act with the service principal they carry. Everything is mounted under `/api/plugins/azure/`; the host forwards
storage routes as `/api/infra/storage/azure/...`.

| Route | What it does |
| --- | --- |
| `GET /infra/capabilities` | `provider: "azure"`, `ready` (never true for a call that names no Connection; `not_ready_reason` then says so), `node_types` (and `gpu_types`) = the configured VM sizes, `flavors: ["gpu"]`, `pricing: ["on_demand", "spot"]`, `region`, `credential_keys`, `missing_fields` (each with `help` and `href`), `facets`, and `storage` (`kind: "bucket"`, `label: "Azure Blob container"`, `creatable/upload/browse/download/bundle/delete/transfer/rename`) |
| `POST /infra/nodes` | Create a VM: `{node_id, node_type (or gpu_type; a VM size), token, env, ports, idle_ttl_s, pricing?, owner?, project_storage?}` → `{provider_id, agent_url, pricing}`; `agent_url` is `http://<public ip>:8800`; `ports` are the browser-facing app ports opened next to the agent port. A request whose `credentials` carry any value is refused: nodes run in the plugin's own subscription |
| `GET /infra/nodes/{id}` | `{state, detail}` with state `pending`, `running`, `exited`, `gone` (from the instance view); `?diagnostics=true` answers the same |
| `DELETE /infra/nodes/{id}` | Delete the VM (not found counts as done) → `{state: "terminated"}`; leftovers are removed once the VM is gone |
| `POST /infra/nodes/{id}/terminate` | Delete a VM in another subscription with the `credentials` in the body (a service principal and its `subscription_id`) |
| `GET /infra/gpu-catalog` | GPU VM sizes in the location with vCPUs, RAM, GPU model and VRAM, family quota, restrictions, pay-as-you-go and spot prices (`?region=` overrides); a failure is an empty list with `error` |
| `GET /infra/cpu-catalog` | CPU sizes with live prices (`?region=` overrides); a failure is an empty list with `error` |
| `GET /infra/datacenters` | Always empty: Azure places a VM in the location |
| `GET /infra/preflight` | Credential, offering and family quota checks before a VM is requested (`?node_type=` or `?gpu_type=`) |
| `GET /infra/storage` | The account's containers with region, by name; `account`; `regions` = the account's region (every region when no account exists yet) |
| `POST /infra/storage` | Create a container `{name, region?}` in the plugin's storage account; the first container creates the account (StorageV2, LRS, HTTPS only, no public access) and sets the plugin's account and location. With `credentials` (a service principal and its `subscription_id`; an all-empty object counts as none) the container is created in the requester's subscription, in a storage account this plugin tagged `3lc=storage` in the resource group there, else a new one; the answer's `account` and `https_url` address it, and nothing is saved. The request's `owner` goes into the container's metadata when it can be written as ASCII |
| `DELETE /infra/storage/{container}` | Delete an empty container; one with blobs is a 409 |
| `POST /infra/storage/discover` | The containers in the requester's subscription, with the `credentials` in the request (a service principal and its `subscription_id`) |
| `GET /infra/storage/list?url=abfs://c/prefix` | One level: sub-folders and blobs (`truncated` past 500) |
| `POST /infra/storage/presign` | `mode: "upload"` (default): PUT URLs for `files: [{path, size, content_type}]` with the `x-ms-blob-type: BlockBlob` header the browser must send; `mode: "download"`: GET URLs saved as attachments |
| `POST /infra/storage/delete` | Delete files and folders under a prefix, counted first (`dry_run`); the open folder and `..` paths are refused |
| `POST /infra/storage/transfer`, `GET/DELETE …/transfer/{id}` | Copy, move or rename inside the account as a job (server-side Copy Blob; SDK `TransferRegistry`) |
| `POST /infra/storage/bundle`, `GET/DELETE …/bundle/{id}` | Zip a folder in the background to `.3lc/downloads/` with a 24-hour link (SDK `BundleRegistry`) |
| `GET/POST /settings` | The plugin page's settings (no secrets; `extra_env` as `extra_env_keys`) |
| `GET /infra/regions` | Private: the subscription's regions `[{id, name}]` and the current one |

**Settings.** One `AzureSettings` dataclass behind the SDK's `PluginSettings`, with no secret field. The
location, resource group, image, pricing model and spot eviction policy are checked before they are saved and
an empty value keeps the current one; the subscription id, the storage account, subnet and network security
group ids are checked and may be cleared. `extra_env` keys must be environment variable names, and its values
are not for secrets (they ride the VM's custom data). Capabilities prompt for what is missing in the
dataclass's field order: the subscription id, the storage account. A node's idle teardown is the host's `idle_ttl_s`; the
plugin keeps no setting for it. A settings file that exists but does not parse answers 409 instead of being
read as defaults.

## Pricing

A GPU node is pay-as-you-go or spot: `pricing: "on_demand" | "spot"` on `POST /infra/nodes`, the `pricing`
setting when the request names none, and `capabilities.pricing` tells the host it may offer spot. A spot VM is
created with `priority: Spot`, the configured eviction policy (`Delete` by default — nothing keeps billing;
`Deallocate` keeps the disk, billed) and `max_price: -1`, which means the current spot price with the
pay-as-you-go price as the only cap. Azure may evict a spot VM with thirty seconds' notice; the node dies, the
job running on it fails, and it has to be started again. A launch that finds no capacity (`AllocationFailed`,
`SkuNotAvailable`, `OverconstrainedAllocationRequest`) fails with a sentence naming the size, the location and
the code; a quota refusal points at Subscriptions → Usage + quotas. Prices come from the public
[Retail Prices API](https://prices.azure.com/api/retail/prices) (Linux meters; Windows and Low Priority meters
skipped; the `Spot` meter is the spot price), cached an hour per size and region.

## Dev setup

```bash
uv sync --extra azure
uv run pytest
uvx --from 'ruff>=0.15,<0.16' ruff check . && uvx --from 'ruff>=0.15,<0.16' ruff format --check .
```

Every Azure client, the Blob service, the Retail Prices API and the IP echo are fakes in the tests; nothing
reaches Azure. The SDK's conformance kit (`assert_conformant`) runs against the plugin with and without the
node lifecycle.

Point a dev compute service at this checkout via `TLC_COMPUTE_EXTERNAL_PLUGIN_DIRS=.../src`, open the Azure
page in the Hub and enter the subscription id. The plugin page's own calls name no Connection, so it shows the
sentence above and its management calls answer 409; nodes created through the Hub with this deployment's own
identity (AMBIENT) act through `az login` on the controller. The tests stand an AMBIENT Connection in to
exercise the provider.

## Host changes needed

None for the routes and shapes: the Hub reads `storage.label`, the capability flags, `regions`, node records
and `pricing` exactly as the AWS plugin reports them. One cosmetic gap noticed while mirroring:

- The Data page's upload progress and error text say "bucket"; with `storage.label` it could say "container".

## Phase 2

1. **Workspaces on Azure** — a CPU VM running the person's Object Service and compute service (Caddy, TLS
   under sslip.io names), the `flavor: "workspace"` branch, `workspace_credentials`, and the workspace wizard's
   storage step; `cpu-catalog` and `regions` exist for it already.
2. **Automatic role assignment for nodes** — grant the VM's managed identity Virtual Machine Contributor on
   the resource group and Storage Blob Data Contributor on the storage account at launch
   (`azure-mgmt-authorization`), so idle nodes delete themselves and reach Blob storage with no credential
   on the VM.
3. **More than one storage account** — list containers across the 3LC-tagged accounts of the resource group
   and resolve `abfs://` URLs to their account; today one account per plugin.
4. **Marketplace image plans and the NVIDIA driver extension** — `plan` on the VM for images that need one, and
   the `NvidiaGpuDriverLinux` extension for plain Ubuntu images.
5. **Spot eviction notice** — read the Scheduled Events endpoint on the node so the agent can fail the job
   cleanly before Azure evicts the VM.
6. **Placement scores and zone selection** — Azure's Spot Placement Scores API for the "availability" column,
   and zonal placement for sizes that require it.
7. **Multipart browser uploads** — block uploads for files above the single-request ceiling (5000 MiB), and
   Blob Batch for large deletes across containers.
8. **Live e2e** — run the plugin against a real subscription (the API-drift gate the fakes cannot be).

## Staging development and publishing

The plugin SDK 0.5 and the 3.5 core it is locked against are not on PyPI yet; `pyproject.toml` routes both
to the private `staging` index
(CloudRepo `prereleases`). Set that index's credentials in your shell (keep them out of source files):

```bash
export UV_INDEX_STAGING_USERNAME="<account email>"
export UV_INDEX_STAGING_PASSWORD="<read token>"
uv sync --locked --group dev --extra azure
uv run --no-sync pytest
```

The Release workflow builds verified artifacts on manual runs. `publish=true` uploads them
to the private staging index; publishing is disabled by default. The timestamp, run and
attempt suffix stamps the distribution and manifest together.

The separate `v*` tag path provides PyPI Trusted Publishing plumbing. Configure the PyPI
project's trusted publisher before using that path; no public release is needed while the SDK is staged.
