diff --git a/docs/reference.md b/docs/reference.md index 29091cec4..34d01ed0c 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -3567,6 +3567,8 @@ The gateway and usage: page's history - `affinity.json` — which key or account answered each conversation, so a restart keeps it there while the vendor has it cached +- `vision-cache.jsonl` — successful inline-image descriptions reused after a + restart (0600); `vision-cache.jsonl.lock` serializes writers during handover - `served.json` — when each account and key last answered - `quotas.json` — the last allowance each account reported - `quota-history.json`, `balance-history.json` — allowance and balance diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index f5cec6949..42574e14f 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -1680,6 +1680,23 @@ asks no other. 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. +- Completed descriptions of inline images are also appended to + `vision-cache.jsonl` in magpie's config directory before their waiters + are released (`saveSight`), and restored by `New`. A restart or update + therefore doesn't describe a conversation's history again. Only inline + images are persisted: their keys come from their bytes, while a URL can + later name different bytes and stays process-local. The private (0600) + file keeps the same 2048-entry LRU on reload; a JSON-malformed or + crash-truncated record is skipped without hiding the other records, and + is copied to a private `.broken-*` file before a later compaction drops + it. An inline description is counted from its creation until it has saved + or failed; gateway shutdown waits for that count to reach zero, so a + canceled request's completed description isn't lost on exit. Appends and compaction + are serialized across gateway processes by `vision-cache.jsonl.lock`; + compaction rereads the latest file under that lock before atomically + replacing it, so a handover can't overwrite another gateway's new record. + A lock or disk-write failure only loses the persistence optimization, + never a description that already succeeded. 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 @@ -1706,6 +1723,9 @@ 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). +Once the model has answered, `sight.answered` also keeps cancellation from +stopping the save: a completed inline description is written before its +waiters are released, even if the last waiter left during that write. 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 @@ -1726,6 +1746,10 @@ Covered by `TestSameImageDescribedOnceWhateverDescribesIt`, `TestCanceledRequestAsksNoMoreDescriptions` and `TestCanceledWhileDescribingKeepsItsRoute` ([`vision_dedupe_test.go`](../../internal/gateway/vision_dedupe_test.go)). +Restart reuse, cancellation during a save, failed writes, truncated records, +cross-Server compaction, duplicate records, the LRU and URL behavior are +covered by `TestDescriptionSurvivesGatewayRestart` and +[`vision_cache_test.go`](../../internal/gateway/vision_cache_test.go). ## Image recognition as an MCP server diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 26abf4035..077e3f3d7 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -527,10 +527,18 @@ type Server struct { sockets clientSockets // what it serves other computers TLS with, nil without (tls.go) tls *tls.Config - // the images described for models that can't see them (vision.go) - sightMu sync.Mutex - sights map[string]*sight - sightOrder []string + // the images described for models that can't see them (vision.go); + // completed inline descriptions also survive a restart (vision_cache.go) + sightMu sync.Mutex + sights map[string]*sight + sightOrder []string + sightFile string + sightDiskLines int + // inline descriptions that may still have to save, from their creation + // until see has saved or given up; a shutdown lets the count reach zero + sightSaveMu sync.Mutex + sightSaving int + sightSavesIdle chan struct{} // closed while none may save // blind are the models that turned an image away while this server // ran, by "/" (refuseSight): kept for the run alone, // so a vendor that adds sight is asked again after a restart @@ -558,7 +566,7 @@ type Server struct { // New makes a gateway. func New() *Server { redact.SetKeyPath(filepath.Join(settings.Dir(), "redact.key")) - return &Server{ + s := &Server{ // a request counted against a MaxRPM waits for room in its minute // first (rpm.go); the ChatGPT backend is spoken to over HTTP/1.1 // (netproxy.HTTP1, which provider/codex_http1.go sets) @@ -566,7 +574,10 @@ func New() *Server { unfit: make(map[string]bool), subscription: newSubscriptionBridge(), debug: os.Getenv("MAGPIE_DEBUG") != "", + sightFile: sightsPath(), } + s.loadSights() + return s } // Recent lists the last calls, newest first. @@ -868,6 +879,12 @@ func (s *Server) ListenAndServe(ctx context.Context) error { log.Printf("gateway: ending after %s with requests still in flight; they are cut (%v)", s.drainFor(), err) } <-sockets + // An inline description may still have to save after its request + // ended, or was canceled: wait for every such description to save or + // give up, rather than have the next start describe the images again. + if !s.waitSightSaves(c) { + log.Printf("gateway: ending before image descriptions could all be saved; the next start may describe them again") + } s.subscription.abortAll() provider.FlushServed() // what answered last, kept for the next start and the CLI flushSticks() // who answered which conversation, for the next start or the magpie handed over to diff --git a/internal/gateway/vision.go b/internal/gateway/vision.go index 0e7b51fba..20a00985b 100644 --- a/internal/gateway/vision.go +++ b/internal/gateway/vision.go @@ -349,6 +349,10 @@ type sight struct { text string by string // the model that described it: model, or one in its place err error + // answered means the model call is over, even while a successful inline + // description is still being saved. Cancellation must not stop that save. + answered bool + persistent bool // inline bytes, never a URL whose contents can change // 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 @@ -430,9 +434,18 @@ func (s *Server) describeKeyed(ctx context.Context, model, src, key string) (tex } } else { work, stop := context.WithCancel(context.WithoutCancel(ctx)) - e = &sight{done: make(chan struct{}), stop: stop} + _, persistent := dataURLBytes(src) + e = &sight{done: make(chan struct{}), stop: stop, persistent: persistent} s.keepSightLocked(key, e) - go s.see(work, e, model, src, key) + if persistent { + s.beginSightSave() + } + go func() { + if persistent { + defer s.endSightSave() + } + s.see(work, e, model, src, key) + }() } e.waiting++ s.sightMu.Unlock() @@ -447,12 +460,14 @@ func (s *Server) describeKeyed(ctx context.Context, model, src, key string) (tex return e.text, e.by, e.err case <-ctx.Done(): s.sightMu.Lock() - if e.waiting--; e.waiting == 0 { + e.waiting-- + answered := e.answered + if e.waiting == 0 && !answered { select { case <-e.done: default: - // no one waits for it now: it stops, and the next to send - // the image asks again + // no one waits for work still in the model: it stops, and the + // next to send the image asks again s.forgetSightLocked(key, e) if e.stop != nil { e.stop() @@ -460,6 +475,12 @@ func (s *Server) describeKeyed(ctx context.Context, model, src, key string) (tex } } s.sightMu.Unlock() + if answered { + // The model has answered: let its successful description finish + // saving before the request returns, so an immediate restart or + // handover can't read an older cache. + <-e.done + } return "", model, ctx.Err() } } @@ -469,12 +490,23 @@ 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: + e.answered = true + if 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.sightMu.Unlock() + + if err == nil && e.persistent { + // Persist before releasing the waiters: an immediate restart must + // find this description. A write failure only loses that saving. + s.saveSight(key, text, by) + } + + s.sightMu.Lock() + if err == nil && s.sights[key] == nil { + // answered as the last to wait went (or while it was being saved): + // kept for the next, as before s.keepSightLocked(key, e) } close(e.done) diff --git a/internal/gateway/vision_cache.go b/internal/gateway/vision_cache.go new file mode 100644 index 000000000..90f3eb3e3 --- /dev/null +++ b/internal/gateway/vision_cache.go @@ -0,0 +1,259 @@ +package gateway + +// Completed image descriptions are kept next to the rest of magpie's +// settings, so restarting or updating the gateway doesn't describe every +// image in an ongoing conversation again. Only inline images are saved: +// their cache key comes from their bytes. A URL is left to the in-memory +// cache because the bytes it points at can change. + +import ( + "bytes" + "context" + "encoding/hex" + "encoding/json" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/filelock" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/steady" +) + +const ( + sightCacheVersion = 2 + sightKindInline = "inline" + sightsCompactAfter = 2 * sightsKept +) + +// sightsSaving orders writers in this process; the file lock below orders +// writers across a handover. The lock file is never the descriptions file. +var sightsSaving sync.Mutex + +// savedSight is one completed description in vision-cache.jsonl. Version is +// the on-disk format and the description contract. Kind is explicit so a URL +// can never be revived as a content-addressed image by a later compaction. +type savedSight struct { + Version int `json:"version"` + Kind string `json:"kind"` + Key string `json:"key"` + Text string `json:"text"` + By string `json:"by"` +} + +func sightsPath() string { return filepath.Join(settings.Dir(), "vision-cache.jsonl") } + +func validSavedSight(v savedSight) bool { + key, err := hex.DecodeString(v.Key) + return v.Version == sightCacheVersion && v.Kind == sightKindInline && err == nil && len(key) == 32 && + hex.EncodeToString(key) == v.Key && strings.TrimSpace(v.Text) != "" && strings.TrimSpace(v.By) != "" +} + +// readSavedSights reads the valid records, newest occurrence winning a +// duplicate key, and returns them oldest to newest with the LRU cap applied. +// A malformed line is reported separately from an invalid record: loading can +// skip it, but compaction must not treat an unreadable file as an empty one. +func readSavedSights(path string) (records []savedSight, lines int, malformed bool, err error) { + b, err := steady.ReadFile(path) + if err != nil { + return nil, 0, false, err + } + latest := map[string]savedSight{} + last := map[string]int{} + seq := 0 + for _, line := range bytes.Split(b, []byte{'\n'}) { + if len(bytes.TrimSpace(line)) == 0 { + continue + } + lines++ + var v savedSight + if json.Unmarshal(line, &v) != nil { + malformed = true + continue + } + if !validSavedSight(v) { + continue + } + seq++ + latest[v.Key] = v + last[v.Key] = seq + } + for _, v := range latest { + records = append(records, v) + } + sort.Slice(records, func(i, j int) bool { return last[records[i].Key] < last[records[j].Key] }) + if len(records) > sightsKept { + records = records[len(records)-sightsKept:] + } + return records, lines, malformed, nil +} + +// loadSights restores completed inline descriptions. Each line is independent: +// a crash-truncated tail doesn't hide the records before it. New doesn't write +// or compact, so a starting gateway can't erase another gateway's new append. +func (s *Server) loadSights() { + records, lines, _, err := readSavedSights(s.sightFile) + if err != nil { + return + } + s.sightDiskLines = lines + _ = os.Chmod(s.sightFile, 0o600) + for _, v := range records { + done := make(chan struct{}) + close(done) + s.keepSightLocked(v.Key, &sight{done: done, text: v.Text, by: v.By, answered: true, persistent: true}) + } +} + +// beginSightSave counts an inline description that may still have to be +// written: from its creation, before the model is called, until see has +// saved it or failed. Counting from creation closes the window where the +// model has answered but see hasn't published answered yet, so a canceled +// request may return before its save but shutdown still waits for it. +func (s *Server) beginSightSave() { + s.sightSaveMu.Lock() + if s.sightSaving == 0 { + s.sightSavesIdle = make(chan struct{}) + } + s.sightSaving++ + s.sightSaveMu.Unlock() +} + +func (s *Server) endSightSave() { + s.sightSaveMu.Lock() + s.sightSaving-- + if s.sightSaving == 0 && s.sightSavesIdle != nil { + close(s.sightSavesIdle) + } + s.sightSaveMu.Unlock() +} + +// waitSightSaves waits until no inline description can still save, or ctx +// ends. A nil channel means none has begun since the last one ended. +func (s *Server) waitSightSaves(ctx context.Context) bool { + s.sightSaveMu.Lock() + idle := s.sightSavesIdle + s.sightSaveMu.Unlock() + if idle == nil { + return true + } + select { + case <-idle: + return true + case <-ctx.Done(): + return false + } +} + +// saveSight appends a completed description before its waiters are released. +// A lock or disk failure only loses persistence, never the successful answer. +// Compaction runs after the append and rereads the latest file under the same +// cross-process lock, so another Server's completed record can't be overwritten. +func (s *Server) saveSight(key, text, by string) { + v := savedSight{Version: sightCacheVersion, Kind: sightKindInline, Key: key, Text: text, By: by} + if !validSavedSight(v) { + return + } + line, err := json.Marshal(v) + if err != nil { + return + } + sightsSaving.Lock() + defer sightsSaving.Unlock() + unlock, held := filelock.Lock(s.sightFile+".lock", filelock.Wait) + defer unlock() + if !held { + return + } + if s.appendSightLocked(line) != nil { + return + } + s.sightDiskLines++ + if s.sightDiskLines >= sightsCompactAfter { + s.compactSightsLocked() + } +} + +func (s *Server) appendSightLocked(line []byte) error { + path := s.sightFile + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0o600) + if err != nil { + return err + } + defer f.Close() + if err := f.Chmod(0o600); err != nil { + return err + } + // Another writer, or a crash after a partial write, may have changed the + // tail since this Server loaded it. Check the actual last byte every time. + if st, err := f.Stat(); err != nil { + return err + } else if st.Size() > 0 { + last := []byte{0} + if _, err := f.ReadAt(last, st.Size()-1); err != nil { + return err + } + if last[0] != '\n' { + line = append([]byte{'\n'}, line...) + } + } + line = append(line, '\n') + _, err = f.Write(line) + return err +} + +// compactSightsLocked rewrites the newest valid records already on disk, not +// this Server's in-memory snapshot. sightsSaving and the file lock are held; +// no sightMu is needed, and URL or in-flight memory entries can't leak here. +func (s *Server) compactSightsLocked() { + path := s.sightFile + records, _, malformed, err := readSavedSights(path) + if err != nil { + return + } + if malformed && !s.preserveMalformedSights(path) { + // An unreadable line stays readable evidence rather than being erased + // by a compaction that couldn't preserve it first. + return + } + var out bytes.Buffer + for _, v := range records { + line, err := json.Marshal(v) + if err != nil { + return + } + out.Write(line) + out.WriteByte('\n') + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return + } + target, err := edit.Target(path) + if err != nil { + return + } + if steady.WriteFile(target, out.Bytes(), 0o600) != nil { + return + } + s.sightDiskLines = len(records) +} + +// preserveMalformedSights copies a file whose malformed line compaction is +// about to drop, so a crash-truncated or hand-edited cache can be inspected +// and the valid records can still be compacted instead of growing forever. +func (s *Server) preserveMalformedSights(path string) bool { + b, err := steady.ReadFile(path) + if err != nil { + return false + } + backup := path + ".broken-" + strconv.FormatInt(time.Now().UnixNano(), 10) + return steady.WriteFile(backup, b, 0o600) == nil +} diff --git a/internal/gateway/vision_cache_test.go b/internal/gateway/vision_cache_test.go new file mode 100644 index 000000000..be4081549 --- /dev/null +++ b/internal/gateway/vision_cache_test.go @@ -0,0 +1,313 @@ +package gateway + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestFailedDescriptionIsNotSaved(t *testing.T) { + s, u := eyed(t) + u.fail = true + if code, got := postAs(t, s, "", imagesBody(1)); code != 502 { + t.Fatalf("failed description: %d %s, want 502", code, got) + } + if _, err := os.Stat(s.sightFile); !os.IsNotExist(err) { + t.Fatalf("a failed description was written: %v", err) + } + + before := len(u.sent("eye")) + u.mu.Lock() + u.fail = false + u.mu.Unlock() + restarted := New() + if code, got := postAs(t, restarted, "", imagesBody(1)); code != 200 { + t.Fatalf("after the describer recovers: %d %s", code, got) + } + if n := len(u.sent("eye")); n != before+1 { + t.Fatalf("the failure was cached: %d descriptions, want one fresh one after the original %d", n, before) + } +} + +func TestRestartReadsCacheBeforeATruncatedRecord(t *testing.T) { + s, u := eyed(t) + if code, got := postAs(t, s, "", imagesBody(1)); code != 200 { + t.Fatalf("before restart: %d %s", code, got) + } + f, err := os.OpenFile(s.sightFile, os.O_WRONLY|os.O_APPEND, 0) + if err != nil { + t.Fatal(err) + } + if _, err := f.WriteString(`{"version":1,"key":"truncated`); err != nil { + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + + restarted := New() + if code, got := postAs(t, restarted, "", imagesBody(1)); code != 200 { + t.Fatalf("after restart: %d %s", code, got) + } + if n := len(u.sent("eye")); n != 1 { + t.Fatalf("a truncated tail hid the good records: %d descriptions, want 1", n) + } +} + +func TestTruncatedRecordDoesNotBlockCompaction(t *testing.T) { + fresh(t) + s := New() + key1 := fmt.Sprintf("%064x", 31) + key2 := fmt.Sprintf("%064x", 32) + s.saveSight(key1, "before the crash", "probe/eye") + f, err := os.OpenFile(s.sightFile, os.O_WRONLY|os.O_APPEND, 0) + if err != nil { + t.Fatal(err) + } + if _, err := f.WriteString(`{"version":2,"kind":"inline","key":"truncated`); err != nil { + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + s.sightDiskLines = sightsCompactAfter + s.saveSight(key2, "after the crash", "probe/eye") + + records, _, malformed, err := readSavedSights(s.sightFile) + if err != nil || malformed || len(records) != 2 { + t.Fatalf("compaction kept a malformed line: %d records, malformed=%v, err=%v", len(records), malformed, err) + } + entries, err := os.ReadDir(filepath.Dir(s.sightFile)) + if err != nil { + t.Fatal(err) + } + backedUp := false + for _, entry := range entries { + if strings.HasPrefix(entry.Name(), filepath.Base(s.sightFile)+".broken-") { + backedUp = true + } + } + if !backedUp { + t.Fatal("the malformed file wasn't preserved before compaction") + } + restarted := New() + restarted.sightMu.Lock() + defer restarted.sightMu.Unlock() + if restarted.sights[key1] == nil || restarted.sights[key2] == nil { + t.Fatalf("valid records were lost: key1=%v key2=%v", restarted.sights[key1], restarted.sights[key2]) + } +} + +func TestSavedSightsReloadWithinCacheLimit(t *testing.T) { + fresh(t) + s := New() + for i := 1; i <= sightsKept+10; i++ { + s.saveSight(fmt.Sprintf("%064x", i), fmt.Sprintf("description %d", i), "probe/eye") + } + + restarted := New() + restarted.sightMu.Lock() + defer restarted.sightMu.Unlock() + if len(restarted.sights) != sightsKept || len(restarted.sightOrder) != sightsKept { + t.Fatalf("restored %d descriptions and %d order entries, want %d", len(restarted.sights), len(restarted.sightOrder), sightsKept) + } + for i := 1; i <= 10; i++ { + if restarted.sights[fmt.Sprintf("%064x", i)] != nil { + t.Fatalf("least recently used description %d survived the limit", i) + } + } + last := restarted.sights[fmt.Sprintf("%064x", sightsKept+10)] + if last == nil || last.text != fmt.Sprintf("description %d", sightsKept+10) || last.by != "probe/eye" { + t.Fatalf("the newest description wasn't restored: %+v", last) + } +} + +func TestSightFileCompactsWithoutDroppingNewest(t *testing.T) { + fresh(t) + s := New() + for i := 1; i <= sightsKept; i++ { + s.saveSight(fmt.Sprintf("%064x", i), fmt.Sprintf("description %d", i), "probe/eye") + } + s.sightDiskLines = sightsCompactAfter + extra := fmt.Sprintf("%064x", sightsKept+1) + s.saveSight(extra, "newest", "probe/eye") + + b, err := os.ReadFile(s.sightFile) + if err != nil { + t.Fatal(err) + } + lines := strings.Count(string(b), "\n") + if lines > sightsKept+1 { + t.Fatalf("compacted file has %d records, want at most %d", lines, sightsKept+1) + } + restarted := New() + restarted.sightMu.Lock() + defer restarted.sightMu.Unlock() + if len(restarted.sights) != sightsKept || restarted.sights[extra] == nil || restarted.sights[extra].text != "newest" { + t.Fatalf("compaction lost the newest description: %d restored, newest=%+v", len(restarted.sights), restarted.sights[extra]) + } +} + +func TestURLDescriptionStaysProcessLocal(t *testing.T) { + s, u := eyed(t) + body := `{"model":"probe/text","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"https://example.com/current.png"}}]}]}` + if code, got := postAs(t, s, "", body); code != 200 { + t.Fatalf("before restart: %d %s", code, got) + } + if _, err := os.Stat(s.sightFile); !os.IsNotExist(err) { + t.Fatalf("a URL-keyed description was persisted: %v", err) + } + if code, got := postAs(t, New(), "", body); code != 200 { + t.Fatalf("after restart: %d %s", code, got) + } + if n := len(u.sent("eye")); n != 2 { + t.Fatalf("a mutable URL reused an old description: %d descriptions, want 2", n) + } +} + +func TestURLDescriptionDoesNotLeakThroughCompaction(t *testing.T) { + s, u := eyed(t) + body := `{"model":"probe/text","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"https://example.com/changing.png"}}]}]}` + if code, got := postAs(t, s, "", body); code != 200 { + t.Fatalf("before compaction: %d %s", code, got) + } + s.sightDiskLines = sightsCompactAfter + s.saveSight(fmt.Sprintf("%064x", 42), "inline", "probe/eye") + + restarted := New() + if code, got := postAs(t, restarted, "", body); code != 200 { + t.Fatalf("after compaction and restart: %d %s", code, got) + } + if n := len(u.sent("eye")); n != 2 { + t.Fatalf("compaction persisted a URL: %d descriptions, want 2", n) + } +} + +func TestSightCompactionKeepsAnotherServersRecord(t *testing.T) { + fresh(t) + a, b := New(), New() + a.sightDiskLines = sightsCompactAfter + b.sightDiskLines = sightsCompactAfter + keyB := fmt.Sprintf("%064x", 51) + keyA := fmt.Sprintf("%064x", 52) + b.saveSight(keyB, "from B", "probe/eye") + a.saveSight(keyA, "from A", "probe/eye") + + restarted := New() + restarted.sightMu.Lock() + defer restarted.sightMu.Unlock() + if got := restarted.sights[keyB]; got == nil || got.text != "from B" { + t.Fatalf("A's compaction dropped B's completed description: %+v", got) + } + if got := restarted.sights[keyA]; got == nil || got.text != "from A" { + t.Fatalf("the compacting writer's own description is missing: %+v", got) + } +} + +func TestSightWriteFailureKeepsMemoryCache(t *testing.T) { + s, u := eyed(t) + if err := os.Mkdir(s.sightFile, 0o700); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if code, got := postAs(t, s, "", imagesBody(1)); code != 200 { + t.Fatalf("request %d with a broken cache file: %d %s", i+1, code, got) + } + } + if n := len(u.sent("eye")); n != 1 { + t.Fatalf("a disk failure also broke the memory cache: %d descriptions, want 1", n) + } +} + +func TestDuplicateSavedSightUsesNewest(t *testing.T) { + fresh(t) + s := New() + key := fmt.Sprintf("%064x", 77) + s.saveSight(key, "old", "probe/eye") + s.saveSight(key, "new", "other/bigeye") + restarted := New() + restarted.sightMu.Lock() + defer restarted.sightMu.Unlock() + if len(restarted.sights) != 1 || len(restarted.sightOrder) != 1 { + t.Fatalf("duplicate key restored %d entries and %d order rows", len(restarted.sights), len(restarted.sightOrder)) + } + if got := restarted.sights[key]; got == nil || got.text != "new" || got.by != "other/bigeye" { + t.Fatalf("newest duplicate didn't win: %+v", got) + } +} + +func TestCancelWhileSavingKeepsCompletedDescription(t *testing.T) { + s, u := eyed(t) + // Hold the writer before the model answers, then cancel after see has + // published its answered state but before the disk save can proceed. + sightsSaving.Lock() + locked := true + ctx, cancel := context.WithCancel(context.Background()) + defer func() { + cancel() + if locked { + sightsSaving.Unlock() + } + }() + done := servedOn(s, ctx, "/v1/chat/completions", imagesBody(1)) + key := sightKey("data:image/png;base64,cGljdHVyZSAw") + deadline := time.Now().Add(10 * time.Second) + for { + s.sightMu.Lock() + e := s.sights[key] + answered := e != nil && e.answered + s.sightMu.Unlock() + if answered { + break + } + if time.Now().After(deadline) { + t.Fatal("the model never completed its description") + } + time.Sleep(time.Millisecond) + } + cancel() + select { + case rec := <-done: + t.Fatalf("the request returned while its save was blocked: %d %s", rec.Code, rec.Body.String()) + case <-time.After(100 * time.Millisecond): + } + waitCtx, stopWait := context.WithTimeout(context.Background(), 50*time.Millisecond) + idle := s.waitSightSaves(waitCtx) + stopWait() + if idle { + t.Fatal("the pending-save barrier disappeared while the save was still blocked") + } + sightsSaving.Unlock() + locked = false + if rec := recorded(t, done); rec.Code < 400 { + t.Fatalf("canceled request: %d %s, want an error", rec.Code, rec.Body.String()) + } + if !s.waitSightSaves(context.Background()) { + t.Fatal("the pending-save barrier didn't clear after the save") + } + s.sightMu.Lock() + e := s.sights[key] + finished := false + if e != nil { + select { + case <-e.done: + finished = true + default: + } + } + s.sightMu.Unlock() + if !finished { + t.Fatal("the canceled request returned before its completed description was saved") + } + + if code, got := postAs(t, New(), "", imagesBody(1)); code != 200 { + t.Fatalf("after restart: %d %s", code, got) + } + if n := len(u.sent("eye")); n != 1 { + t.Fatalf("the completed description was lost on cancellation: %d descriptions, want 1", n) + } +} diff --git a/internal/gateway/vision_cache_unix_test.go b/internal/gateway/vision_cache_unix_test.go new file mode 100644 index 000000000..70eb0dd07 --- /dev/null +++ b/internal/gateway/vision_cache_unix_test.go @@ -0,0 +1,32 @@ +//go:build !windows + +package gateway + +import ( + "fmt" + "os" + "path/filepath" + "testing" +) + +func TestSightAppendTightensExistingPermissions(t *testing.T) { + fresh(t) + s := New() + if err := os.MkdirAll(filepath.Dir(s.sightFile), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(s.sightFile, nil, 0o644); err != nil { + t.Fatal(err) + } + if err := os.Chmod(s.sightFile, 0o644); err != nil { + t.Fatal(err) + } + s.saveSight(fmt.Sprintf("%064x", 88), "private", "probe/eye") + st, err := os.Stat(s.sightFile) + if err != nil { + t.Fatal(err) + } + if got := st.Mode().Perm(); got != 0o600 { + t.Fatalf("cache mode = %04o, want 0600", got) + } +} diff --git a/internal/gateway/vision_dedupe_test.go b/internal/gateway/vision_dedupe_test.go index b2c50372f..ed0dfc2f1 100644 --- a/internal/gateway/vision_dedupe_test.go +++ b/internal/gateway/vision_dedupe_test.go @@ -252,3 +252,28 @@ func TestCanceledWhileDescribingKeepsItsRoute(t *testing.T) { t.Fatalf("the canceled request's routes: %+v", rs) } } + +// A gateway restart must not describe a conversation's images all over +// again. The description cache lives in the same config directory as the +// gateway, so the next Server starts with every completed description. +func TestDescriptionSurvivesGatewayRestart(t *testing.T) { + s, u := eyed(t) + body := imagesBody(1) + if code, got := postAs(t, s, "", body); code != 200 { + t.Fatalf("before restart: %d %s", code, got) + } + if n := len(u.sent("eye")); n != 1 { + t.Fatalf("before restart: %d descriptions, want 1", n) + } + + restarted := New() + if code, got := postAs(t, restarted, "", body); code != 200 { + t.Fatalf("after restart: %d %s", code, got) + } + if n := len(u.sent("eye")); n != 1 { + t.Fatalf("after restart: %d descriptions, want the original 1", n) + } + if got := u.sent("text"); len(got) != 2 || !strings.Contains(got[1], "A red square with the word HELLO") || !strings.Contains(got[1], "probe/eye describes it") { + t.Fatalf("the restored description/by wasn't sent to the text model: %v", got) + } +}