gateway: an image is described once, whatever model describes it, and a canceled request stops its descriptions

Pkh on Discord (0.1.2509, Linux, QwenPaw, Auto routing): with images in
the conversation, the Routing view filled with "Image description" rows,
one request asking for 63 in ~60ms, and the request they were for had no
row of its own.

Causes, each red on origin/main b2145eac1 (the new tests run there):
- A description was kept under the describing model and its level
  (sha256(model, effort, src)): AutoVision's pick changing between turns
  (opencode-go/deepseek-v4.1-flash, auto/qwen3.8-flash) read every image
  again. It is now kept under sightKey: a base64 data URL's decoded bytes
  (strict base64), else the URL, with the level picked in Settings, so
  the same picture on another protocol or media type is described once
  too, and seenBody dedupes by the key.
- describe ran on the first asker's context. Its agent canceling it failed
  the description for every request waiting on it ("context canceled",
  a 502 to a request nobody canceled) and took it out of the cache. The
  work now runs on its own context (WithoutCancel + cancel); a request
  that goes stops waiting, and only the last to go stops it and forgets
  it. A reply that came whole is kept though its asker ended.
- seenBody's queued images took a slot without looking at the context,
  so after a cancel each went on to serve with a dead context and put an
  instant 499 row on the Routing page. One waiting for a slot when its
  request ends is now asked of no one.
- The descriptions' routes are noted on the request's inflight (they run
  on its context), which dropped its "routing" placeholder; a cancel
  then left it no route at all. It now gets one (notDescribed), 499 when
  its agent canceled and 502 else, and the usage record names it. A
  group's request ends 499 on a cancel too.

Not as reported: a failure never threw away good descriptions (only the
failed one went), and seenBody already deduped and shared in-flight work
within the cache; it was the cancel, the model in the key, and the
queued work that made it read everything again.

Run on mote at this tree (rebased on da0005df8):
- gofmt -l internal: clean. go vet ./... on darwin, and GOOS=linux /
  GOOS=windows -tags nogui go vet ./...: ok.
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway: ok
  (806s); also ok on the earlier bases 8ac1c7a56 (with ./internal/catalog)
  and ccb75030a.
- -race -count=10 on the four new tests, TestUnrouted* and
  TestTextOnlyModelIsGivenTheImagesDescription: ok.

Broken by hand, each red with the named test:
- the model back in the key, and the key by src string:
  TestSameImageDescribedOnceWhateverDescribesIt;
- the work on the first asker's context:
  TestOneRequestGoneLeavesTheDescriptionToAnother (502 context canceled);
- the slot taken without the context: TestCanceledRequestAsksNoMoreDescriptions
  (9 rows, want 4); on origin/main 10;
- no notDescribed: TestCanceledWhileDescribingKeepsItsRoute (no route).

Not tried: Pkh's own QwenPaw conversation and providers; the fix is
tested with a fake describer only. heldSight (unrouted_test.go) now seeds
the cache under sightKey.
This commit is contained in:
yetone
2026-11-01 10:50:31 +08:00
parent da0005df81
commit f435aadbf3
5 changed files with 504 additions and 69 deletions
+45 -5
View File
@@ -962,7 +962,8 @@ searcher with no level at all. Only these two calls carry it
([`side_effort.go`](../../internal/gateway/side_effort.go)):
- `askVisionWith` sends Chat's `reasoning_effort`; the image cache key
(`describe`) has the level in it, so a new level reads the image again.
(`sightKey`) has the level picked in it, so a new pick reads the image
again.
- `searchBody` sends the searcher's Anthropic body `thinking` (`disabled` for
`none`, else enabled with `budgetOf`'s budget, 1024 for `minimal`) and
`output_config.effort` unless the vendor model is a Claude older than
@@ -1285,10 +1286,15 @@ asks no other.
- When none answers, the error is the first's reason as before, then
"nor could X, asked in its place: why" for each other one
(`visionFailed`).
- `sights` keeps a description under the describer asked first, whichever
model answered: the image sent again next turn is asked of no one, and a
new image is asked of the pick first again, so a pick that failed once is
not given up for good. A failure is still not kept.
- `sights` keeps a description under the image (`sightKey`): a base64
data URL's decoded bytes, else the URL, with the level picked in
Settings. Not under a model: the image sent again next turn is asked of
no one, whichever model is picked now (AutoVision's pick changing
between turns had a long conversation's every image described again,
Pkh on Discord), and a new image is asked of the pick first again, so a
pick that failed once is not given up for good. The same bytes sent on
another protocol, or under another media type, are described once
(`seenBody` dedupes by the key too). A failure is still not kept.
This differs from a searcher named in Settings, which gives way to no other
provider: a failed search still leaves the search APIs and the model's own
@@ -1302,6 +1308,40 @@ Covered by `TestPickedDescriberThatFailsGivesWayToTheNextThatSees`,
([`vision_fallback_test.go`](../../internal/gateway/vision_fallback_test.go))
and `vision-instead.test.cjs`.
## A description is no one request's
A description is asked once (`describe`) on a context of its own
(`context.WithoutCancel` of the first asker's, with its own cancel):
every request that sends the image while it is being described waits on
the same one (`sight.waiting`). One whose agent cancels it stops
waiting; the description goes on for the others, and only the last to
go stops it and takes it out of `sights`, so the next to send the image
asks again. Before, the description ran on the first asker's context:
its cancel failed the description for every other request waiting on it
with "context canceled", and took it out of the cache, so the next turn
read the image again. A reply that came whole is kept though its asker
ended as it came (`askVisionWith` reads the reply before the context).
In `seenBody`, an image waiting for one of the `visionParallel` slots
when its request ends is asked of no one: before, each queued image went
on to `serve` with a dead context, and one canceled request put a row for each
image on the Routing page in a few ms (Pkh: 63 in ~60ms).
A description's `serve` runs on its request's context, so its route is
noted on that request's `inflight` (`noteRoute`) and stands in for it on
the Routing page while it waits; when the images can't be described,
the request is given a route of its own, ended 499 when its agent
canceled it and 502 else (`notDescribed`), and its usage record names
it. One magpie answered for, held too long (`giveUp`), keeps the route
that showed it. A routing group's request, routed already, ends 499 too
when its agent canceled it.
Covered by `TestSameImageDescribedOnceWhateverDescribesIt`,
`TestOneRequestGoneLeavesTheDescriptionToAnother`,
`TestCanceledRequestAsksNoMoreDescriptions` and
`TestCanceledWhileDescribingKeepsItsRoute`
([`vision_dedupe_test.go`](../../internal/gateway/vision_dedupe_test.go)).
## Image recognition as an MCP server
`VisionMCPPath`, `/mcp/magpie/vision`, serves the model that describes
+9 -2
View File
@@ -1948,7 +1948,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// (a lane refusal, which returns to serve's end) does not call
// turnedAway and record twice.
logged := func() {
rec := usage.Record{Time: start, Agent: call.Agent, Via: call.Via, Provider: call.Provider, Model: call.Model, Requested: call.Model,
rec := usage.Record{RouteID: call.Route, Time: start, Agent: call.Agent, Via: call.Via, Provider: call.Provider, Model: call.Model, Requested: call.Model,
Millis: call.Millis, Status: call.Status, Rejected: true, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind, Endpoint: endpointOf(r, from, "", provider.Provider{}, ""), Archive: call.archiveName()}
failedWith(&rec, call.Status, call.Error, "")
withBodies(&rec, &call)
@@ -2330,6 +2330,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
seen, err := s.seenBody(withDescribeFor(r.Context(), call.Agent, call.Model, sessionOf(r.Header), unknownSight), from, body, see)
if err != nil {
call.Status, call.Error = 502, "image not described"
if r.Context().Err() != nil {
call.Status, call.Error = canceled(r.Context())
}
s.notDescribed(r, &call, start)
writeError(w, from, 502, fmt.Sprintf("model %q can't see images, and %s couldn't describe the image for it: %v%s%s", call.Model, see, err, missingSeerNote(), autoSeerNote(see)))
turnedAway()
return
@@ -2935,7 +2939,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
}
see, _ := seeing()
call.Status = 502
failTo(w, kept, from, 502, fmt.Sprintf("model %q can't see images, and %s couldn't describe the image for it: %v%s%s", c.p.ID+"/"+c.model, see, err, missingSeerNote(), autoSeerNote(see)))
if r.Context().Err() != nil {
call.Status, call.Error = canceled(r.Context())
}
failTo(w, kept, from, call.Status, fmt.Sprintf("model %q can't see images, and %s couldn't describe the image for it: %v%s%s", c.p.ID+"/"+c.model, see, err, missingSeerNote(), autoSeerNote(see)))
break
}
attemptBody = b
+2 -11
View File
@@ -2,8 +2,6 @@ package gateway
import (
"context"
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"net/http/httptest"
@@ -297,19 +295,12 @@ func TestUnroutedSlotWaitNotCutOff(t *testing.T) {
// returned, closed to let it go with text.
func heldSight(t *testing.T, s *Server) (release func(text string)) {
t.Helper()
model, ok := seer()
if !ok {
if _, ok := seer(); !ok {
t.Fatal("no model to describe images with")
}
sum := sha256.Sum256([]byte(model + "\x00" + visionEffort(model) + "\x00" + "data:image/png;base64,aGVsbG8="))
key := hex.EncodeToString(sum[:])
e := &sight{done: make(chan struct{})}
s.sightMu.Lock()
if s.sights == nil {
s.sights = map[string]*sight{}
}
s.sights[key] = e
s.sightOrder = append(s.sightOrder, key)
s.keepSightLocked(sightKey("data:image/png;base64,aGVsbG8="), e)
s.sightMu.Unlock()
closed := false
t.Cleanup(func() {
+194 -51
View File
@@ -3,6 +3,7 @@ package gateway
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
@@ -346,6 +347,49 @@ type sight struct {
text string
by string // the model that described it: model, or one in its place
err error
// waiting is how many requests wait on it now, and stop ends the
// work of describing it: the last of them to go stops it (sightMu)
waiting int
stop context.CancelFunc
}
// sightKey is what a description is kept under: the image's own bytes,
// as an inline image's data URL carries them, or the address it is at,
// and the level picked in Settings to describe images at. The same
// picture is described once, whichever request, protocol or data URL's
// type sends it, and whichever model describes it; a level picked since
// reads it again.
func sightKey(src string) string {
h := sha256.New()
h.Write([]byte(provider.HeldSettings().VisionEffort + "\x00"))
if b, ok := dataURLBytes(src); ok {
h.Write([]byte("bytes\x00"))
h.Write(b)
} else {
h.Write([]byte("src\x00"))
h.Write([]byte(src))
}
return hex.EncodeToString(h.Sum(nil))
}
// dataURLBytes is the bytes of a base64 data URL, false for anything else.
func dataURLBytes(src string) ([]byte, bool) {
rest, ok := strings.CutPrefix(src, "data:")
if !ok {
return nil, false
}
meta, data, ok := strings.Cut(rest, ",")
if !ok || !strings.HasSuffix(strings.ToLower(meta), ";base64") {
return nil, false
}
// strictly: text that only decodes loosely to the same bytes is
// another image's, as far as is known
for _, enc := range []*base64.Encoding{base64.StdEncoding.Strict(), base64.RawStdEncoding.Strict(), base64.URLEncoding.Strict(), base64.RawURLEncoding.Strict()} {
if b, err := enc.DecodeString(data); err == nil {
return b, true
}
}
return nil, false
}
// describe is what model says of the image at src, asked once for each
@@ -354,56 +398,135 @@ type sight struct {
// described it: model, or the next that sees when model couldn't
// (describeWith).
//
// A description is kept under model, whichever described it: the image
// sent again on the next turn isn't asked of anyone, while a new image is
// asked of model first again, so a pick that failed once is tried on each
// new image and not given up for good (kelvinjason11 on X).
// A description is kept under the image (sightKey), not the model that
// was asked: Pkh on Discord had AutoVision's pick change between turns,
// and every image of a long conversation was described again, one
// request sending 63 descriptions at once. A new image is asked of
// model first again, so a pick that failed once is tried on each new
// image and not given up for good (kelvinjason11 on X).
//
// The description is the work of no one request: one that goes away
// leaves it to the others waiting on it, and the last to go stops it
// and leaves nothing behind, so the next asks again. Only a failure of
// the describing itself is handed to those waiting; it isn't kept.
func (s *Server) describe(ctx context.Context, model, src string) (text, by string, err error) {
// a level picked since is asked again, not given what was said at the last
sum := sha256.Sum256([]byte(model + "\x00" + visionEffort(model) + "\x00" + src))
key := hex.EncodeToString(sum[:])
return s.describeKeyed(ctx, model, src, sightKey(src))
}
func (s *Server) describeKeyed(ctx context.Context, model, src, key string) (text, by string, err error) {
if err := ctx.Err(); err != nil {
return "", model, err
}
s.sightMu.Lock()
if e, ok := s.sights[key]; ok {
e, ok := s.sights[key]
if ok {
// used again, so the last to go: a long conversation's first
// images, still sent every turn, outlast those of conversations
// that have ended
if i := slices.Index(s.sightOrder, key); i >= 0 {
s.sightOrder = append(append(s.sightOrder[:i:i], s.sightOrder[i+1:]...), key)
}
s.sightMu.Unlock()
select {
case <-e.done:
by := e.by
if by == "" {
by = model
}
return e.text, by, e.err
case <-ctx.Done():
return "", model, ctx.Err()
}
} else {
work, stop := context.WithCancel(context.WithoutCancel(ctx))
e = &sight{done: make(chan struct{}), stop: stop}
s.keepSightLocked(key, e)
go s.see(work, e, model, src, key)
}
e.waiting++
s.sightMu.Unlock()
select {
case <-e.done:
s.sightMu.Lock()
e.waiting--
s.sightMu.Unlock()
if e.by == "" {
return e.text, model, e.err
}
return e.text, e.by, e.err
case <-ctx.Done():
s.sightMu.Lock()
if e.waiting--; e.waiting == 0 {
select {
case <-e.done:
default:
// no one waits for it now: it stops, and the next to send
// the image asks again
s.forgetSightLocked(key, e)
if e.stop != nil {
e.stop()
}
}
}
s.sightMu.Unlock()
return "", model, ctx.Err()
}
}
// see describes the image for e, on work, which ends when no one waits.
func (s *Server) see(work context.Context, e *sight, model, src, key string) {
text, by, err := s.describeWith(work, model, src, visionSystem, "Describe this image.")
s.sightMu.Lock()
e.text, e.by, e.err = text, by, err
switch {
case err != nil:
// a failure isn't kept: the next request asks again
s.forgetSightLocked(key, e)
case s.sights[key] == nil:
// answered as the last to wait went: kept for the next
s.keepSightLocked(key, e)
}
close(e.done)
s.sightMu.Unlock()
e.stop()
}
// keepSightLocked keeps e under key, the most recently used, and lets
// the least recently used go past sightsKept; sightMu is held.
func (s *Server) keepSightLocked(key string, e *sight) {
if s.sights == nil {
s.sights = map[string]*sight{}
}
e := &sight{done: make(chan struct{})}
s.sights[key] = e
s.sightOrder = append(s.sightOrder, key)
for len(s.sightOrder) > sightsKept {
delete(s.sights, s.sightOrder[0])
s.sightOrder = s.sightOrder[1:]
}
s.sightMu.Unlock()
e.text, e.by, e.err = s.describeWith(ctx, model, src, visionSystem, "Describe this image.")
if e.err != nil {
// a failure isn't kept: the next request asks again
s.sightMu.Lock()
if s.sights[key] == e {
delete(s.sights, key)
}
s.sightMu.Unlock()
}
// forgetSightLocked takes e, kept under key, out of the cache; sightMu is
// held.
func (s *Server) forgetSightLocked(key string, e *sight) {
if s.sights[key] != e {
return
}
close(e.done)
return e.text, e.by, e.err
delete(s.sights, key)
if i := slices.Index(s.sightOrder, key); i >= 0 {
s.sightOrder = slices.Delete(s.sightOrder, i, i+1)
}
}
// notDescribed puts on the Routing page a request whose images weren't
// described before it was routed: call says why. Its describers' rows
// stood in for it while it waited (noteRoute), and without this it had
// none of its own once it ended (Pkh on Discord: only "Image
// description" rows, the request they were for gone). One magpie
// answered for, held too long (giveUp), has its own already.
func (s *Server) notDescribed(r *http.Request, call *Call, start time.Time) {
if f := inflightOf(r.Context()); f != nil {
f.mu.Lock()
answered := f.unrouted != nil && f.unrouted.ended
f.mu.Unlock()
if answered {
return
}
}
rt := s.trace.beginFor(r, Route{Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Kind: call.Kind, For: call.For, Model: call.Model, Provider: "magpie"})
ms := time.Since(start).Milliseconds()
s.trace.update(rt, func(t *Route) {
t.Done, t.Status, t.Error, t.Millis = true, call.Status, call.Error, ms
})
call.Route = rt.ID
}
// visionTries is how many models are asked about one image, the first
@@ -548,12 +671,6 @@ func (s *Server) askVisionWith(ctx context.Context, model, src, system, text str
}
w := httptest.NewRecorder()
s.serve(w, r, provider.Chat, body)
if t, ok := sideTimeout(ctx); ok {
return "", t
}
if ctx.Err() != nil {
return "", ctx.Err()
}
var out struct {
Choices []struct {
Message struct {
@@ -564,7 +681,21 @@ func (s *Server) askVisionWith(ctx context.Context, model, src, system, text str
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
parsed := json.Unmarshal(w.Body.Bytes(), &out) == nil
if parsed && w.Code < 300 && out.Error == nil && len(out.Choices) > 0 {
if said := strings.TrimSpace(out.Choices[0].Message.Content); said != "" {
// a description that came whole is kept, though what asked
// for it ended as it came: it was paid for
return said, nil
}
}
if t, ok := sideTimeout(ctx); ok {
return "", t
}
if ctx.Err() != nil {
return "", ctx.Err()
}
if !parsed {
return "", fmt.Errorf("%d, not an answer", w.Code)
}
if w.Code >= 300 || out.Error != nil {
@@ -574,10 +705,7 @@ func (s *Server) askVisionWith(ctx context.Context, model, src, system, text str
}
return "", errors.New(msg)
}
if len(out.Choices) == 0 || strings.TrimSpace(out.Choices[0].Message.Content) == "" {
return "", errors.New("no description")
}
return strings.TrimSpace(out.Choices[0].Message.Content), nil
return "", errors.New("no description")
}
// seenBody is the body with each of its images described by model in its
@@ -588,12 +716,21 @@ func (s *Server) seenBody(ctx context.Context, proto provider.Protocol, body []b
// the images described before a route is begun: a wait magpie knows
// of (unrouted.go)
defer noteWait(ctx, "image description")()
var srcs []string
// each picture once, however many times and however it is sent
keyOf := map[string]string{}
var keys, srcs []string
have := map[string]bool{}
walkImages(proto, body, func(im imageAt) (json.RawMessage, error) {
if im.Src != "" && !have[im.Src] {
have[im.Src] = true
srcs = append(srcs, im.Src)
if im.Src == "" {
return nil, nil
}
if _, ok := keyOf[im.Src]; !ok {
k := sightKey(im.Src)
keyOf[im.Src] = k
if !have[k] {
have[k] = true
keys, srcs = append(keys, k), append(srcs, im.Src)
}
}
return nil, nil
})
@@ -608,16 +745,22 @@ func (s *Server) seenBody(ctx context.Context, proto provider.Protocol, body []b
wg.Add(1)
go func() {
defer wg.Done()
slots <- struct{}{}
// one waiting for a slot when the request ends asks no one
select {
case slots <- struct{}{}:
case <-ctx.Done():
results[i] = result{by: model, err: ctx.Err()}
return
}
defer func() { <-slots }()
text, by, err := s.describe(ctx, model, src)
text, by, err := s.describeKeyed(ctx, model, src, keys[i])
results[i] = result{text, by, err}
}()
}
wg.Wait()
of := map[string]result{}
for i, src := range srcs {
of[src] = results[i]
for i, k := range keys {
of[k] = results[i]
}
return walkImages(proto, body, func(im imageAt) (json.RawMessage, error) {
if im.Src == "" {
@@ -626,7 +769,7 @@ func (s *Server) seenBody(ctx context.Context, proto provider.Protocol, body []b
}
return textBlock(proto, imageOmitted), nil
}
r := of[im.Src]
r := of[keyOf[im.Src]]
if r.err != nil {
if im.Current() {
return nil, r.err
+254
View File
@@ -0,0 +1,254 @@
package gateway
import (
"context"
"encoding/base64"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// gatedEye is eyeUp with each description held until gate is closed or
// its request ends; asked counts the descriptions asked for, and arrived
// says each one has come.
type gatedEye struct {
eyeUp
mu sync.Mutex
asked int
arrived chan struct{}
gate chan struct{}
open func() // closes gate, once
}
func (u *gatedEye) ServeHTTP(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
if strings.HasSuffix(modelOf(body), "eye") {
u.mu.Lock()
u.asked++
u.mu.Unlock()
u.arrived <- struct{}{}
select {
case <-u.gate:
case <-r.Context().Done():
return
}
}
r.Body = io.NopCloser(strings.NewReader(string(body)))
u.eyeUp.ServeHTTP(w, r)
}
func (u *gatedEye) count() int {
u.mu.Lock()
defer u.mu.Unlock()
return u.asked
}
// gateEyed is eyed with every description held at the gate.
func gateEyed(t *testing.T) (*Server, *gatedEye) {
t.Helper()
fresh(t)
u := &gatedEye{arrived: make(chan struct{}, 256), gate: make(chan struct{})}
up := httptest.NewServer(u)
var once sync.Once
u.open = func() { once.Do(func() { close(u.gate) }) }
t.Cleanup(func() {
u.open()
up.Close()
})
if err := provider.Save(provider.Provider{ID: "probe", Name: "Probe", Chat: up.URL + "/v1", Key: "key", Models: []string{"text", "eye"}}); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("probe", up.URL+"/v1", []catalog.Model{
{ID: "text", ImageInput: imageInputBool(false)},
{ID: "eye", Images: true, ImageInput: imageInputBool(true)},
}); err != nil {
t.Fatal(err)
}
return New(), u
}
// arrive waits for n descriptions to be asked for.
func (u *gatedEye) arrive(t *testing.T, n int) {
t.Helper()
for i := range n {
select {
case <-u.arrived:
case <-time.After(10 * time.Second):
t.Fatalf("only %d of %d descriptions were asked for", i, n)
}
}
}
// imagesBody is a Chat request to probe/text with n images, each its own.
func imagesBody(n int) string {
var parts []string
for i := range n {
data := base64.StdEncoding.EncodeToString(fmt.Appendf(nil, "picture %d", i))
parts = append(parts, `{"type":"image_url","image_url":{"url":"data:image/png;base64,`+data+`"}}`)
}
return `{"model":"probe/text","messages":[{"role":"user","content":[{"type":"text","text":"read"},` + strings.Join(parts, ",") + `]}]}`
}
// sightWaiters is how many requests wait on the description of src.
func sightWaiters(s *Server, src string) int {
s.sightMu.Lock()
defer s.sightMu.Unlock()
if e := s.sights[sightKey(src)]; e != nil {
return e.waiting
}
return 0
}
// servedOn answers body, posted to path on ctx, on the channel it returns.
func servedOn(s *Server, ctx context.Context, path, body string) <-chan *httptest.ResponseRecorder {
done := make(chan *httptest.ResponseRecorder, 1)
go func() {
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)).WithContext(ctx))
done <- rec
}()
return done
}
func recorded(t *testing.T, done <-chan *httptest.ResponseRecorder) *httptest.ResponseRecorder {
t.Helper()
select {
case rec := <-done:
return rec
case <-time.After(15 * time.Second):
t.Fatal("the request was never answered")
}
return nil
}
// Pkh on Discord: AutoVision's pick changed between turns, and every image
// in the conversation was described again by the new one. A description is
// kept under the image's bytes: the same picture, sent on another
// protocol, under another type, with another model picked to describe it,
// isn't described again.
func TestSameImageDescribedOnceWhateverDescribesIt(t *testing.T) {
s, u := eyed(t)
code, body := postAs(t, s, "", pastedImage)
if code != 200 {
t.Fatalf("first turn: %d %s", code, body)
}
// another model that sees, now picked to describe images
other := &eyeUp{}
srv := httptest.NewServer(other)
t.Cleanup(srv.Close)
if err := provider.Save(provider.Provider{ID: "other", Name: "Other", Chat: srv.URL + "/v1", Key: "key", Models: []string{"bigeye"}}); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("other", srv.URL+"/v1", []catalog.Model{{ID: "bigeye", Images: true, ImageInput: imageInputBool(true)}}); err != nil {
t.Fatal(err)
}
st := settings.Load()
st.Vision = "other/bigeye"
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
// the same bytes, on Messages, called a JPEG
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(`{"model":"probe/text","max_tokens":16,"messages":[{"role":"user","content":[{"type":"text","text":"read"},{"type":"image","source":{"type":"base64","media_type":"image/jpeg","data":"aGVsbG8="}}]}]}`)))
if rec.Code != 200 {
t.Fatalf("second turn: %d %s", rec.Code, rec.Body.String())
}
if n := len(other.sent("bigeye")); n != 0 {
t.Fatalf("the image, described already, was described again by the new pick (%d times)", n)
}
if n := len(u.sent("eye")); n != 1 {
t.Fatalf("the image was described %d times", n)
}
got := u.sent("text")
if len(got) != 2 || !strings.Contains(got[1], "HELLO") {
t.Fatalf("the second turn wasn't given the kept description: %v", got)
}
}
// One request's agent canceling it doesn't fail the description another
// request waits on: the description is no one request's, and the next
// waiting is given it when it comes.
func TestOneRequestGoneLeavesTheDescriptionToAnother(t *testing.T) {
s, u := gateEyed(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
first := servedOn(s, ctx, "/v1/chat/completions", pastedImage)
u.arrive(t, 1)
second := servedOn(s, context.Background(), "/v1/chat/completions", pastedImage)
src := "data:image/png;base64,aGVsbG8="
deadline := time.Now().Add(10 * time.Second)
for sightWaiters(s, src) < 2 {
if time.Now().After(deadline) {
t.Fatalf("the second request never waited on the description (%d waiting)", sightWaiters(s, src))
}
time.Sleep(5 * time.Millisecond)
}
cancel()
recorded(t, first)
u.open()
rec := recorded(t, second)
if rec.Code != 200 {
t.Fatalf("the request still waiting: %d %s", rec.Code, rec.Body.String())
}
if got := u.sent("text"); len(got) != 1 || !strings.Contains(got[0], "HELLO") {
t.Fatalf("text model was sent %v", got)
}
if n := u.count(); n != 1 {
t.Fatalf("the image was asked about %d times", n)
}
}
// canceledWhileDescribing sends a request with ten images, cancels it once
// the first visionParallel are being described, and answers once it has
// returned.
func canceledWhileDescribing(t *testing.T) (*Server, *gatedEye) {
t.Helper()
s, u := gateEyed(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := servedOn(s, ctx, "/v1/chat/completions", imagesBody(10))
u.arrive(t, visionParallel)
cancel()
recorded(t, done)
return s, u
}
// Pkh on Discord: one canceled request went on to ask for 63 descriptions
// in 60ms, each its own row on the Routing page. The images still waiting
// for a slot when their request ends are asked of no one, and those being
// described stop with no one left waiting on them.
func TestCanceledRequestAsksNoMoreDescriptions(t *testing.T) {
s, u := canceledWhileDescribing(t)
if n := u.count(); n != visionParallel {
t.Fatalf("a canceled request asked for %d descriptions, want the %d under way", n, visionParallel)
}
if rs := routesOf(s, "probe/eye"); len(rs) != visionParallel {
t.Fatalf("a canceled request left %d description rows, want %d", len(rs), visionParallel)
}
s.sightMu.Lock()
left := len(s.sights)
s.sightMu.Unlock()
if left != 0 {
t.Fatalf("%d descriptions no one waits for were left in the cache", left)
}
}
// Pkh on Discord: the request whose images were being described had no row
// of its own on the Routing page once it was canceled, only its
// descriptions'. It has one, ended as the agent canceled it.
func TestCanceledWhileDescribingKeepsItsRoute(t *testing.T) {
s, _ := canceledWhileDescribing(t)
rs := routesOf(s, "probe/text")
if len(rs) != 1 || !rs[0].Done || rs[0].Status != 499 || !strings.Contains(rs[0].Error, "canceled") {
t.Fatalf("the canceled request's routes: %+v", rs)
}
}