colmugx found magpie hotter with groups, and worse since ~v0.1.1225. Yayoi_no_yume saw CPU jump to 100% as soon as a request entered a group, and stay there under concurrency. Cause: one request to a group asked for the groups' entries (groupEntries) five or six times: Catalog from Resolve and IsDecider, and Served from membersImageInput, outputLimit, windowIn and roomy. A direct provider/model request asked through Resolve too. Nothing held that work. Each build: - went through every member of every group, the found auto-<model> ones included, with a linear pass over the whole catalog per member. It copied each large Entry it passed (groupEntries, resolveIn); - since8f4d091c6(#2224) ran smallestWindow for every group, not only one set to ContextSmallest. That was a second full pass per member, which is the regression after v0.1.1225; - parsed settings.json again for each group's disabled models (membersIn -> disabledList -> settings.LoadChecked). Fix: - groupEntries is held while a request holds the catalog. heldFrom keys it to the catalog slice it was built from, so it is rebuilt for a rebuilt catalog. Catalog and Served hand out a copy. - Each member's entry is looked up in a map built once per build. - smallestWindow runs only for ContextSmallest. - resolveIn walks by index, not by copying each Entry. - disabledList is held like heldSettings. SetDisabledModels calls Changed, so a change is seen at once. Guards (each fails without its fix, broken by hand): - TestGroupEntriesBuiltOnceWhileHeld: the same build under one Hold. Also checks that a caller's change to Catalog doesn't reach the next caller, that another catalog is built from, and that a save is seen. - TestGroupLooksParseNoSettingsPerGroupWhileHeld: settings parses per look. - BenchmarkGroupEntries (provider) and BenchmarkGroupOverhead / BenchmarkGroupOverheadParallel (gateway). These use fake upstreams: direct vs groups of 1, 4 and 8 members, one with a failing first member and one with a resting first member, at 200KB and 2MB, streamed and not, on a 12x20 and a 30x60 catalog. Numbers. cpu-ms/op is process CPU per request. The machine was at load ~200-430, so wall times are not comparable. - Catalog of 30 providers x 60 shared models, 200KB, non-stream, BenchmarkGroupOverhead, 5x: | Version | direct p0/m1 | groups (g1 g4 g8u gfail grest) | |----------------------|--------------|--------------------------------| | v0.1.1225 (54ba9042d) | 242 | 976 / 1006 / 965 / 966 / 945 | | HEADccb2eea15| 571 | 1462 / 1745 / 1719 / 1758 / 1715 | | this commit | 76 | 93 / 116 / 91 / 114 / 106 | Parallel, HEAD -> this commit: direct 563 -> 73, groups 1355-1625 -> 94-152. The cost of entering a group, over direct: ~+1150 ms at HEAD, ~+15-40 ms now. Memory per group request: 200MB -> 74-79MB. Allocs: 442k -> 128-141k. - BenchmarkGroupEntries, one build of the 30x60 catalog's groups, CPU: HEAD 233 ms; HEAD with smallestWindow gated only 151 ms; this commit 20 ms. - 12x20 catalog, 200KB, HEAD (before): direct 45.5, groups 83-89 cpu-ms/op. v0.1.1225: direct 37, groups 85-97. So with a small catalog the overhead is old, not new. It grows with providers x models x groups, which is why colmugx's and Yayoi_no_yume's catalogs feel it. Run at this head: - go test ./... -timeout 45m at load ~430: 60 packages ok, including internal/provider. internal/agent, internal/gateway and internal/library hit the 45m timeout under that load. These were not failures. internal/gui failed two tests: - TestSetAnswersWhileDevinAndProvidersHang ("set slow/slow-1 took 11.9s", over its 10s wall bound) failed in the run and once more alone (16.25s). It passed on theccb2eea15checkout (9.95s) and 2 of 2 with -count=2 at this commit. It is a wall-clock bound under load, and this commit doesn't touch its path. - TestMainWindowCorners was killed while measuring and passed rerun. - go test ./internal/gateway -run 'Group|Member|Rout|Fallback|Rest|Window|Image' -count=1: ok (221s) - TestGroupLooksParseNoSettingsPerGroupWhileHeld with disabledList not held: red, "settings.json parsed 50 times in 50 looks" - gofmt -l internal: clean - GOOS=linux go vet -tags nogui ./...: clean - GOOS=windows go vet ./...: clean
197 lines
7.1 KiB
Go
197 lines
7.1 KiB
Go
package gateway
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"io/fs"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
// groupBenchUpstream answers an Anthropic request as it asked: streamed
|
|
// when its body says so. Refusing, it answers code with an overloaded
|
|
// error.
|
|
type groupBenchUpstream struct{ code int }
|
|
|
|
const groupBenchReply = `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":7,"output_tokens":1}}`
|
|
|
|
var groupBenchStream = sse(
|
|
`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","model":"m1","usage":{"input_tokens":7}}}`,
|
|
`event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
|
|
`event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}`,
|
|
`event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`,
|
|
`event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`,
|
|
`event: message_stop`+"\n"+`data: {"type":"message_stop"}`)
|
|
|
|
func (u groupBenchUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
b, _ := io.ReadAll(r.Body)
|
|
if u.code != 0 {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Header().Set("Retry-After", "3600")
|
|
w.WriteHeader(u.code)
|
|
io.WriteString(w, `{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}`)
|
|
return
|
|
}
|
|
if bytes.Contains(b, []byte(`"stream":true`)) {
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
io.WriteString(w, groupBenchStream)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
io.WriteString(w, groupBenchReply)
|
|
}
|
|
|
|
// groupBenchCatalog is a catalog of providers serving models each, the
|
|
// same model ids at each (so magpie finds a group of each model), and
|
|
// groups of one, four and eight members, one whose first member fails
|
|
// every time, and one whose first member is resting.
|
|
func groupBenchCatalog(b *testing.B, providers, models int) {
|
|
b.Helper()
|
|
b.Setenv("XDG_CONFIG_HOME", b.TempDir())
|
|
b.Setenv("XDG_CACHE_HOME", b.TempDir())
|
|
good := httptest.NewServer(groupBenchUpstream{})
|
|
b.Cleanup(good.Close)
|
|
failing := httptest.NewServer(groupBenchUpstream{code: 500})
|
|
b.Cleanup(failing.Close)
|
|
resting := httptest.NewServer(groupBenchUpstream{code: 429})
|
|
b.Cleanup(resting.Close)
|
|
var ids []string
|
|
for i := range models {
|
|
ids = append(ids, fmt.Sprintf("m%d", i))
|
|
}
|
|
for i := range providers {
|
|
p := provider.Provider{ID: fmt.Sprintf("p%d", i), Name: fmt.Sprintf("P%d", i), Key: "k", Models: ids, Anthropic: good.URL}
|
|
if err := provider.Save(p); err != nil {
|
|
b.Fatal(err)
|
|
}
|
|
}
|
|
for _, p := range []provider.Provider{
|
|
{ID: "bad", Name: "Bad", Key: "k", Models: ids, Anthropic: failing.URL},
|
|
{ID: "rest", Name: "Rest", Key: "k", Models: ids, Anthropic: resting.URL},
|
|
} {
|
|
if err := provider.Save(p); err != nil {
|
|
b.Fatal(err)
|
|
}
|
|
}
|
|
if err := settings.Save(settings.Settings{}); err != nil {
|
|
b.Fatal(err)
|
|
}
|
|
for _, g := range []provider.Group{
|
|
{ID: "g1", Name: "G1", Members: []string{"p0/m1"}, Routing: provider.Ordered},
|
|
{ID: "g4", Name: "G4", Members: []string{"p0/m1", "p1/m1", "p2/m1", "p3/m1"}, Routing: provider.Ordered},
|
|
{ID: "g8u", Name: "G8U", Members: []string{"p0/m1", "p1/m1", "p2/m1", "p3/m1", "p4/m1", "p5/m1", "p6/m1", "p7/m1"}, Routing: provider.LeastUsed},
|
|
{ID: "gfail", Name: "GFail", Members: []string{"bad/m1", "p0/m1", "p1/m1"}, Routing: provider.Ordered},
|
|
{ID: "grest", Name: "GRest", Members: []string{"rest/m1", "p0/m1", "p1/m1"}, Routing: provider.Ordered},
|
|
} {
|
|
if err := provider.SaveGroup(g); err != nil {
|
|
b.Fatal(err)
|
|
}
|
|
}
|
|
// as a user's files are: written a while ago, not just now (a file
|
|
// written in the last seconds is read again each time)
|
|
old := time.Now().Add(-time.Hour)
|
|
filepath.WalkDir(os.Getenv("XDG_CONFIG_HOME"), func(path string, _ fs.DirEntry, _ error) error {
|
|
return os.Chtimes(path, old, old)
|
|
})
|
|
provider.Changed()
|
|
}
|
|
|
|
// groupBenchCase is one benchmark's request.
|
|
type groupBenchCase struct {
|
|
providers, models, words int
|
|
stream bool
|
|
model string
|
|
}
|
|
|
|
func (c groupBenchCase) name() string {
|
|
return fmt.Sprintf("catalog=%dx%d/%dKB/stream=%v/%s", c.providers, c.models, c.words*4/1000, c.stream, c.model)
|
|
}
|
|
|
|
// groupBenchCases: a dozen providers of 20 models, with a ~200KB and a
|
|
// ~2MB conversation, and a large catalog (30 providers of 60 models, as
|
|
// a user of several relays has) with the ~200KB one.
|
|
func groupBenchCases() []groupBenchCase {
|
|
var out []groupBenchCase
|
|
for _, size := range []struct{ providers, models, words int }{{12, 20, 50_000}, {12, 20, 500_000}, {30, 60, 50_000}} {
|
|
for _, stream := range []bool{false, true} {
|
|
for _, model := range []string{"p0/m1", "group/g1", "group/g4", "group/g8u", "group/gfail", "group/grest"} {
|
|
out = append(out, groupBenchCase{size.providers, size.models, size.words, stream, model})
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// groupBenchServer is the gateway with c's catalog, and a request of the
|
|
// body c sends that fails the benchmark unless it is answered.
|
|
func groupBenchServer(b *testing.B, c groupBenchCase) func() {
|
|
noRests()
|
|
b.Cleanup(noRests)
|
|
groupBenchCatalog(b, c.providers, c.models)
|
|
body := largeConversation(provider.Anthropic, c.model, c.words)
|
|
if c.stream {
|
|
body = bytes.Replace(body, []byte(`"stream":false`), []byte(`"stream":true`), 1)
|
|
}
|
|
b.SetBytes(int64(len(body)))
|
|
h := New().Handler()
|
|
do := func() {
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", bytes.NewReader(body)))
|
|
if rec.Code != 200 || !bytes.Contains(rec.Body.Bytes(), []byte("ok")) {
|
|
b.Fatalf("%d %s", rec.Code, rec.Body.String())
|
|
}
|
|
}
|
|
do() // the resting member rests
|
|
return do
|
|
}
|
|
|
|
// BenchmarkGroupOverhead is a request to a provider's model and the same
|
|
// request to routing groups, streamed and not, with a long conversation:
|
|
// what magpie adds for a group is the difference. cpu-ms/op is the CPU
|
|
// the process spent, which a busy machine doesn't change as it does the
|
|
// wall time.
|
|
func BenchmarkGroupOverhead(b *testing.B) {
|
|
for _, c := range groupBenchCases() {
|
|
b.Run(c.name(), func(b *testing.B) {
|
|
do := groupBenchServer(b, c)
|
|
b.ResetTimer()
|
|
cpu, _ := processCPU()
|
|
for range b.N {
|
|
do()
|
|
}
|
|
after, _ := processCPU()
|
|
b.ReportMetric(float64(after-cpu)/float64(b.N)/1e6, "cpu-ms/op")
|
|
})
|
|
}
|
|
}
|
|
|
|
// BenchmarkGroupOverheadParallel is BenchmarkGroupOverhead's requests sent
|
|
// at once, as several agents send them.
|
|
func BenchmarkGroupOverheadParallel(b *testing.B) {
|
|
for _, c := range groupBenchCases() {
|
|
if c.stream || c.words > 50_000 {
|
|
continue
|
|
}
|
|
b.Run(c.name(), func(b *testing.B) {
|
|
do := groupBenchServer(b, c)
|
|
b.ResetTimer()
|
|
cpu, _ := processCPU()
|
|
b.RunParallel(func(pb *testing.PB) {
|
|
for pb.Next() {
|
|
do()
|
|
}
|
|
})
|
|
after, _ := processCPU()
|
|
b.ReportMetric(float64(after-cpu)/float64(b.N)/1e6, "cpu-ms/op")
|
|
})
|
|
}
|
|
}
|