package app import ( "context" "errors" "math" "strings" "testing" "time" ) func TestAdminCostsPerRequest(t *testing.T) { s, _ := fixtureService(t) s.cfg.JevPricePerMillion = 0.042 ctx := context.WithValue(context.Background(), contextKey{}, callContext{ID: "costly", Caller: "test"}) s.log.request(ctx, "search", map[string]string{"query": "q"}, "ok") s.log.decision(ctx, "rerank", "jev", []byte(`{}`), []byte(`{"answers":{},"usage":{"input_tokens":1000000,"output_tokens":20}}`), nil, time.Millisecond) // the local model reports no usage: priced from the request size (400 bytes, about 100 tokens) s.log.decision(ctx, "passage", "local", []byte(strings.Repeat("x", 400)), []byte(`{"answers":{}}`), nil, time.Millisecond) s.log.decision(ctx, "passage", "jev", []byte(`{}`), nil, errors.New("refused"), time.Millisecond) free := context.WithValue(context.Background(), contextKey{}, callContext{ID: "free", Caller: "test"}) s.log.request(free, "contents", map[string]string{"urls": "u"}, "ok") page, err := s.adminRequests(context.Background(), 0, "", false) if err != nil { t.Fatal(err) } got := map[string]map[string]any{} for _, row := range page.Rows { got[row["requestId"].(string)] = row } c := got["costly"] if c["decisionCalls"] != int64(2) || c["inputTokens"] != int64(1000100) || math.Abs(c["jevUsd"].(float64)-0.0420042) > 1e-9 { t.Fatalf("costly request: %v", c) } if f := got["free"]; f["decisionCalls"] != int64(0) || f["jevUsd"].(float64) != 0 { t.Fatalf("request without decisions: %v", f) } o, err := s.adminOverview(context.Background()) if err != nil { t.Fatal(err) } d := o.(map[string]any)["decisions"].(map[string]any) if d["requests"] != int64(2) || d["calls"] != int64(2) || d["estimatedCalls"] != int64(1) { t.Fatalf("overview decisions: %v", d) } }