The platform for continuously improving AI agents.
"""Dedicated GPU menu, hourly metering, and dedicated/<model> chat routing."""
from __future__ import annotations
import json
import time
import uuid
from decimal import Decimal
import pytest
from conftest import drain_stream
from django.utils import timezone
from rest_framework.test import APIClient
from rest_framework_simplejwt.tokens import RefreshToken
from modal_shared.container_meter import STORE
from overbae.core.errors import InputValidationError
from overbae.models import BillingTelemetry, DedicatedDeployment, InferenceCall, Project, User
from overbae.models.billing import BillingService
from overbae.models.inference import DeployedModel
from overbae.services import container_meter, dedicated, inference_requests
from overbae.services.provider_pricing import refresh_rates
from tests.fakes.modal import open_chat_tunnel
pytestmark = [pytest.mark.django_db, pytest.mark.covers("state-machines")]
def _user() -> User:
return User.objects.create_user(
email=f"u-{uuid.uuid4().hex[:6]}@test.com",
password="pw",
clerk_user_id=f"clerk_{uuid.uuid4().hex}",
)
def _ready(project: Project) -> DeployedModel:
return DeployedModel.objects.create(
project=project,
model_id=f"ft-{uuid.uuid4().hex[:8]}",
status=DeployedModel.Status.READY,
base_model_id="meta-llama/Llama-3.2-3B-Instruct",
gpu_type="L4",
)
def _ok(**_kwargs):
return {
"status": 200,
"headers": {"content-type": "application/json"},
"body": json.dumps(
{
"model": "dedicated/internal",
"system_fingerprint": "vllm-0.30.0-nohash",
"choices": [{"message": {"content": "hi"}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
}
).encode(),
}
def test_missing_rate_refuses_start_and_a_second_start_conflicts(fake_modal):
refresh_rates()
user = _user()
project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
deployed = _ready(project)
with pytest.raises(InputValidationError, match="price is unavailable"):
dedicated.start(deployed, user, gpu_type="L4")
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
row = dedicated.start(deployed, user, gpu_type="H100")
assert row.credits_per_gpu_hour > 0
with pytest.raises(InputValidationError, match="already has a dedicated"):
dedicated.start(deployed, user, gpu_type="H100")
def test_stopped_deployment_can_restart_with_its_saved_configuration(fake_modal):
refresh_rates()
user = _user()
project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
deployed = _ready(project)
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
row = dedicated.start(
deployed,
user,
gpu_type="H100",
min_replicas=2,
max_replicas=3,
idle_shutdown_seconds=600,
)
dedicated.advance(str(row.id))
dedicated.advance(str(row.id))
dedicated.stop(row)
fake_modal.worker_stats = {"num_total_runners": 0, "backlog": 0, "num_running_inputs": 0}
dedicated.advance(str(row.id))
row.refresh_from_db()
assert row.status == DedicatedDeployment.Status.OFFLINE
assert any(
kind == "autoscaler" and kwargs.get("min_containers") == 0
for kind, _, _, kwargs in fake_modal.log
)
restarted = dedicated.start(
deployed,
user,
gpu_type=row.gpu_type,
min_replicas=row.min_replicas,
max_replicas=row.max_replicas,
scale_to_zero=row.scale_to_zero,
idle_shutdown_seconds=row.idle_shutdown_seconds,
)
assert restarted.min_replicas == 2
assert restarted.max_replicas == 3
assert restarted.idle_shutdown_seconds == 600
@pytest.mark.covers("ledger")
def test_the_containers_meter_dedicated_time_and_the_deployment_shows_it(fake_modal):
refresh_rates()
user = _user()
project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
deployed = _ready(project)
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
fake_modal.worker_stats = {"num_total_runners": 2, "backlog": 0, "num_running_inputs": 0}
row = dedicated.start(deployed, user, gpu_type="H100", min_replicas=1, max_replicas=2)
dedicated.advance(str(row.id))
dedicated.advance(str(row.id))
row.refresh_from_db()
assert row.status == DedicatedDeployment.Status.ONLINE
assert not BillingTelemetry.objects.filter(service=BillingService.DEDICATED_INFERENCE).exists()
now = time.time()
fake_modal.dictionaries.setdefault(("", STORE), {})["td-1"] = {
"container": "td-1",
"function": "H100_vllm_dedicated",
"gpu": "H100",
"gpu_count": 1,
"cpu": 8,
"memory_gib": 64,
"started_at": now - 120,
"seen_at": now,
"wall_seconds": 120,
"cpu_core_seconds": 960,
"memory_gib_seconds": 7680,
"refs": {},
"last_ref": f"served_model:{row.served_model_id}",
"default_ref": f"served_model:{row.served_model_id}",
"stopped": False,
}
container_meter.collect()
(charge,) = BillingTelemetry.objects.filter(service=BillingService.DEDICATED_INFERENCE)
assert (charge.user_id, charge.actor_id, charge.quantity) == (user.pk, user.pk, 120)
DedicatedDeployment.objects.filter(pk=row.pk).update(next_poll_at=timezone.now())
dedicated.advance(str(row.id))
row.refresh_from_db()
assert row.accrued_credits == (-charge.amount * 100).quantize(Decimal("0.01"))
def test_gpu_change_scales_the_previous_gpu_to_zero(fake_modal):
refresh_rates()
user = _user()
project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
deployed = _ready(project)
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
row = dedicated.start(deployed, user, gpu_type="H100", min_replicas=1, max_replicas=1)
dedicated.advance(str(row.id))
dedicated.advance(str(row.id))
dedicated.update(row, gpu_type="H200")
drained = [
kwargs
for kind, name, _, kwargs in fake_modal.log
if kind == "autoscaler"
and name.endswith("H100_vllm_dedicated")
and kwargs.get("min_containers") == 0
]
assert drained
row.refresh_from_db()
assert row.gpu_type == "H200"
assert row.status == DedicatedDeployment.Status.DEPLOYING
@pytest.mark.covers("ledger")
def test_dedicated_chat_skips_per_request_billing_and_appears_in_the_model_list(fake_modal):
refresh_rates()
user = _user()
project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
from overbae.models import ProjectMembership
ProjectMembership.objects.create(user=user, project=project)
deployed = _ready(project)
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
open_chat_tunnel(
fake_modal,
"H100_vllm_dedicated",
{
"model": "dedicated/internal",
"system_fingerprint": "vllm-0.30.0-nohash",
"choices": [{"message": {"content": "hi"}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
},
)
row = dedicated.start(deployed, user, gpu_type="H100")
dedicated.advance(str(row.id))
dedicated.advance(str(row.id))
row.refresh_from_db()
client = APIClient()
token = RefreshToken.for_user(user)
client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.access_token}")
response = client.post(
"/api/v1/chat/completions",
{"model": row.public_model_id, "messages": [{"role": "user", "content": "Hi"}]},
format="json",
)
assert response.status_code == 200
assert response.json()["model"] == f"dedicated/{deployed.model_id}"
assert "system_fingerprint" not in response.json()
call = InferenceCall.objects.get(requested_model=row.public_model_id)
assert call.cost is None
assert BillingTelemetry.objects.filter(service=BillingService.INFERENCE_FT_MODEL).count() == 0
listed = client.get("/api/v1/models")
assert row.public_model_id in {item["id"] for item in listed.json()["data"]}
def test_dedicated_chat_streams_tokens_before_the_reply_finishes(fake_modal):
refresh_rates()
user = _user()
project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
from overbae.models import ProjectMembership
ProjectMembership.objects.create(user=user, project=project)
deployed = _ready(project)
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
piece = json.dumps(
{
"model": "internal",
"system_fingerprint": "vllm",
"choices": [{"delta": {"content": "hi"}, "finish_reason": None}],
}
)
usage = json.dumps(
{
"model": "internal",
"choices": [],
"usage": {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3},
"metrics": {
"time_to_first_token_ms": 20,
"generation_time_ms": 40,
"tokens_per_second": 50,
},
}
)
open_chat_tunnel(
fake_modal,
"H100_vllm_dedicated",
{"choices": [{"message": {"content": "hi"}}]},
stream=f"data: {piece}\n\ndata: {usage}\n\ndata: [DONE]\n\n".encode(),
)
row = dedicated.start(deployed, user, gpu_type="H100")
dedicated.advance(str(row.id))
dedicated.advance(str(row.id))
row.refresh_from_db()
client = APIClient()
token = RefreshToken.for_user(user)
client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.access_token}")
response = client.post(
"/api/v1/chat/completions",
{
"model": row.public_model_id,
"messages": [{"role": "user", "content": "Hi"}],
"stream": True,
},
format="json",
)
assert response.status_code == 200
assert "text/event-stream" in response["Content-Type"]
text = drain_stream(response).decode()
assert '"content": "hi"' in text
assert f'"model": "{row.public_model_id}"' in text
assert "system_fingerprint" not in text
assert "tokens_per_second" not in text
assert text.strip().endswith("data: [DONE]")
call = InferenceCall.objects.get(requested_model=row.public_model_id)
assert call.tokens_per_second == 50
assert call.cost is None
def test_dedicated_list_returns_the_latest_row_for_each_model():
from overbae.models import ProjectMembership
user = _user()
project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
ProjectMembership.objects.create(user=user, project=project)
other = Project.objects.create(name="Other", slug=f"p-{uuid.uuid4().hex[:8]}")
first = _ready(project)
second = _ready(project)
foreign = _ready(other)
def row(deployed, gpu, status):
return DedicatedDeployment.objects.create(
project=deployed.project,
deployed_model=deployed,
gpu_type=gpu,
serving_shape="lora_bf16",
status=status,
rate_usd_per_gpu_hour="1",
credits_per_gpu_hour="100",
)
row(first, "L4", DedicatedDeployment.Status.OFFLINE)
current = row(first, "H100", DedicatedDeployment.Status.ONLINE)
row(second, "L40S", DedicatedDeployment.Status.OFFLINE)
row(foreign, "H100", DedicatedDeployment.Status.ONLINE)
client = APIClient()
client.force_authenticate(user)
response = client.get("/api/deployed-models/dedicated/", {"project": str(project.id)})
assert response.status_code == 200
body = response.json()["results"]
assert {item["deployed_model"] for item in body} == {str(first.id), str(second.id)}
listed = next(item for item in body if item["deployed_model"] == str(first.id))
assert listed["id"] == str(current.id)
assert listed["gpu_type"] == "H100"
assert listed["model_name"] == first.model_id
assert listed["model_id"] == f"dedicated/{first.model_id}"
def test_failed_warmup_releases_the_remote_floor_before_becoming_terminal(fake_modal):
refresh_rates()
user = _user()
project = Project.objects.create(owner=user, name="Failure cleanup")
deployed = _ready(project)
fake_modal.deploy(
"overmind-dedicated", "H100_vllm_dedicated.infer", lambda **kwargs: {"status": 503}
)
row = dedicated.start(deployed, user, gpu_type="H100")
dedicated.advance(str(row.pk))
dedicated.advance(str(row.pk))
row.refresh_from_db()
assert row.status == "shutting_down"
assert row.stopped_at is None
assert dedicated.due().filter(pk=row.pk).exists() is False # Next observation is scheduled.
fake_modal.worker_stats = {"num_total_runners": 1}
dedicated.advance(str(row.pk))
row.refresh_from_db()
assert row.status == "shutting_down"
assert row.running_replicas == 1
assert any(
kind == "autoscaler" and kwargs.get("min_containers") == 0
for kind, _, _, kwargs in fake_modal.log
)
fake_modal.worker_stats = {"num_total_runners": 0}
dedicated.advance(str(row.pk))
row.refresh_from_db()
assert row.status == "failed"
assert row.stopped_at is not None
@pytest.mark.covers("work-once")
def test_a_dedicated_request_is_read_back_from_its_saved_call(fake_modal):
user = _user()
project = Project.objects.create(owner=user, name="Dedicated request")
model = _ready(project)
refresh_rates()
row = dedicated.start(model, user, gpu_type="H100")
row.status = "online"
row.save(update_fields=["status"])
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok, held=True)
request = inference_requests.submit(
model,
user,
"slow",
{"messages": [{"role": "user", "content": "Hi"}], "max_tokens": 32},
dedicated=row,
)
inference_requests.advance(request.pk)
# A worker that takes over reads the saved call instead of sending the request again.
inference_requests.advance(request.pk)
fake_modal.release("H100_vllm_dedicated.infer")
inference_requests.advance(request.pk)
request.refresh_from_db()
assert request.state == "succeeded" and request.result["content"] == "hi"
assert fake_modal.spawns() == ["H100_vllm_dedicated.infer"]
@pytest.mark.covers("work-once")
def test_dedicated_unknown_acknowledgement_is_never_replayed(fake_modal):
user = _user()
project = Project.objects.create(owner=user, name="Unknown dedicated acknowledgement")
model = _ready(project)
refresh_rates()
row = dedicated.start(model, user, gpu_type="H100")
row.status = "online"
row.save(update_fields=["status"])
request = inference_requests.submit(
model,
user,
"unknown",
{"messages": [{"role": "user", "content": "Hi"}], "max_tokens": 32},
dedicated=row,
)
inference_requests.advance(request.pk)
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
inference_requests.advance(request.pk)
request.refresh_from_db()
assert request.state == "submission_unknown"
assert fake_modal.spawns() == []
@pytest.mark.covers("ledger")
def test_deleting_a_model_shuts_its_dedicated_pool_down(fake_modal, scripted):
from overbae.models import ProjectMembership
scripted("http://inference.test").reply(200, json_body={})
refresh_rates()
user = _user()
project = Project.objects.create(owner=user, name="P", slug=f"p-{uuid.uuid4().hex[:8]}")
ProjectMembership.objects.create(user=user, project=project)
deployed = _ready(project)
fake_modal.deploy("overmind-dedicated", "H100_vllm_dedicated.infer", _ok)
row = dedicated.start(deployed, user, gpu_type="H100")
dedicated.advance(str(row.id))
dedicated.advance(str(row.id))
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=f"Bearer {RefreshToken.for_user(user).access_token}")
response = client.delete(f"/api/deployed-models/{deployed.id}/")
assert response.status_code == 204
row.refresh_from_db()
assert row.status == DedicatedDeployment.Status.SHUTTING_DOWN
fake_modal.worker_stats = {"num_total_runners": 0, "backlog": 0, "num_running_inputs": 0}
dedicated.advance(str(row.id))
row.refresh_from_db()
assert row.status == DedicatedDeployment.Status.OFFLINE