gateway: the Routing view keeps a day's routes when a request that began before midnight is done after the day was gzipped, and lists the day once (waitingsnow) (#1057)
saveRoute writes a done route to the file of the day it began, and
pruneHistory, at most once an hour, gzips every day before today. gzipFile
wrote <day>.jsonl.gz whole from <day>.jsonl and removed the file, so a
request that began before midnight and was done after the first prune past
it (a long streamed reply, say) went into a new <day>.jsonl, and the next
prune gzipped that over the day's .gz: every other route of the day was
lost, and only the late ones were left. While both files were there,
History listed the day twice.
* gzipFile keeps a day's .gz and adds the file's routes after it as a
gzip member of their own, which the gzip reader reads back as one
stream. The new .gz is written to <day>.jsonl.gz.tmp and renamed over
the old one (steady.Rename), and the file is removed only once that is
done.
* A route the .gz has already is not added again: a file added and left
behind (magpie stopped before removing it) adds only what was written
to it since, however many times that happens. The .gz is read a route
at a time and matched against a set made from the file's lines, never
held whole unzipped.
* A .gz that doesn't read to its end, or ends in a route cut short (an
older magpie stopped, or the disk filled, while it or its file was
written), is written anew from its whole routes and the file's when the
file has a route to add. Added after the break, the file's routes could
never be read, and after a route cut short the first of them would join
it. A last route whole but for its newline is kept. The old gzipFile
mended a .gz cut short by writing it over from its file, and this keeps
that.
* A .gz that can't be read, other than for not being there, is unknown,
not empty: it and the file are left as they are for a later prune.
* pruneHistory removes a <day>.jsonl.gz.tmp once it is an hour old, left
by a magpie stopped between the write and the rename. A younger one
may be another magpie's, still being written.
* History counts a day's .jsonl beside its .gz into one entry of its day
list.
A day with only its .jsonl, the usual case, is gzipped to the same lines
as before at the same cost: 6.3 MB allocated for a real 4.5 MB day, here
and upstream. A late route beside a real day's .gz (569 KB, 5,481 routes)
allocates 14.7 MB and takes about 16 ms; upstream allocated 1.1 MB in under
a millisecond, writing over the day. While a file added and left behind is
there, until the next prune, History counts its routes twice, as it did
before.
Tests, with what upstream's history.go gives:
* TestHistoryKeepsALateRouteWithItsDay: a route done after its day's
prune, the file it went to left behind once with nothing written since
and twice with a late route written to it, and an older day beside it.
Upstream lists the day twice before the second prune ([{2026-09-29 1}
{2026-09-29 1} {2026-09-28 1}]), and after it returns routes [2] and
"route 1 not found".
* TestHistoryKeepsADayCutShort: a .gz cut short while written in place,
its whole file still there, comes back [1 2 3]; a .gz gzipped from a
file whose last route was cut short, a late route written since, comes
back [1 3]; one whose last route had no newline comes back [1 2 3].
Upstream returns [3] for the last two (the late file written over the
day), and passes the first, which it mends the same way.
* TestHistoryLeavesADayItCantRead: a .gz that can't be read keeps the
file beside it, and both read back [1 2] once it can be. Upstream
returns [2]. It skips where a file at mode 0 still reads: as root, on
Windows, or on a file system without Unix permissions.
* TestHistoryDropsALeftGzTmp: a .gz.tmp an hour and a minute old goes,
one written just now stays. Upstream leaves both.
Each part was also broken on its own, and each break fails a test:
History's old day list (the day twice), matching a file left behind by the
.gz's last member instead of by line ([1 2 2 3 3 4]), no check for a route
the .gz has ([1 2 2]), adding after a .gz cut short ([1] and "flate:
corrupt input before offset 41"), a mend that drops the .gz's routes ([2
3]), no check of the .gz's last newline ([1]), dropping a whole last route
without its newline ([1 3]), keeping a route cut short (4 routes counted
for 3), reading an unreadable .gz as empty ([2]), no sweep of the .gz.tmp,
and a sweep with no hour's grace. Writing the .gz in place instead of
through the .tmp passes them all: the atomic replace isn't covered by a
test.
Verified on 0bf9d77d, under a temporary HOME with Go's caches pinned:
gofmt -l, go vet ./..., go build, GOOS=linux go build -tags nogui and
GOOS=windows go build pass; the four new tests pass with -race -count=20,
and the history tests with -race -count=10. go test -tags nogui ./...
passes but for internal/plugin, whose tests don't build internal/gateway:
its TestHostJSCancellation/ready-wait ran past its 10s limit with the
load average at about 25 to 35, and passes alone (4.6s).
On a copy of a real routing directory, one late route on 2026-10-05 left
that day's 5,481 routes in place and listed it once with 5,482; upstream
kept the late route alone. Not tried on Windows itself. Two magpies pruning
the same directory at once (during a take-over) aren't covered: history.mu
holds within one process only.
This commit is contained in:
+100
-5
@@ -22,6 +22,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
@@ -85,6 +86,18 @@ func saveRoute(r Route) {
|
||||
// pruneHistory gzips the days that are over, and drops the days older than
|
||||
// historyDays, then the oldest until what is left fits historyBytes.
|
||||
func pruneHistory(dir string, now time.Time) {
|
||||
// a .gz.tmp left by a magpie stopped before renaming it (gzipFile) goes
|
||||
// once it is an hour old: a younger one may be another magpie's, still
|
||||
// being written
|
||||
es, _ := os.ReadDir(dir)
|
||||
for _, e := range es {
|
||||
if !strings.HasSuffix(e.Name(), ".jsonl.gz.tmp") {
|
||||
continue
|
||||
}
|
||||
if fi, err := e.Info(); err == nil && now.Sub(fi.ModTime()) > time.Hour {
|
||||
os.Remove(filepath.Join(dir, e.Name()))
|
||||
}
|
||||
}
|
||||
today := now.Local().Format(dayForm)
|
||||
for _, d := range historyFiles(dir) {
|
||||
if d.day < today && !strings.HasSuffix(d.path, ".gz") {
|
||||
@@ -107,20 +120,98 @@ func pruneHistory(dir string, now time.Time) {
|
||||
}
|
||||
}
|
||||
|
||||
// gzipFile gzips a day's file into its .gz. A day gzipped already keeps its
|
||||
// .gz, the file's routes going after its own as a gzip member of their own
|
||||
// (read back as one stream): a route that began before midnight and was done
|
||||
// after the first prune past it is written to its day's file again. A route
|
||||
// in the .gz already, from a file added and left behind (magpie stopped
|
||||
// before removing it), isn't added again. A .gz cut short, or ending in a
|
||||
// route cut short (an older magpie stopped, or the disk filled, as it or its
|
||||
// file was written), is written anew from its whole routes and the file's
|
||||
// when the file has a route to add: after the break the file's routes
|
||||
// couldn't be read, and after a route cut short the first of them would join
|
||||
// it. A last route whole but for its newline is kept. The .gz is read a route
|
||||
// at a time, never held whole unzipped; it is replaced whole, never seen half
|
||||
// written, and the file goes once its routes are in. A .gz that can't be read
|
||||
// from disk is left as it is, and the file with it, for a later prune.
|
||||
func gzipFile(path string) {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
z := gzip.NewWriter(&buf)
|
||||
z.Write(b)
|
||||
if z.Close() != nil || os.WriteFile(path+".gz", buf.Bytes(), 0o600) != nil {
|
||||
old, err := os.ReadFile(path + ".gz")
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return
|
||||
}
|
||||
// the file's routes, each true once the .gz is seen to have it: a set
|
||||
// built from the file, a few routes, not from the whole day
|
||||
in := map[string]bool{}
|
||||
whole := true // the .gz, if there is one, can have routes go after it
|
||||
if len(old) > 0 {
|
||||
for l := range bytes.Lines(b) {
|
||||
in[string(bytes.TrimSpace(l))] = false
|
||||
}
|
||||
whole = gzRoutes(old, func(l []byte) {
|
||||
if _, ok := in[string(l)]; ok {
|
||||
in[string(l)] = true
|
||||
}
|
||||
})
|
||||
}
|
||||
buf := new(bytes.Buffer)
|
||||
if whole {
|
||||
buf = bytes.NewBuffer(old)
|
||||
}
|
||||
z := gzip.NewWriter(buf)
|
||||
nl := []byte{'\n'}
|
||||
add := func(l []byte) {
|
||||
z.Write(l)
|
||||
z.Write(nl)
|
||||
}
|
||||
if !whole {
|
||||
gzRoutes(old, add) // written anew, its whole routes first
|
||||
}
|
||||
added := false
|
||||
for l := range bytes.Lines(b) {
|
||||
if l = bytes.TrimSpace(l); len(l) > 0 && !in[string(l)] {
|
||||
add(l)
|
||||
added = true
|
||||
}
|
||||
}
|
||||
if added {
|
||||
tmp := path + ".gz.tmp"
|
||||
if z.Close() != nil || os.WriteFile(tmp, buf.Bytes(), 0o600) != nil || steady.Rename(tmp, path+".gz") != nil {
|
||||
os.Remove(tmp)
|
||||
return
|
||||
}
|
||||
}
|
||||
os.Remove(path)
|
||||
}
|
||||
|
||||
// gzRoutes calls f with each route of a day's .gz in turn, a last route
|
||||
// whole but for its newline among them and one cut short left out. It says
|
||||
// whether the .gz read to its end, its last route ending in a newline: what
|
||||
// a gzip member added after it needs to be read.
|
||||
func gzRoutes(gz []byte, f func([]byte)) bool {
|
||||
z, err := gzip.NewReader(bytes.NewReader(gz))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
r := bufio.NewReader(z)
|
||||
for {
|
||||
line, err := r.ReadBytes('\n')
|
||||
l := bytes.TrimSpace(line)
|
||||
if err != nil {
|
||||
if len(l) > 0 && json.Valid(l) {
|
||||
f(l)
|
||||
}
|
||||
return err == io.EOF && len(l) == 0
|
||||
}
|
||||
if len(l) > 0 {
|
||||
f(l)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type dayFile struct {
|
||||
day, path string
|
||||
size int64
|
||||
@@ -184,7 +275,11 @@ func History(day string) (days []HistoryDay, routes []Route, cut bool) {
|
||||
history.counts[d.path] = c
|
||||
}
|
||||
if n := c.n; n > 0 {
|
||||
days = append([]HistoryDay{{d.day, n}}, days...)
|
||||
if len(days) > 0 && days[0].Day == d.day {
|
||||
days[0].Requests += n // a late route's file beside the day's .gz
|
||||
} else {
|
||||
days = append([]HistoryDay{{d.day, n}}, days...)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.SliceStable(routes, func(i, j int) bool { return routes[i].Time.Before(routes[j].Time) })
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -79,6 +84,202 @@ func TestHistoryKeepsDaysAndDropsOld(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A route that began on a day gzipped already, its reply streamed past
|
||||
// midnight and past that hour's prune, is kept with the day's other
|
||||
// routes: its file is added to the day's .gz, not written over it, and the
|
||||
// day is listed once with all of them, before and after. Its file added and
|
||||
// left behind (magpie stopped before removing it) adds none of them again,
|
||||
// however often it is left, and late routes written to it in between.
|
||||
func TestHistoryKeepsALateRouteWithItsDay(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
now := historyNoon(t)
|
||||
y, m, d := now.AddDate(0, 0, -1).Date()
|
||||
yday := time.Date(y, m, d, 23, 59, 0, 0, time.Local)
|
||||
before := yday.AddDate(0, 0, -1)
|
||||
day, dir := yday.Format(dayForm), HistoryDir()
|
||||
late := filepath.Join(dir, day+".jsonl")
|
||||
kept := func(when string, ids ...int64) {
|
||||
t.Helper()
|
||||
want := []HistoryDay{{day, len(ids)}, {before.Format(dayForm), 1}}
|
||||
days, rs, _ := History(day)
|
||||
var got []int64
|
||||
for _, r := range rs {
|
||||
got = append(got, r.ID)
|
||||
}
|
||||
if !slices.Equal(days, want) || !slices.Equal(got, ids) {
|
||||
t.Errorf("%s: days %+v, routes %v; want %+v, routes %v", when, days, got, want, ids)
|
||||
}
|
||||
if days, _, _ := History(""); !slices.Equal(days, want) {
|
||||
t.Errorf("%s: days live %+v; want %+v", when, days, want)
|
||||
}
|
||||
for _, id := range ids {
|
||||
if _, ok := HistoryRoute(id, yday); !ok {
|
||||
t.Errorf("%s: route %d not found", when, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
prune := func() {
|
||||
t.Helper()
|
||||
pruneHistory(dir, now)
|
||||
if _, err := os.Stat(late); !os.IsNotExist(err) {
|
||||
t.Errorf("the late file is still there: %v", err)
|
||||
}
|
||||
}
|
||||
saveRoute(Route{ID: 9, Time: before, Model: "z", Done: true})
|
||||
saveRoute(Route{ID: 1, Time: yday, Model: "a", Done: true})
|
||||
prune()
|
||||
saveRoute(Route{ID: 2, Time: yday.Add(10 * time.Second), Model: "b", Done: true}) // done after the prune
|
||||
kept("beside the day's .gz", 1, 2)
|
||||
left, err := os.ReadFile(late)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prune()
|
||||
kept("added to the day's .gz", 1, 2)
|
||||
os.WriteFile(late, left, 0o600)
|
||||
prune()
|
||||
kept("left behind", 1, 2)
|
||||
ids := []int64{1, 2, 3, 4}
|
||||
for _, id := range ids[2:] {
|
||||
os.WriteFile(late, left, 0o600)
|
||||
saveRoute(Route{ID: id, Time: yday.Add(time.Duration(id) * 10 * time.Second), Model: "c", Done: true})
|
||||
if left, err = os.ReadFile(late); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prune()
|
||||
kept("left behind, a late route written to it since", ids[:id]...)
|
||||
}
|
||||
}
|
||||
|
||||
// A day's .gz cut short, by an older magpie stopped (or a disk filled) while
|
||||
// writing it in place, or by a route cut short in the file it was gzipped
|
||||
// from, is written anew from the whole routes it has and its file's: after
|
||||
// the break none of the file's routes could be read, and after a route cut
|
||||
// short the first of them would join it. A last route whole but for its
|
||||
// newline is kept.
|
||||
func TestHistoryKeepsADayCutShort(t *testing.T) {
|
||||
route := func(id int) string { return `{"id":` + strconv.Itoa(id) + `,"model":"m"}` + "\n" }
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
gz func(z *gzip.Writer) // writes the .gz as it was left
|
||||
file string
|
||||
ids []int64
|
||||
}{
|
||||
// gzipped in place from its file, all three routes, and stopped
|
||||
// after the first and a half
|
||||
{"stopped while written in place", func(z *gzip.Writer) {
|
||||
z.Write([]byte(route(1) + route(2)[:9]))
|
||||
z.Flush()
|
||||
}, route(1) + route(2) + route(3), []int64{1, 2, 3}},
|
||||
// gzipped whole from a file whose second route was cut short, and a
|
||||
// late route written to the file since
|
||||
{"its file cut short", func(z *gzip.Writer) {
|
||||
z.Write([]byte(route(1) + route(2)[:9]))
|
||||
z.Close()
|
||||
}, route(3), []int64{1, 3}},
|
||||
// gzipped whole from a file whose last route was written without its
|
||||
// newline, and a late route written to the file since
|
||||
{"its last route without its newline", func(z *gzip.Writer) {
|
||||
z.Write([]byte(route(1) + strings.TrimSuffix(route(2), "\n")))
|
||||
z.Close()
|
||||
}, route(3), []int64{1, 2, 3}},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
now := time.Now()
|
||||
day, dir := now.AddDate(0, 0, -1).Format(dayForm), HistoryDir()
|
||||
path := filepath.Join(dir, day+".jsonl")
|
||||
os.MkdirAll(dir, 0o700)
|
||||
var gz bytes.Buffer
|
||||
c.gz(gzip.NewWriter(&gz))
|
||||
os.WriteFile(path+".gz", gz.Bytes(), 0o600)
|
||||
os.WriteFile(path, []byte(c.file), 0o600)
|
||||
pruneHistory(dir, now)
|
||||
days, rs, _ := History(day)
|
||||
var got []int64
|
||||
for _, r := range rs {
|
||||
got = append(got, r.ID)
|
||||
}
|
||||
if len(days) != 1 || days[0] != (HistoryDay{day, len(c.ids)}) || !slices.Equal(got, c.ids) {
|
||||
t.Errorf("days %+v, routes %v; want %s with %v", days, got, day, c.ids)
|
||||
}
|
||||
b, _ := os.ReadFile(path + ".gz")
|
||||
z, err := gzip.NewReader(bytes.NewReader(b))
|
||||
if err == nil {
|
||||
_, err = io.Copy(io.Discard, z)
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("the .gz isn't whole: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Errorf("the file is still there: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A day's .gz.tmp left by a magpie stopped before renaming it over the .gz
|
||||
// goes at a prune once it is an hour old. A younger one, maybe another
|
||||
// magpie's still being written, stays.
|
||||
func TestHistoryDropsALeftGzTmp(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
now := time.Now()
|
||||
dir := HistoryDir()
|
||||
os.MkdirAll(dir, 0o700)
|
||||
left := filepath.Join(dir, now.AddDate(0, 0, -2).Format(dayForm)+".jsonl.gz.tmp")
|
||||
young := filepath.Join(dir, now.AddDate(0, 0, -1).Format(dayForm)+".jsonl.gz.tmp")
|
||||
os.WriteFile(left, []byte("\x1f\x8b\x08"), 0o600)
|
||||
os.WriteFile(young, []byte("\x1f\x8b\x08"), 0o600)
|
||||
then := now.Add(-time.Hour - time.Minute)
|
||||
if err := os.Chtimes(left, then, then); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pruneHistory(dir, now)
|
||||
if _, err := os.Stat(left); !os.IsNotExist(err) {
|
||||
t.Errorf("the .gz.tmp left over an hour ago is still there: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(young); err != nil {
|
||||
t.Errorf("a .gz.tmp written just now is gone: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A day's .gz that can't be read (left by magpie run as another user, say)
|
||||
// is unknown, not empty: it isn't written over from the day's file, and the
|
||||
// file stays for a prune that can read the .gz.
|
||||
func TestHistoryLeavesADayItCantRead(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
now := time.Now()
|
||||
day, dir := now.AddDate(0, 0, -1).Format(dayForm), HistoryDir()
|
||||
path := filepath.Join(dir, day+".jsonl")
|
||||
os.MkdirAll(dir, 0o700)
|
||||
var gz bytes.Buffer
|
||||
z := gzip.NewWriter(&gz)
|
||||
z.Write([]byte(`{"id":1,"model":"m"}` + "\n"))
|
||||
z.Close()
|
||||
os.WriteFile(path+".gz", gz.Bytes(), 0o600)
|
||||
os.WriteFile(path, []byte(`{"id":2,"model":"m"}`+"\n"), 0o600)
|
||||
if err := os.Chmod(path+".gz", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.ReadFile(path + ".gz"); err == nil {
|
||||
t.Skip("a file at mode 0 still reads here: root, Windows, or a file system without Unix permissions")
|
||||
}
|
||||
pruneHistory(dir, now)
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
t.Errorf("the file is gone with the .gz unread: %v", err)
|
||||
}
|
||||
os.Chmod(path+".gz", 0o600)
|
||||
pruneHistory(dir, now)
|
||||
days, rs, _ := History(day)
|
||||
var got []int64
|
||||
for _, r := range rs {
|
||||
got = append(got, r.ID)
|
||||
}
|
||||
if want := []int64{1, 2}; len(days) != 1 || days[0] != (HistoryDay{day, 2}) || !slices.Equal(got, want) {
|
||||
t.Errorf("read again: days %+v, routes %v; want %s with %v", days, got, day, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteUsageCompactAndLegacyJSON(t *testing.T) {
|
||||
// Ignore fields that full ledger records wrote into earlier route history.
|
||||
var old Route
|
||||
|
||||
Reference in New Issue
Block a user