Files
gpu-broker/internal/ollamaproxy/proxy_test.go
T
Ziad ArafatandClaude Opus 5.5 20b1bc4c27 Ollama proxy; spread leases across GPUs
The proxy leases a not-yet-loaded model's size (+20%) and forces CPU-only
with 4 threads on a CPU grant; loaded models, other endpoints and a down
broker pass through. Spread leases let a model use both cards, as Ollama
does with gemma4-12b (8.4 GB > the 1080's 8 GB).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:55:38 -07:00

174 lines
5.1 KiB
Go

package ollamaproxy
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/sched"
"gitea.godemperordoge.org/ziadarafat/gpu-broker/internal/server"
)
const gib = 1 << 30
// fakeOllama serves /api/tags and /api/ps like Ollama and records inference bodies.
type fakeOllama struct {
mu sync.Mutex
loaded []string
bodies []map[string]any
paths []string
}
func (f *fakeOllama) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
f.paths = append(f.paths, r.Method+" "+r.URL.Path)
switch r.URL.Path {
case "/api/tags":
json.NewEncoder(w).Encode(map[string]any{"models": []map[string]any{
{"name": "gemma4-12b-qat:latest", "size": 7 * gib},
{"name": "qwen3.5-9b-gpu:latest", "size": 7 * gib},
}})
case "/api/ps":
var models []map[string]any
for _, m := range f.loaded {
models = append(models, map[string]any{"name": m, "size_vram": 7 * gib})
}
json.NewEncoder(w).Encode(map[string]any{"models": models})
default:
var body map[string]any
json.NewDecoder(r.Body).Decode(&body)
f.bodies = append(f.bodies, body)
w.Header().Set("Content-Type", "application/x-ndjson")
io.WriteString(w, `{"message":{"content":"hi"},"done":false}`+"\n")
w.(http.Flusher).Flush()
io.WriteString(w, `{"done":true}`+"\n")
}
}
type rig struct {
proxy *httptest.Server
ollama *fakeOllama
sched *sched.Scheduler
}
// newRig wires proxy -> fake Ollama, with a real broker whose GPUs have used0/used1 MB in use.
func newRig(t *testing.T, used0, used1 int, brokerUp bool) *rig {
t.Helper()
s := sched.New(sched.Config{ReserveMB: map[int]int{0: 1500}, LoadWindow: time.Minute, LeaseTTL: time.Minute}, time.Now)
s.Observe([]sched.GPU{{Index: 0, TotalMB: 6144, UsedMB: used0}, {Index: 1, TotalMB: 8192, UsedMB: used1}})
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go server.Tick(ctx, s, 20*time.Millisecond)
broker := httptest.NewServer(server.Handler(s, time.Minute))
t.Cleanup(broker.Close)
brokerURL := broker.URL
if !brokerUp {
brokerURL = "http://127.0.0.1:1" // nothing listens there
}
o := &fakeOllama{}
up := httptest.NewServer(o)
t.Cleanup(up.Close)
p, err := New(Config{Upstream: up.URL, Broker: brokerURL, MaxWait: time.Second, CPUThreads: 4, Prefer: []int{1}})
if err != nil {
t.Fatal(err)
}
px := httptest.NewServer(p)
t.Cleanup(px.Close)
return &rig{proxy: px, ollama: o, sched: s}
}
func (r *rig) chat(t *testing.T, model string, extra string) string {
t.Helper()
body := `{"model":"` + model + `","messages":[{"role":"user","content":"hi"}]` + extra + `}`
resp, err := http.Post(r.proxy.URL+"/api/chat", "application/json", strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
out, _ := io.ReadAll(resp.Body)
return string(out)
}
func (r *rig) lastBody(t *testing.T) map[string]any {
t.Helper()
r.ollama.mu.Lock()
defer r.ollama.mu.Unlock()
if len(r.ollama.bodies) == 0 {
t.Fatal("Ollama got no request")
}
return r.ollama.bodies[len(r.ollama.bodies)-1]
}
func TestFreeGPUForwardsTheRequestUnchanged(t *testing.T) {
r := newRig(t, 0, 0, true)
out := r.chat(t, "gemma4-12b-qat", `,"options":{"temperature":0}`)
if !strings.Contains(out, `"done":true`) {
t.Fatalf("response %q", out)
}
body := r.lastBody(t)
if body["options"].(map[string]any)["num_gpu"] != nil {
t.Fatalf("GPU request was changed: %v", body)
}
}
func TestLeaseSizeComesFromTheModelListAndIsReleasedAfter(t *testing.T) {
r := newRig(t, 0, 0, true)
r.chat(t, "gemma4-12b-qat", "")
// the lease was released once the response finished
if n := len(r.sched.Status().Leases); n != 0 {
t.Fatalf("%d leases left", n)
}
}
func TestBusyGPUsSendTheRequestToTheCPUWithFewThreads(t *testing.T) {
r := newRig(t, 6144, 8192, true)
r.chat(t, "gemma4-12b-qat", `,"options":{"temperature":0}`)
opts := r.lastBody(t)["options"].(map[string]any)
if opts["num_gpu"] != float64(0) || opts["num_thread"] != float64(4) || opts["temperature"] != float64(0) {
t.Fatalf("options %v", opts)
}
}
func TestLoadedModelsSkipTheBroker(t *testing.T) {
r := newRig(t, 6144, 8192, true) // GPUs look full: because the model is already on them
r.ollama.loaded = []string{"gemma4-12b-qat:latest"}
r.chat(t, "gemma4-12b-qat", "")
if r.lastBody(t)["options"] != nil {
t.Fatalf("loaded model was sent to the CPU: %v", r.lastBody(t))
}
}
func TestBrokerDownPassesThrough(t *testing.T) {
r := newRig(t, 0, 0, false)
out := r.chat(t, "gemma4-12b-qat", "")
if !strings.Contains(out, `"done":true`) || r.lastBody(t)["options"] != nil {
t.Fatalf("got %q / %v", out, r.lastBody(t))
}
}
func TestOtherEndpointsPassThrough(t *testing.T) {
r := newRig(t, 6144, 8192, true)
resp, err := http.Get(r.proxy.URL + "/api/tags")
if err != nil || resp.StatusCode != 200 {
t.Fatalf("%v %v", err, resp)
}
if len(r.sched.Status().Leases)+len(r.sched.Status().Waiting) != 0 {
t.Fatal("tags asked the broker")
}
}
func TestUnknownModelsPassThrough(t *testing.T) {
r := newRig(t, 6144, 8192, true)
r.chat(t, "not-pulled-yet", "")
if r.lastBody(t)["options"] != nil {
t.Fatal("unknown model was changed")
}
}