Files
magpie/internal/usage/probes.go
T
yetone f39fc3ac8b usage: a model list that was answered is no row of Requests (ferock on Discord)
ferock (Discord #general): Usage > Requests is full of rows like
"magpie · magpie's own · Remote magpie · API · Model list · 0 0 · 757 ms
· 200, GET /v1/models", which no tool of theirs sent.

Cause: ffe493773 (v0.1.1446) wrote every request magpie sends a
provider on its own into the request log (source "probe"): the editor's
Test and Detect APIs, and every model-list fetch. 0152f6696 then gave a
Remote magpie a 10-minute list schedule (KeepListsFresh), so each Remote
magpie added ~144 such rows a day. The same rows came from every other
automatic fetch: start-up's FetchNew, the panel's FetchNewSoon, the
Providers page's FetchNewBehind and any provider with a RefreshEvery.
They were already counted in no token, cost, chart, budget or quota
total, but they were listed and counted in the page's row total.

Fix: a model_list probe with a 2xx/3xx status and no error
(usage.quietProbe) is not written by usage's probelog.Sink, and is
skipped when the log's index parses one (logSnapshot.probes). This rule
covers every list fetch, whoever started it, so every sibling is
covered by one check. A list that failed is still a row (the Failed
filter finds it, and the row says why models are missing), and every
Test and Detect APIs row stays as it was. Older rows: the answered
model lists already in usage.jsonl stop being listed at the next start
of the index, with no rewrite. The lines stay in the file and nothing
reads them. Quota and usage polls and health checks were never written
there (only Test, Detect and list are marked by probelog), so nothing
else needed changing. The TUI and CLI have no request list. The heatmap,
Summarize, Load and the exports skipped probes already.

Tests:
- usage TestAnsweredModelListIsNoRow (new): 200 and 304 lists aren't
  written; a 503 and a connection-refused list are listed and Failed
  finds both; a 200 Test is listed; an old answered list line in the log
  is not listed, and Total is 3.
- TestProbeRowsListedNotCounted and the rename tests now use a failed
  list (a 200 one would no longer be a row).

Broken by hand, each red: quietProbe returning false (the 200 list
written and listed); the index's skip removed, Sink's kept (the old line
listed, total 4).

Run, on mote:
- go test -tags nogui -timeout 45m ./... at the pre-rebase head
  (b4f2fa9d3 on 0a7633136): every package ok, 76 ok, exit 0 (gateway
  547s, agent 298s, provider 167s, usage 48s).
- After rebase on origin/main 9ba3f049e (which touched neither usage
  nor probelog): go build ./...; go vet for darwin, GOOS=linux and
  GOOS=windows on usage and probelog; go test usage, probelog,
  usageapi, and provider -run Probe|Detect|TestTestWrites: ok. gofmt
  -l clean.
- GUI (no asset changed): usage-ledger*.test.cjs, ledger-*.test.cjs and
  own-requests.test.cjs, chromium and webkit, each file's languages:
  381 tests, 375 pass. The 6 reds are usage-ledger's "newest live route
  needs no return-to-live button" (en, zh, both engines), which is
  already filed as #3104. usage-ledger-probe passed in every language.

Not tried: a real Remote magpie over a day. The row filter was not
checked on a real usage.jsonl.
2026-10-28 09:42:21 +08:00

150 lines
5.4 KiB
Go

package usage
import (
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/probelog"
"github.com/yetone/magpie/internal/provider"
)
// SourceProbe is Record.Source for a request magpie sent a provider on its
// own, outside any agent's turn (probelog): the editor's Test, Detect
// APIs, a model list's refresh. Its Kind says which (probelog.KindTest,
// KindDetect, KindList). Such a row is listed on the request log, told
// apart there, and counted nowhere: no total, cost, chart, group, budget,
// window hold or observer reads it. The log's index keeps it apart from
// the calls (logSnapshot.probes) so a reader of those never meets it.
const SourceProbe = "probe"
// IsProbe is a request magpie sent on its own (SourceProbe).
func (r Record) IsProbe() bool { return r.Source == SourceProbe }
// IsProbe is a row of such a request. A packed row keeps the row's Source,
// not its record's, so the request log asks the row.
func (r Row) IsProbe() bool { return r.Source == SourceProbe || r.Record.IsProbe() }
// probeRow is a probe's record and where its line ends in the log, as a
// gateway row's Order is.
type probeRow struct {
Record
off int64
}
func init() {
probelog.Sink = func(p probelog.Row) {
r := Record{Time: p.Time, Agent: "magpie", Provider: p.Provider, ProviderAccount: p.Account,
Host: p.Host, Model: p.Model, Requested: p.Model, Status: p.Status, Millis: p.Millis,
Error: clipProbeError(p.Error), Endpoint: p.Endpoint, Kind: p.Kind, Source: SourceProbe}
if quietProbe(r) {
return
}
Append(r)
}
}
// quietProbe is a request of magpie's own the request log leaves out: a
// model list that was answered. magpie asks for one by itself, at start-up,
// behind the panel and the Providers page, and on a schedule (a Remote
// magpie's every 10 minutes, RemoteMagpieEvery), so the Requests page
// filled with rows of 0 tokens that no agent sent (ferock on Discord). One
// that failed is listed, as is every Test and Detect APIs: a list that
// couldn't be fetched is why models are missing, and the row says why.
// Rows written before this are left out the same way as the log is read
// (logSnapshot.probes); the lines stay in the file, counted nowhere.
func quietProbe(r Record) bool {
return r.Kind == probelog.KindList && r.Status >= 200 && r.Status < 400 && r.Error == ""
}
// clipProbeError keeps an error's first 500 bytes, as a vendor's answer can
// be a whole page.
func clipProbeError(s string) string {
const most = 500
if len(s) <= most {
return s
}
cut := most
for cut > 0 && s[cut]&0xC0 == 0x80 { // not inside a character
cut--
}
return s[:cut] + "…"
}
// probeChunk is the probes made since since as one chunk of the request
// log's rows, each in the order its line has in the log as a gateway
// row's is; nil for none.
// A provider renamed since is listed by the id it has now (Renames): the
// Requests page's provider list named a renamed one twice (cybercaius).
// One asked while a provider was being added, under its host, is listed
// by the id of the provider on that host (Renames.ProbeOf), and once no
// provider is on it, a deleted one's, by the id the log's calls to that
// host were made under (hosts, logSnapshot.hosts): cybercaius on Discord,
// a deleted provider's tests were listed under its host beside its id.
// A host no provider was on goes by its site (provider.SiteOf) the same
// way: CyberCaius again, Leee's model list asked at leee.baby before it
// was saved on another host of that site.
func probeChunk(probes []probeRow, since time.Time, renames provider.Renames, hosts map[string]string) *rowChunk {
var c *rowChunk
sites := sync.OnceValue(func() map[string]string { return sitesOf(hosts) })
for _, p := range probes {
if !since.IsZero() && p.Time.Before(since) {
continue
}
if c == nil {
c = &rowChunk{}
}
r := p.Record
r.Provider = probeProvider(r, renames, hosts, sites)
c.add(Row{Record: r, Source: SourceProbe}, "", p.off, false)
}
if c == nil {
return nil
}
c.dict, c.shapeIDs = nil, nil
return c
}
// sitesOf is hosts by site (provider.SiteOf): the provider the log's
// calls to that site went to, "" for a site two providers' calls went to.
func sitesOf(hosts map[string]string) map[string]string {
out := map[string]string{}
for h, id := range hosts {
site := provider.SiteOf(h)
if site == "" {
continue
}
if to, ok := out[site]; ok && to != id {
id = ""
}
out[site] = id
}
return out
}
// probeProvider is the provider a probe row is listed under: its id as it
// is now, and for one recorded under its host before the provider had an
// id, the provider saved on that host, or, with none on it now, the one
// the log's calls to that host went to; with neither, the same by the
// host's site. A host or site two providers were on, or none, stays the
// host.
func probeProvider(r Record, renames provider.Renames, hosts map[string]string, sites func() map[string]string) string {
id := renames.ProbeOf(r.Provider, r.Time)
if id != r.Provider || !strings.EqualFold(r.Provider, r.Host) || renames.OnHost(r.Host) {
return id
}
if to := hosts[strings.ToLower(r.Host)]; to != "" {
return renames.Of(to, r.Time)
}
if to, on := renames.OnSite(r.Host); on {
if to != "" {
return to
}
} else if site := provider.SiteOf(r.Host); site != "" {
if to := sites()[site]; to != "" {
return renames.Of(to, r.Time)
}
}
return strings.ToLower(id) // one host, however it was typed
}