Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: who answered a conversation is written to affinity.json behind the answer, once in a while, not on every answer

yetonea1118187b5c9
diff --git a/internal/cli/signals.go b/internal/cli/signals.go
index adf313216..d27102608 100644
--- a/internal/cli/signals.go
+++ b/internal/cli/signals.go
@@ -8,6 +8,7 @@ import (
"sync/atomic"
"syscall"
+ "github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/provider"
)
@@ -41,6 +42,7 @@ func endProbesOnSignal() {
proc.EndProbes()
if !handled {
provider.FlushServed() // a gateway's last answers, noted and not yet written
+ gateway.FlushSticks() // and who answered which conversation
die(s)
}
}
diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go
index 2e6508318..4352c4d6f 100644
--- a/internal/gateway/affinity.go
+++ b/internal/gateway/affinity.go
@@ -36,6 +36,7 @@ import (
"slices"
"strings"
"sync"
+ "testing"
"time"
"github.com/yetone/magpie/internal/edit"
@@ -141,6 +142,69 @@ var sticks = struct {
// sticksSaving keeps one write of the file at a time, the latest last.
var sticksSaving sync.Mutex
+// sticksFlushAfter is how long a conversation answered waits before the
+// file is written: what is answered meanwhile goes in the same write, so a
+// gateway answering many requests a second writes it once in a while, not
+// once a request (up to 512 conversations marshalled, written and renamed
+// on every answer, each after the last). A crash loses the last moment's;
+// flushSticks, as the gateway ends, loses nothing. In a test binary it is
+// 0, the file written at once, as it was: a write left waiting would
+// outlive the test and write into its temp folder as it is removed.
+var sticksFlushAfter = func() time.Duration {
+ if testing.Testing() {
+ return 0
+ }
+ return 2 * time.Second
+}()
+
+// sticksFlush is the write noteSticks has waiting, for the file at path.
+var sticksFlush struct {
+ sync.Mutex
+ pending bool
+ path string
+}
+
+// noteSticks has the file written within sticksFlushAfter: what this
+// magpie answered is in memory at once.
+func noteSticks() {
+ if sticksFlushAfter <= 0 {
+ saveSticks()
+ return
+ }
+ path := sticksPath()
+ sticksFlush.Lock()
+ if sticksFlush.pending && sticksFlush.path == path {
+ sticksFlush.Unlock()
+ return
+ }
+ sticksFlush.pending, sticksFlush.path = true, path
+ sticksFlush.Unlock()
+ time.AfterFunc(sticksFlushAfter, func() { flushSticksAt(path) })
+}
+
+// flushSticks writes what noteSticks has waiting: the gateway calls it as
+// it ends, so the magpie it hands over to, or the next start, reads it.
+func flushSticks() { flushSticksAt(sticksPath()) }
+
+// FlushSticks is flushSticks, for magpie ending on a signal before the
+// gateway's own end.
+func FlushSticks() { flushSticks() }
+
+// flushSticksAt writes the file at path when a write for it is waiting:
+// one waiting for another (a test's HOME before this one's) is dropped.
+func flushSticksAt(path string) {
+ sticksFlush.Lock()
+ if !sticksFlush.pending || sticksFlush.path != path {
+ sticksFlush.Unlock()
+ return
+ }
+ sticksFlush.pending = false
+ sticksFlush.Unlock()
+ if path == sticksPath() {
+ saveSticks()
+ }
+}
+
// savedStick is a stick as the file has it.
type savedStick struct {
Rest string `json:"rest"`
@@ -201,6 +265,11 @@ func stickOf(key string) (stick, bool) {
func saveSticks() {
sticksSaving.Lock()
defer sticksSaving.Unlock()
+ sticksFlush.Lock()
+ if sticksFlush.path == sticksPath() {
+ sticksFlush.pending = false // this write is the one waiting
+ }
+ sticksFlush.Unlock()
now := time.Now()
type kept struct {
k string
@@ -600,7 +669,7 @@ func answered(key string, c candidate, turn int, u Usage) {
}
}
sticks.Unlock()
- saveSticks()
+ noteSticks()
}
// unanswered forgets that c answered a conversation, when its reply to it
@@ -626,7 +695,7 @@ func unanswered(key string, c candidate) {
}
sticks.Unlock()
if ok {
- saveSticks()
+ noteSticks()
}
}
diff --git a/internal/gateway/affinity_write_behind_test.go b/internal/gateway/affinity_write_behind_test.go
new file mode 100644
index 000000000..2ff7c90b6
--- /dev/null
+++ b/internal/gateway/affinity_write_behind_test.go
@@ -0,0 +1,79 @@
+package gateway
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// Who answered a conversation is written to affinity.json behind the
+// answer, once in a while: each answer marshalled up to 512 conversations
+// and wrote and renamed the file, one answer after another.
+func TestSticksWrittenBehind(t *testing.T) {
+ fresh(t)
+ was := sticksFlushAfter
+ sticksFlushAfter = 2 * time.Second // as outside a test binary
+ t.Cleanup(func() { flushSticks(); sticksFlushAfter = was })
+ sticks.Lock()
+ sticks.m = map[string]stick{}
+ sticks.Unlock()
+ os.Remove(sticksPath())
+ c := candidate{p: provider.Provider{ID: "a", Key: "k"}, model: "m", rest: "a"}
+ for i := range 200 {
+ answered(fmt.Sprintf("conv-%d", i), c, 1, Usage{})
+ }
+ if _, err := os.Stat(sticksPath()); err == nil {
+ t.Fatal("affinity.json written on a request answered")
+ }
+ sticks.Lock()
+ _, ok := stickOf("conv-199")
+ sticks.Unlock()
+ if !ok {
+ t.Fatal("the last answer isn't known in memory")
+ }
+ flushSticks() // as the gateway ends
+ b, err := os.ReadFile(sticksPath())
+ if err != nil {
+ t.Fatalf("not written as the gateway ends: %v", err)
+ }
+ var saved map[string]savedStick
+ if err := json.Unmarshal(b, &saved); err != nil || len(saved) != 200 {
+ t.Fatalf("written %d conversations (%v), want 200", len(saved), err)
+ }
+
+ // and by itself, a moment later
+ sticksFlushAfter = 10 * time.Millisecond
+ os.Remove(sticksPath())
+ answered("conv-late", c, 1, Usage{})
+ for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(5 * time.Millisecond) {
+ if b, err := os.ReadFile(sticksPath()); err == nil && json.Unmarshal(b, &saved) == nil && saved["conv-late"].Who != "" {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("an answer never written")
+ }
+ }
+}
+
+func BenchmarkAnswered(b *testing.B) {
+ was := sticksFlushAfter
+ sticksFlushAfter = 2 * time.Second // as outside a test binary
+ b.Cleanup(func() { flushSticks(); sticksFlushAfter = was })
+ sticks.Lock()
+ sticks.m = map[string]stick{}
+ for i := range sticksKept {
+ sticks.m[fmt.Sprintf("conv-%d", i)] = stick{rest: "a", who: "a#k", model: "m", turn: 3, at: time.Now()}
+ }
+ sticks.Unlock()
+ c := candidate{p: provider.Provider{ID: "a", Key: "k"}, model: "m", rest: "a"}
+ b.ReportAllocs()
+ for i := 0; b.Loop(); i++ {
+ answered(fmt.Sprintf("conv-%d", i%sticksKept), c, 3, Usage{Input: 100})
+ }
+ b.StopTimer()
+ flushSticks()
+}
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index b5ac19456..a0f248abf 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -592,6 +592,7 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
srv.Shutdown(c)
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
}()
for {
err := srv.Serve(ln)