# Model Swap

> Replace a model backend in Red Hat OpenShift AI Models as a Service without changing anything from the customer's perspective — same API key, same model ID.

---

LLMS index: [llms.txt](/CAI-Field-Manual-MaaS/llms.txt)

---

This page explains how to replace a model backend in Red Hat OpenShift AI Models as a Service without changing anything from the customer's perspective - same API key, same model ID. The key is the `MaaSModelRef` abstraction layer that decouples the customer-facing API from the actual inference backend. Customers must use the body-based routing (BBR) endpoint (`/v1/chat/completions`) for seamless swaps.

> [!TIP]
> All file paths and `oc apply` commands in this guide are relative to the [CAI-Field-Manual-MaaS](https://github.com/rh-aiservices-bu/CAI-Field-Manual-MaaS) repository root. Make sure you have cloned it and are working from its root directory (see [Getting Started](/CAI-Field-Manual-MaaS/maas/#getting-started)).

> [!IMPORTANT]
> This guide is not a replacement for the official Red Hat OpenShift AI Models as a Service documentation ([3.5](https://docs.redhat.com/en/documentation/red_hat_openshift_ai_self-managed/3.5/html/govern_llm_access_with_models-as-a-service/index) | [3.4](https://docs.redhat.com/en/documentation/red_hat_openshift_ai_self-managed/3.4/html/govern_llm_access_with_models-as-a-service/index)). It is a companion resource with opinionated Kustomize manifests and automation scripts to accelerate deployment.

## Overview

A model swap is the process of replacing the inference backend behind a model without affecting customers. Typical scenarios include:

- Upgrading to a newer model version (e.g. Qwen 3.6 to Qwen 3.8)
- Replacing a GPU model with a more efficient one
- Moving from a simulator to a real model (or vice versa)
- Switching hardware (e.g. different GPU type or node pool)

The swap works because `MaaSModelRef` acts as an indirection layer. Auth policies, subscriptions, and API keys all reference the MaaSModelRef by name - they have no knowledge of which `LLMInferenceService` sits behind it. Swapping the backend is a one-field patch.

## Resource Hierarchy

Understanding how resources relate to each other is critical for a safe swap. Some resources are created by the admin, others are auto-created by `maas-controller`.

| Resource | Namespace | Created By | Role |
| --- | --- | --- | --- |
| **LLMInferenceService** | `llm` (model ns) | Admin | Defines the inference workload: container, model weights, resources, gateway routing. This is the actual serving pod. |
| **MaaSModelRef** | `llm` (model ns) | Admin | Registers the model with the MaaS control plane. Points to an LLMInferenceService (or ExternalModel) via `spec.modelRef`. This is the stable identity that customers interact with. |
| **MaaSAuthPolicy** | `models-as-a-service` | Admin | Controls who can access the model. References MaaSModelRef by name + namespace. |
| **MaaSSubscription** | `models-as-a-service` | Admin | Defines rate-limiting tiers. References MaaSModelRef by name + namespace. API keys are permanently bound to a subscription at creation time. |
| **HTTPRoute** | `llm` (model ns) | Controller (KServe) | Routes traffic from the Gateway to the model pod. Created automatically when the LLMInferenceService is deployed. |
| **TokenRateLimitPolicy** | `llm` (model ns) | Controller (maas-controller) | Enforces token rate limits from MaaSSubscription. Owned by the HTTPRoute - garbage collected when the HTTPRoute is deleted. |
| **AuthPolicy (singleton)** | Gateway ns | Controller (maas-controller) | Shared gateway-level auth policy. One per gateway, not per model. |

### The Abstraction Layer

The diagram below shows how the resources connect. The MaaSModelRef is the pivot point - everything above it (auth, subscriptions, API keys) stays the same during a swap. Only the pointer below it (to the LLMInferenceService) changes.

![Model Swap Architecture](images/model-swap-diagram.png)

### MaaSModelRef Phase Transitions

The MaaSModelRef goes through these phases:

| Phase | Meaning |
| --- | --- |
| **Pending** | Backend is initializing or no governance pairing found yet. |
| **Ready** | Backend is healthy AND at least one MaaSSubscription + MaaSAuthPolicy pair is active. Inference is possible. |
| **Unhealthy** | Governance is attached but the backend has a runtime or health failure. |
| **Failed** | Non-recoverable reconciliation error. |
| **Invalid** | The resource spec is missing or structurally invalid. |

Governance means at least one `MaaSSubscription` AND one `MaaSAuthPolicy` both reference the same MaaSModelRef. Both are required for the model to reach `Ready` phase. These two CRDs are independent - updating one does NOT auto-update the other. For details on keeping them in sync, see [Governance Pairing](/CAI-Field-Manual-MaaS/maas/model-deployment/maas-models/#governance-pairing) in Phase 5.

## What Changes vs What Stays the Same

| Component | Changes? | Why |
| --- | --- | --- |
| LLMInferenceService | Yes | New backend deployed (`qwen-38`), old one deleted (`qwen-36`). |
| MaaSModelRef `spec.modelRef.name` | Yes | Pointer swapped from `qwen-36` to `qwen-38`. |
| MaaSModelRef name | **No** | `qwen-coder` is the stable identity that customers see. Keeping it the same is what makes the swap seamless. |
| MaaSAuthPolicy | **No** | References MaaSModelRef `qwen-coder` by name (unchanged). |
| MaaSSubscription | **No** | References MaaSModelRef `qwen-coder` by name (unchanged). |
| API keys | **No** | Bound to a subscription at creation time. Subscription is unchanged, so keys keep working. |
| Model ID in requests | **No** | Both `qwen-36` and `qwen-38` serve the same `spec.model.name` (`Qwen/Qwen3-Coder`), so the canonical model ID (`publishers/llm/models/Qwen/Qwen3-Coder`) stays the same. |
| BBR endpoint (`/v1/chat/completions`) | **No** | Body-based routing uses the canonical model ID in the request body (`publishers/llm/models/Qwen/Qwen3-Coder`), derived from the namespace and `spec.model.name` (both unchanged). Customers using this endpoint need no changes. |
| Per-model URL path (`/llm/<name>/...`) | **Yes** | The per-model URL path changes from `/llm/qwen-36/...` to `/llm/qwen-38/...` because it is derived from the LLMInferenceService name. Customers using per-model URLs must switch to the BBR endpoint. |

> [!WARNING]
> The per-model URL path changes after a swap: `/llm/qwen-36/v1/chat/completions` becomes `/llm/qwen-38/v1/chat/completions` because it is derived from the LLMInferenceService name, not the MaaSModelRef name. Always use the BBR endpoint (`/v1/chat/completions`) with the full publisher model ID in the request body (e.g. `publishers/llm/models/Qwen/Qwen3-Coder`) for swap-safe client integration.

## Prerequisites

- [Phases 1](/CAI-Field-Manual-MaaS/maas/installation-guide/prerequisites/)-[5](/CAI-Field-Manual-MaaS/maas/model-deployment/maas-models/) completed (Red Hat OpenShift AI installed, Models as a Service platform running, `llm` namespace created)
- Admin access to the model namespace and `models-as-a-service` namespace

## Swap Procedure

This procedure walks through the full swap lifecycle using the provided Qwen 3.6 -> 3.8 simulator templates. Both templates use the CPU simulator image (`llm-d-inference-sim`), so no GPU is required.

The scenario: you have a model called `qwen-36` registered with MaaS through a MaaSModelRef called `qwen-coder`. You want to replace it with `qwen-38` without affecting customers.

> [!TIP]
> If you already have a model deployed from [Phase 5](/CAI-Field-Manual-MaaS/maas/model-deployment/maas-models/), you can skip the original model deployment and adapt the steps to your existing model names.

### Step 1: Deploy the Original Model

Deploy the original model (`qwen-36`) with its full MaaS stack (MaaSModelRef, AuthPolicy, Subscriptions):

```sh
oc apply -k manifests/99-model-swap/qwen-36/
```

Wait for the model to become Ready:

```sh
oc wait llminferenceservice qwen-36 -n llm --for=condition=Ready --timeout=300s
oc get maasmodelref -n llm -o wide
```

Expected output:

```text
NAME          PHASE   ENDPOINT                                                  HTTPROUTE                GATEWAY              AGE
qwen-coder    Ready   https://maas.<cluster-domain>/                            qwen-36-kserve-route     maas-default-gateway  ...
```

### Step 2: Deploy the Replacement Model

Deploy the replacement (`qwen-38`) alongside the existing one:

```sh
oc apply -k manifests/99-model-swap/qwen-38/
```

> [!IMPORTANT]
> The new LLMInferenceService **must** use the same `spec.model.name` as the existing one. Both `qwen-36` and `qwen-38` use `Qwen/Qwen3-Coder`. This is the model ID that customers send in their API requests (`/v1/chat/completions`). If the names differ, customers would need to update their client code.

### Step 3: Verify the Replacement is Ready

Wait for both LLMInferenceServices to be running:

```sh
oc get llminferenceservice -n llm
```

Expected output - both old and new show a `Ready` condition:

```text
NAME       READY   ...
qwen-36    True    ...
qwen-38    True    ...
```

For GPU models, this can take 5-15 minutes while the image is pulled and model weights are loaded.

### Step 4: Swap the MaaSModelRef Pointer

This is the swap itself. Patch the MaaSModelRef to point to the new LLMInferenceService:

```sh
oc patch maasmodelref qwen-coder -n llm --type=merge \
  -p '{"spec":{"modelRef":{"name":"qwen-38"}}}'
```

This one-field change is what makes the swap seamless. The MaaSModelRef name (`qwen-coder`) stays the same, so all auth policies, subscriptions, and API keys continue to work.

Verify the MaaSModelRef now points to `qwen-38`:

```sh
oc get maasmodelref qwen-coder -n llm -o jsonpath='{.spec.modelRef.name}'
# Expected: qwen-38
```

### Step 5: Delete the Old LLMInferenceService

While both LLMInferenceServices exist, the gateway routes 100% of BBR traffic to `qwen-36` (the first-created backend) and 0% to `qwen-38`. You must delete `qwen-36` so the gateway starts routing to `qwen-38`.

> [!NOTE]
> This means the swap is not zero-downtime. There is a brief window (typically a few seconds) between deleting the old model and the gateway routing to the new one where requests may fail.

```sh
oc delete llminferenceservice qwen-36 -n llm
```

This deletes the old inference pods, its HTTPRoute, and frees any GPU resources it was using.

### Step 6: Clean Up Stale TokenRateLimitPolicy

After swapping the MaaSModelRef and deleting the old LLMInferenceService, the `TokenRateLimitPolicy` (TRLP) may retain an owner reference to the old HTTPRoute. This causes the MaaSSubscription to go `Failed` because the TRLP references a non-existent route.

Delete the stale TRLP so the controller can recreate it with the correct owner reference:

```sh
oc delete tokenratelimitpolicy maas-trlp-qwen-coder -n llm
```

The `maas-controller` will automatically recreate the TRLP, now correctly owned by the new HTTPRoute.

### Step 7: Verify

Confirm that everything is healthy:

```sh
# MaaSModelRef should be Ready
oc get maasmodelref -n llm -o wide

# Only the new LLMInferenceService should exist
oc get llminferenceservice -n llm

# Subscriptions should be active (not Failed)
oc get maassubscription -n models-as-a-service

# TRLP should exist and reference the new HTTPRoute
oc get tokenratelimitpolicy -n llm
```

Test inference to confirm the swap worked. If you already have an API key from before the swap, use it - the whole point is that existing keys keep working. If you need a new one:

```sh
CLUSTER_DOMAIN=$(oc get ingresses.config/cluster -o jsonpath='{.spec.domain}')
MAAS_URL="maas.${CLUSTER_DOMAIN}"

# Get admin token
TOKEN=$(oc create token admin-user -n models-as-a-service --duration=1h)

# Create API key (bound to the qwen-coder-free subscription)
API_KEY=$(curl -sk -X POST "https://${MAAS_URL}/v1/api-keys" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{"name":"swap-test","description":"Post-swap verification","subscription":"qwen-coder-free"}' | \
  python3 -c "import sys,json; print(json.load(sys.stdin)['key'])")
echo "API_KEY=${API_KEY}"
```

Send an inference request using the BBR endpoint:

```sh
curl -sk "https://${MAAS_URL}/v1/chat/completions" \
  -H "Authorization: Bearer ${API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "publishers/llm/models/Qwen/Qwen3-Coder",
    "messages": [{"role": "user", "content": "Hello!"}]
  }' | jq .
```

A successful response confirms the swap is complete - the request was routed to `qwen-38` using the same model ID and API key that worked with `qwen-36`.

> [!NOTE]
> The model ID in the request body must be the full publisher path as returned by `/v1/models` (e.g. `publishers/llm/models/Qwen/Qwen3-Coder`). Using the short name (`Qwen/Qwen3-Coder`) returns a 404.

## Operational Notes

> [!WARNING]
> **BBR Routing Conflict**
>
> When two LLMInferenceServices in the same namespace share the same `spec.model.name`, their HTTPRoutes create identical BBR match rules. The gateway accepts both routes but routes 100% of traffic to the first-created backend - the new model receives zero requests. This was validated on OpenShift 4.21: 10/10 requests hit the old pod, 0/10 hit the new one. Deleting the old LLMInferenceService removes its HTTPRoute and lets the gateway discover the new one. There is no way to "test the new model first" while the old one exists.

> [!WARNING]
> **TokenRateLimitPolicy Stale Owner Reference**
>
> The `TokenRateLimitPolicy` is auto-created by `maas-controller` and owned by the HTTPRoute. When the MaaSModelRef pointer changes, the TRLP still references the old HTTPRoute. Deleting the TRLP (Step 6) lets the controller recreate it with the correct owner. If you skip this, the MaaSSubscription may go `Failed` with an error like: `Object <namespace>/maas-trlp-<name> is already owned by another HTTPRoute`.

> [!NOTE]
> **endpointOverride**
>
> If you created the MaaSModelRef manually (not through the Kustomize manifests in Phase 5), the controller may not be able to auto-discover the endpoint URL. In that case, set `spec.endpointOverride` on the MaaSModelRef:
>
> ```sh
> oc patch maasmodelref <name> -n llm --type=merge \
>   -p '{"spec":{"endpointOverride":"https://maas.<cluster-domain>/"}}'
> ```
>
> You can check if this is needed by looking at the MaaSModelRef status. If it is stuck in `Unhealthy` with an empty endpoint, `endpointOverride` is the fix.

> [!NOTE]
> **Model ID Format**
>
> The model ID used in inference requests (`/v1/chat/completions`) is the full publisher path, not the short model name. For example:
>
> - Short name: `Qwen/Qwen3-Coder`
> - Full publisher path: `publishers/llm/models/Qwen/Qwen3-Coder`
>
> Always use the model ID as returned by the `/v1/models` endpoint to avoid 404 errors.

## Template Manifests

The `manifests/99-model-swap/` directory contains two concrete simulator-based templates that walk through the full swap lifecycle (Qwen 3.6 -> 3.8):

```text
99-model-swap/
  qwen-36/                             # Original model (deploy first)
    kustomization.yaml                 # Aggregates llm/ and maas/
    llm/
      kustomization.yaml               # Sets namespace: llm
      model.yaml                       # LLMInferenceService: qwen-36
    maas/
      kustomization.yaml               # MaaS governance resources
      maas-model.yaml                  # MaaSModelRef: qwen-coder -> qwen-36
      maas-auth-policy.yaml            # MaaSAuthPolicy: qwen-coder-access
      maas-subscription-free.yaml      # Free tier (100 tokens/min)
      maas-subscription-premium.yaml   # Premium tier (100000 tokens/min)
  qwen-38/                             # Replacement model (deploy second)
    kustomization.yaml                 # Aggregates llm/ only
    llm/
      kustomization.yaml               # Sets namespace: llm
      model.yaml                       # LLMInferenceService: qwen-38
```

Both templates use the CPU simulator image (`llm-d-inference-sim`), so no GPU is required. Both share `spec.model.name: Qwen/Qwen3-Coder` - this is the invariant that makes the swap seamless.

The `qwen-36/` directory includes the full MaaS stack (MaaSModelRef + AuthPolicy + Subscriptions) because it is the original deployment. The `qwen-38/` directory only includes the LLMInferenceService because the MaaS governance resources persist unchanged across the swap - only the MaaSModelRef pointer changes.

For a real swap with GPU models, replace the container image, model URI, and resource requests in both `model.yaml` files to match your actual models.

## References

- [Architecture & Request Flow](/CAI-Field-Manual-MaaS/maas/reference/architecture/) - full Models as a Service component overview and request lifecycle
- [Phase 5: Model Deployment](/CAI-Field-Manual-MaaS/maas/model-deployment/maas-models/) - how to deploy a model from scratch
- [Upstream MaaS Documentation](https://opendatahub-io.github.io/models-as-a-service/latest/)
