diff --git a/internal/usage/log_disk.go b/internal/usage/log_disk.go new file mode 100644 index 000000000..44bbb70ad --- /dev/null +++ b/internal/usage/log_disk.go @@ -0,0 +1,247 @@ +package usage + +import ( + "bufio" + "encoding/binary" + "encoding/json" + "os" + "path/filepath" + "sync" + "time" + + "github.com/yetone/magpie/internal/sessions" +) + +// The log's full blocks are kept on disk between runs (log-v1.bin). A +// started magpie parsed the whole log again, a record at a time, before +// its first page: a long history's 109 MB took ~620 MB of allocations in +// the first seconds, the start's largest part, and its collections (#2278). +// The file stands for the log's first bytes while their SHA-256 is the +// one it was written with, under the same code (requestDiskBinary); a +// start reads the blocks from it and parses only the lines after them, as +// a parse continues the snapshot before it. + +const logDiskMagic = "magpie-log-v1\n" + +func logDiskPath() string { + return filepath.Join(filepath.Dir(sessions.CachePath()), "log-v1.bin") +} + +// logFull is a snapshot as it was where its full blocks end: how many, +// the log's bytes up to the last of them, their hash and its running +// state, and what the lines up to there said. +type logFull struct { + n int + off int64 + hash string + digest []byte + first, firstOwn time.Time + keyProviders map[string]bool + hosts map[string]string +} + +// logDiskEvery bounds how often the file is written again: a block fills +// every logBlockRows calls, and a start parses what came after the last +// write. +const logDiskEvery = 10 * time.Minute + +// logDiskLoaded, in tests, is told how many blocks a start read from the +// file. +var logDiskLoaded func(n int) + +var logDiskWrote struct { + sync.Mutex + path string + n int + at time.Time +} + +// logDisk is the snapshot a start continues from: the file's blocks and +// what was read with them, or nil. +type logDisk struct { + full logFull + probes []probeRow + blocks []*rowChunk +} + +type logDiskProbe struct { + R Record `json:"r"` + Off int64 `json:"o"` +} + +// logDiskRead is the file's snapshot of the log at path, when the log's +// first bytes are still the ones it was written of. +func logDiskRead(path string, size int64) *logDisk { + b, err := os.ReadFile(logDiskPath()) + if err != nil { + return nil + } + header, b, ok := cutDiskEntry(b) + if !ok { + return nil + } + take := func() uint64 { + n, k := binary.Uvarint(header) + if k <= 0 { + header = nil + return 0 + } + header = header[k:] + return n + } + text := func() string { + n := take() + if header == nil || n > uint64(len(header)) { + header = nil + return "" + } + s := string(header[:n]) + header = header[n:] + return s + } + if text() != logDiskMagic || text() != requestDiskBinary() || text() != path || header == nil { + return nil + } + d := &logDisk{full: logFull{keyProviders: map[string]bool{}, hosts: map[string]string{}}} + d.full.hash, d.full.digest = text(), []byte(text()) + d.full.off, d.full.n = int64(take()), int(take()) + for _, t := range []*time.Time{&d.full.first, &d.full.firstOwn} { + if s := text(); s != "" && t.UnmarshalText([]byte(s)) != nil { + return nil + } + } + for range take() { + d.full.keyProviders[text()] = true + } + for range take() { + k := text() + d.full.hosts[k] = text() + } + if header == nil || len(header) != 0 || d.full.off > size || d.full.hash == "" || logRecordHash(path, d.full.off) != d.full.hash { + return nil + } + raw, b, ok := cutDiskEntry(b) + var probes []logDiskProbe + if !ok || json.Unmarshal(raw, &probes) != nil { + return nil + } + for _, p := range probes { + d.probes = append(d.probes, probeRow{p.R, p.Off}) + } + for range d.full.n { + raw, b, ok = cutDiskEntry(b) + if !ok { + return nil + } + c, err := readDiskEntry(raw) + if err != nil { + return nil + } + c.serial = nextChunkSerial() + d.blocks = append(d.blocks, c) + } + if len(b) != 0 { + return nil + } + return d +} + +// logDiskKept notes that the file holds n full blocks of the log at path. +func logDiskKept(path string, n int) { + logDiskWrote.Lock() + logDiskWrote.path, logDiskWrote.n, logDiskWrote.at = path, n, time.Now() + logDiskWrote.Unlock() +} + +// logDiskWrite keeps s's full blocks, when it has more than the file was +// last written with and logDiskEvery has passed since. +func logDiskWrite(s *logSnapshot) { + if s.full.n == 0 || s.full.hash == "" || s.full.digest == nil { + return + } + logDiskWrote.Lock() + defer logDiskWrote.Unlock() + w := &logDiskWrote + if w.path == s.path && (s.full.n <= w.n || time.Since(w.at) < logDiskEvery) { + return + } + if logDiskSave(s) == nil { + w.path, w.n, w.at = s.path, s.full.n, time.Now() + } +} + +func logDiskSave(s *logSnapshot) error { + var h []byte + for _, t := range []string{logDiskMagic, requestDiskBinary(), s.path, s.full.hash, string(s.full.digest)} { + h = appendDiskString(h, t) + } + h = binary.AppendUvarint(h, uint64(s.full.off)) + h = binary.AppendUvarint(h, uint64(s.full.n)) + for _, t := range []time.Time{s.full.first, s.full.firstOwn} { + text := "" + if !t.IsZero() { + b, err := t.MarshalText() + if err != nil { + return err + } + text = string(b) + } + h = appendDiskString(h, text) + } + h = binary.AppendUvarint(h, uint64(len(s.full.keyProviders))) + for k := range s.full.keyProviders { + h = appendDiskString(h, k) + } + h = binary.AppendUvarint(h, uint64(len(s.full.hosts))) + for k, v := range s.full.hosts { + h = appendDiskString(appendDiskString(h, k), v) + } + // the probes of the full blocks' lines: the lines after are parsed again + probes := []logDiskProbe{} + for _, p := range s.probes { + if p.off <= s.full.off { + probes = append(probes, logDiskProbe{p.Record, p.off}) + } + } + pb, err := json.Marshal(probes) + if err != nil { + return err + } + path := logDiskPath() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + out, err := os.CreateTemp(filepath.Dir(path), "log-*.tmp") + if err != nil { + return err + } + defer os.Remove(out.Name()) + bw := bufio.NewWriterSize(out, 1<<20) + err = writeDiskEntry(bw, h) + if err == nil { + err = writeDiskEntry(bw, pb) + } + var buf []byte + for _, c := range s.blocks[:s.full.n] { + if err != nil { + break + } + b := diskEntry(buf, c) + if b == nil { + err = errDiskEntry + break + } + err = writeDiskEntry(bw, b) + buf = b + } + if err == nil { + err = bw.Flush() + } + if closeErr := out.Close(); err == nil { + err = closeErr + } + if err != nil { + return err + } + return os.Rename(out.Name(), path) +} diff --git a/internal/usage/log_disk_test.go b/internal/usage/log_disk_test.go new file mode 100644 index 000000000..a73d4dcea --- /dev/null +++ b/internal/usage/log_disk_test.go @@ -0,0 +1,150 @@ +package usage + +import ( + "encoding/json" + "fmt" + "maps" + "os" + "path/filepath" + "reflect" + "slices" + "testing" + "time" + + "github.com/yetone/magpie/internal/probelog" +) + +// logLines appends n calls from the i-th on to the log, as a gateway that +// isn't running reads them at its next start: in two zones, with hosts, +// keys, a try handed on and probes among them. +func logLines(t *testing.T, from, n int) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(Path()), 0o700); err != nil { + t.Fatal(err) + } + f, err := os.OpenFile(Path(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) + if err != nil { + t.Fatal(err) + } + enc := json.NewEncoder(f) + at := time.Date(2026, 8, 1, 9, 0, 0, 0, time.FixedZone("", 8*3600)) + for i := from; i < from+n; i++ { + r := Record{Time: at.Add(time.Duration(i) * time.Minute), Agent: "codex", Provider: fmt.Sprintf("p%d", i%3), Model: "m", + Host: fmt.Sprintf("h%d.example", i%5), Session: fmt.Sprintf("s%d", i/40), Input: i, Status: 200} + switch { + case i%7 == 0: + r.Time = r.Time.UTC() + case i%11 == 0: + r.ProviderKeyID, r.ProviderKeyName = fmt.Sprintf("k%d", i), "Team" + case i%13 == 0: + r.Source, r.Kind, r.Endpoint, r.Status, r.Error = SourceProbe, probelog.KindTest, "/v1/chat/completions", 500, "down" + case i%17 == 0: + r.RouteID, r.Status, r.Error = int64(i), 502, "bad gateway" + case i%17 == 1: + r.RouteID = int64(i - 1) + } + if err := enc.Encode(r); err != nil { + t.Fatal(err) + } + } + if err := f.Close(); err != nil { + t.Fatal(err) + } +} + +// logRead is what a snapshot gives its readers, written out. +func logRead(t *testing.T, s *logSnapshot) map[string]any { + t.Helper() + var rows, probes []string + s.visit(time.Time{}, func(r Record) { + b, _ := json.Marshal(r) + rows = append(rows, string(b)) + }) + for _, p := range s.probes { + b, _ := json.Marshal(p.Record) + probes = append(probes, fmt.Sprintf("%d %s", p.off, b)) + } + first, _ := s.first.MarshalText() + firstOwn, _ := s.firstOwn.MarshalText() + return map[string]any{"rows": rows, "probes": probes, "first": string(first), "firstOwn": string(firstOwn), "off": s.off, "hash": s.hash, + "blocks": len(s.blocks), "keys": slices.Sorted(maps.Keys(s.keyProviders)), "hosts": s.hosts} +} + +func restartLog() { + logIndex.Lock() + logIndex.snapshot = nil + logIndex.Unlock() + logDiskWrote.Lock() + logDiskWrote.path, logDiskWrote.n, logDiskWrote.at = "", 0, time.Time{} + logDiskWrote.Unlock() +} + +// A start reads the log's full blocks from log-v1.bin and parses only the +// lines after them, into the snapshot a parse of the whole log makes; a +// log whose first lines changed is parsed whole again (#2278). +func TestStartReadsKeptLogBlocks(t *testing.T) { + pageHome(t) + settleLogClock(t) + t.Cleanup(restartLog) + loaded := -1 + logDiskLoaded = func(n int) { loaded = n } + t.Cleanup(func() { logDiskLoaded = nil }) + restartLog() + logLines(t, 0, 2*logBlockRows+300) + first := logRead(t, readLogSnapshot()) + if loaded != -1 { + t.Fatalf("the first start read %d blocks from a file it hadn't written", loaded) + } + if _, err := os.Stat(logDiskPath()); err != nil { + t.Fatalf("the full blocks weren't kept: %v", err) + } + if n := len(first["probes"].([]string)); n < 50 { + t.Fatalf("%d probes", n) + } + + // the log grows while magpie isn't running + logLines(t, 2*logBlockRows+300, logBlockRows) + restartLog() + kept := logRead(t, readLogSnapshot()) + if loaded != 2 { + t.Fatalf("started again, %d blocks read from the file, want 2", loaded) + } + loaded = -1 + os.Remove(logDiskPath()) + restartLog() + whole := logRead(t, readLogSnapshot()) + if loaded != -1 { + t.Fatal("read blocks from a file that was removed") + } + if !reflect.DeepEqual(kept, whole) { + for k := range whole { + if !reflect.DeepEqual(kept[k], whole[k]) { + t.Errorf("%s from the kept blocks differs from the log's parse:\n%v\nwant\n%v", k, kept[k], whole[k]) + } + } + } + + // the log's first line is written over: its blocks are parsed again + b, err := os.ReadFile(Path()) + if err != nil { + t.Fatal(err) + } + if i := slices.Index(b, '1'); i < 0 { + t.Fatal("no digit") + } else { + b[i] = '2' + } + if err := os.WriteFile(Path(), b, 0o600); err != nil { + t.Fatal(err) + } + restartLog() + rewritten := logRead(t, readLogSnapshot()) + if loaded != -1 { + t.Fatalf("read %d blocks kept of the log before it was written over", loaded) + } + os.Remove(logDiskPath()) + restartLog() + if want := logRead(t, readLogSnapshot()); !reflect.DeepEqual(rewritten, want) { + t.Fatal("the log written over isn't read as a parse of it reads it") + } +} diff --git a/internal/usage/log_index.go b/internal/usage/log_index.go index d2d5dd653..6a5d87752 100644 --- a/internal/usage/log_index.go +++ b/internal/usage/log_index.go @@ -58,6 +58,8 @@ type logSnapshot struct { // while a provider was being added, under its host, is that // provider's after it is deleted too (probeChunk; cybercaius). hosts map[string]string + // full is where the full blocks end, for log-v1.bin + full logFull } var logIndex struct { @@ -147,6 +149,19 @@ func readLogSnapshot() *logSnapshot { next.keyProviders = maps.Clone(old.keyProviders) next.probes = slices.Clip(old.probes) // appended to, never written in next.hosts = maps.Clone(old.hosts) + next.full = old.full + } else if old == nil { + // a start: the blocks kept, and the lines after them + if d := logDiskRead(path, info.Size()); d != nil && resumeLogHash(sum, d.full.digest) { + next.full = d.full + next.off, next.first, next.firstOwn = d.full.off, d.full.first, d.full.firstOwn + next.blocks, next.probes = d.blocks, d.probes + next.keyProviders, next.hosts = maps.Clone(d.full.keyProviders), maps.Clone(d.full.hosts) + logDiskKept(path, d.full.n) + if logDiskLoaded != nil { + logDiskLoaded(d.full.n) + } + } } logIndex.reads++ f, err := os.Open(path) @@ -204,6 +219,8 @@ func readLogSnapshot() *logSnapshot { next.blocks = append(next.blocks, tail.freeze()) tail = nil clear(routes) + next.full = logFull{n: len(next.blocks), off: next.off, hash: fmt.Sprintf("%x", sum.Sum(nil)), digest: marshalLogHash(sum), + first: next.first, firstOwn: next.firstOwn, keyProviders: maps.Clone(next.keyProviders), hosts: maps.Clone(next.hosts)} } } if tail != nil { @@ -214,6 +231,7 @@ func readLogSnapshot() *logSnapshot { if (!trusted || !settled) && next.hash != logRecordHash(path, next.off) { next.hash, next.digest = "", nil next.settled = false + next.full = logFull{} } logAppends.Lock() // Preserve writes which arrived while this immutable snapshot was built. @@ -227,6 +245,7 @@ func readLogSnapshot() *logSnapshot { next.bytes += c.Bytes } logIndex.snapshot = next + logDiskWrite(next) return next }