feat(laya): add sanitized ranking diagnostics
This commit is contained in:
66
backend/internal/ai/laya_diagnostics.go
Normal file
66
backend/internal/ai/laya_diagnostics.go
Normal file
@ -0,0 +1,66 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Only numeric aggregates live here. Never attach a request, result, asset or
|
||||
// candidate: diagnostics must remain independent of sensitive model inputs.
|
||||
type layaDiagnostics struct {
|
||||
candidates, assets, statesPlanned, requestsPlanned int
|
||||
statesSent, requestsSent, requestsValidated int
|
||||
batchMin, batchMax int
|
||||
durationMin, durationMax, durationTotal time.Duration
|
||||
durations int
|
||||
started time.Time
|
||||
planned bool
|
||||
}
|
||||
|
||||
func (d *layaDiagnostics) plan(states, batchSize int) {
|
||||
d.statesPlanned = states
|
||||
if states > 0 {
|
||||
d.requestsPlanned = (states + batchSize - 1) / batchSize
|
||||
}
|
||||
d.planned = true
|
||||
log.Printf("laya ranking plan candidates=%d assets=%d states_planned=%d requests_planned=%d", d.candidates, d.assets, d.statesPlanned, d.requestsPlanned)
|
||||
}
|
||||
func (d *layaDiagnostics) sending(size int) {
|
||||
d.requestsSent++
|
||||
d.statesSent += size
|
||||
if d.requestsSent == 1 || size < d.batchMin {
|
||||
d.batchMin = size
|
||||
}
|
||||
if size > d.batchMax {
|
||||
d.batchMax = size
|
||||
}
|
||||
}
|
||||
func (d *layaDiagnostics) finished(duration time.Duration) {
|
||||
if d.durations == 0 || duration < d.durationMin {
|
||||
d.durationMin = duration
|
||||
}
|
||||
if duration > d.durationMax {
|
||||
d.durationMax = duration
|
||||
}
|
||||
d.durationTotal += duration
|
||||
d.durations++
|
||||
}
|
||||
func durationMS(duration time.Duration) float64 { return float64(duration) / float64(time.Millisecond) }
|
||||
func (d *layaDiagnostics) report(failed bool) {
|
||||
// Early validation failures and empty input still have an explicit zero plan.
|
||||
if !d.planned {
|
||||
d.plan(0, 1)
|
||||
}
|
||||
batchMean, durationMean := 0.0, 0.0
|
||||
if d.requestsSent > 0 {
|
||||
batchMean = float64(d.statesSent) / float64(d.requestsSent)
|
||||
}
|
||||
if d.durations > 0 {
|
||||
durationMean = durationMS(d.durationTotal) / float64(d.durations)
|
||||
}
|
||||
outcome := "success"
|
||||
if failed {
|
||||
outcome = "failed"
|
||||
}
|
||||
log.Printf("laya ranking diagnostics candidates=%d assets=%d states_planned=%d states_sent=%d requests_planned=%d requests_sent=%d requests_validated=%d batch_size_min=%d batch_size_max=%d batch_size_mean=%.3f request_duration_ms_min=%.3f request_duration_ms_max=%.3f request_duration_ms_mean=%.3f request_duration_ms_total=%.3f rank_duration_ms=%.3f outcome=%s", d.candidates, d.assets, d.statesPlanned, d.statesSent, d.requestsPlanned, d.requestsSent, d.requestsValidated, d.batchMin, d.batchMax, batchMean, durationMS(d.durationMin), durationMS(d.durationMax), durationMean, durationMS(d.durationTotal), durationMS(time.Since(d.started)), outcome)
|
||||
}
|
||||
235
backend/internal/ai/laya_diagnostics_ticket32_test.go
Normal file
235
backend/internal/ai/laya_diagnostics_ticket32_test.go
Normal file
@ -0,0 +1,235 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
func ticket32Metrics(t *testing.T, output, prefix string) map[string]float64 {
|
||||
t.Helper()
|
||||
var found string
|
||||
for _, line := range strings.Split(output, "\n") {
|
||||
if i := strings.Index(line, prefix); i >= 0 {
|
||||
if found != "" {
|
||||
t.Fatal("duplicate diagnostic summary")
|
||||
}
|
||||
found = line[i+len(prefix):]
|
||||
}
|
||||
}
|
||||
if found == "" {
|
||||
t.Fatalf("missing %s diagnostics", prefix)
|
||||
}
|
||||
values := map[string]float64{}
|
||||
for _, field := range strings.Fields(found) {
|
||||
pair := strings.SplitN(field, "=", 2)
|
||||
if len(pair) != 2 {
|
||||
continue
|
||||
}
|
||||
if n, err := strconv.ParseFloat(pair[1], 64); err == nil {
|
||||
values[pair[0]] = n
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func TestTicket32DiagnosticsReportPlanAndActualAttemptsOnSuccessAndFailure(t *testing.T) {
|
||||
for _, failure := range []string{"", "timeout", "http", "invalid", "truncation", "read", "transport"} {
|
||||
t.Run(failure, func(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
previous := log.Writer()
|
||||
log.SetOutput(&logs)
|
||||
defer log.SetOutput(previous)
|
||||
ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://PRIVATE_URL.invalid", APIKey: "PRIVATE_API_KEY", BatchSize: 2, Timeout: 20 * time.Millisecond})
|
||||
calls := 0
|
||||
ranker.client = &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
var payload struct{ States []any }
|
||||
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls == 2 && failure == "transport" {
|
||||
return nil, errors.New("PRIVATE_TRANSPORT_URL_AND_SECRET")
|
||||
}
|
||||
if calls == 2 && failure == "timeout" {
|
||||
<-r.Context().Done()
|
||||
return nil, r.Context().Err()
|
||||
}
|
||||
status := 200
|
||||
if calls == 2 && failure == "http" {
|
||||
status = 503
|
||||
}
|
||||
results := []any{}
|
||||
for range payload.States {
|
||||
results = append(results, map[string]any{"answers": map[string]any{"relevance": map[string]any{"type": "score", "score": 0.2, "answer_confidence": 0.99}}, "usage": map[string]any{"truncated": calls == 2 && failure == "truncation"}})
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"results": results})
|
||||
if calls == 2 && failure == "invalid" {
|
||||
raw = []byte("PRIVATE_RESPONSE")
|
||||
}
|
||||
body := io.ReadCloser(io.NopCloser(bytes.NewReader(raw)))
|
||||
if calls == 2 && failure == "read" {
|
||||
body = ticket32BrokenBody{}
|
||||
}
|
||||
return &http.Response{StatusCode: status, Body: body, Header: make(http.Header)}, nil
|
||||
})}
|
||||
candidates := make([]generation.Candidate, 5)
|
||||
for i := range candidates {
|
||||
candidates[i] = generation.Candidate{ID: strconv.Itoa(i) + "PRIVATE_CANDIDATE_ID", SourceID: "PRIVATE_SOURCE_ID", Article: scraper.Article{Title: "PRIVATE_TITLE", Content: "PRIVATE_CONTENT", URL: "https://PRIVATE_ARTICLE_URL.invalid", Symbols: []string{"PRIVATE_ARTICLE_SYMBOL"}}}
|
||||
}
|
||||
opaque := "PRIVATE_COMPANY_ID"
|
||||
got, err := ranker.Rank(context.Background(), "title_content", []models.UserAsset{{ID: "PRIVATE_ASSET_ID", Name: "PRIVATE_NAME", Symbol: "PRIVATE_SYMBOL", CompanyID: &opaque}}, candidates)
|
||||
if (err != nil) != (failure != "") || (failure != "" && got != nil) {
|
||||
t.Fatalf("unexpected outcome: err=%v", err)
|
||||
}
|
||||
outcome := "success"
|
||||
if failure != "" {
|
||||
outcome = "failed"
|
||||
}
|
||||
if !strings.Contains(logs.String(), "outcome="+outcome) {
|
||||
t.Error("wrong diagnostic outcome")
|
||||
}
|
||||
plan := ticket32Metrics(t, logs.String(), "laya ranking plan ")
|
||||
summary := ticket32Metrics(t, logs.String(), "laya ranking diagnostics ")
|
||||
want := map[string]float64{"candidates": 5, "assets": 1, "states_planned": 5, "requests_planned": 3, "requests_sent": 3, "states_sent": 5, "batch_size_min": 1, "batch_size_max": 2, "batch_size_mean": 1.667, "requests_validated": 3}
|
||||
if failure != "" {
|
||||
want["requests_sent"] = 2
|
||||
want["states_sent"] = 4
|
||||
want["batch_size_min"] = 2
|
||||
want["batch_size_mean"] = 2
|
||||
want["requests_validated"] = 1
|
||||
}
|
||||
for key, value := range want {
|
||||
if summary[key] != value {
|
||||
t.Errorf("%s=%v want %v", key, summary[key], value)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"candidates", "assets", "states_planned", "requests_planned"} {
|
||||
if plan[key] != want[key] {
|
||||
t.Errorf("plan %s=%v want %v", key, plan[key], want[key])
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"request_duration_ms_min", "request_duration_ms_max", "request_duration_ms_mean", "request_duration_ms_total", "rank_duration_ms"} {
|
||||
if _, ok := summary[key]; !ok {
|
||||
t.Errorf("missing duration %s", key)
|
||||
}
|
||||
}
|
||||
if failure == "timeout" && summary["request_duration_ms_total"] < 1 {
|
||||
t.Error("timed-out request not measured")
|
||||
}
|
||||
for _, secret := range []string{"PRIVATE_", "private_", "http://", "https://"} {
|
||||
if strings.Contains(logs.String(), secret) {
|
||||
t.Fatal("sensitive log content")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type ticket32BrokenBody struct{}
|
||||
|
||||
func (ticket32BrokenBody) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
|
||||
func (ticket32BrokenBody) Close() error { return nil }
|
||||
|
||||
func TestTicket32ProductionShapedLongContentTimeoutAfterFifteenRequests(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
previous := log.Writer()
|
||||
log.SetOutput(&logs)
|
||||
defer log.SetOutput(previous)
|
||||
assets := make([]models.UserAsset, 30)
|
||||
for i := range assets {
|
||||
assets[i] = models.UserAsset{Name: "PRIVATE_COMPANY_NAME", Symbol: "PRIVATE_TICKER"}
|
||||
}
|
||||
candidates := make([]generation.Candidate, 233)
|
||||
for i := range candidates {
|
||||
candidates[i] = generation.Candidate{ID: strconv.Itoa(i), Article: scraper.Article{Title: "PRIVATE_TITLE", Content: strings.Repeat("PRIVATE_CONTENT ", 100)}}
|
||||
}
|
||||
ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://PRIVATE_URL.invalid", Timeout: time.Second})
|
||||
calls := 0
|
||||
ranker.client = &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if calls == 15 {
|
||||
<-r.Context().Done()
|
||||
return nil, r.Context().Err()
|
||||
}
|
||||
var payload struct{ States []any }
|
||||
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
results := make([]any, len(payload.States))
|
||||
for i := range results {
|
||||
results[i] = map[string]any{"answers": map[string]any{"relevance": map[string]any{"type": "score", "score": 0.2, "answer_confidence": 0.99}}, "usage": map[string]any{"truncated": false}}
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"results": results})
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(bytes.NewReader(raw)), Header: make(http.Header)}, nil
|
||||
})}
|
||||
got, err := ranker.Rank(context.Background(), "title_content", assets, candidates)
|
||||
if err == nil || err.Error() != "laya: timeout" || got != nil || calls != 15 {
|
||||
t.Fatalf("calls=%d err=%v", calls, err)
|
||||
}
|
||||
summary := ticket32Metrics(t, logs.String(), "laya ranking diagnostics ")
|
||||
for key, want := range map[string]float64{"candidates": 233, "assets": 30, "states_planned": 6990, "requests_planned": 110, "states_sent": 960, "requests_sent": 15, "requests_validated": 14, "batch_size_min": 64, "batch_size_max": 64, "batch_size_mean": 64} {
|
||||
if summary[key] != want {
|
||||
t.Errorf("%s=%v want=%v", key, summary[key], want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(logs.String(), "PRIVATE_") {
|
||||
t.Fatal("sensitive diagnostic")
|
||||
}
|
||||
t.Log("233 candidates / 30 assets, long content: planned 6990 states / 110 requests; timeout after 15 attempts / 960 states, 14 batches validated")
|
||||
}
|
||||
|
||||
func TestTicket32EmptyAndInvalidInputsHaveFiniteZeroAttemptMetrics(t *testing.T) {
|
||||
for _, mode := range []string{"title", "invalid"} {
|
||||
var logs bytes.Buffer
|
||||
previous := log.Writer()
|
||||
log.SetOutput(&logs)
|
||||
ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://fake.invalid"})
|
||||
_, err := ranker.Rank(context.Background(), mode, nil, nil)
|
||||
log.SetOutput(previous)
|
||||
if (mode == "invalid") != (err != nil) {
|
||||
t.Fatal("validation changed")
|
||||
}
|
||||
summary := ticket32Metrics(t, logs.String(), "laya ranking diagnostics ")
|
||||
for _, key := range []string{"states_planned", "states_sent", "requests_sent", "requests_validated", "batch_size_min", "batch_size_max", "batch_size_mean", "request_duration_ms_min", "request_duration_ms_max", "request_duration_ms_mean", "request_duration_ms_total"} {
|
||||
if summary[key] != 0 {
|
||||
t.Errorf("%s=%v", key, summary[key])
|
||||
}
|
||||
}
|
||||
if strings.Contains(logs.String(), "NaN") || strings.Contains(logs.String(), "Inf") {
|
||||
t.Fatal("invalid zero-attempt statistics")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket32DurationAndSizeAggregatesAreExact(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
previous := log.Writer()
|
||||
log.SetOutput(&logs)
|
||||
defer log.SetOutput(previous)
|
||||
d := layaDiagnostics{started: time.Now()}
|
||||
d.plan(81, 64)
|
||||
d.sending(64)
|
||||
d.finished(10 * time.Millisecond)
|
||||
d.sending(17)
|
||||
d.finished(30 * time.Millisecond)
|
||||
d.report(false)
|
||||
summary := ticket32Metrics(t, logs.String(), "laya ranking diagnostics ")
|
||||
for key, want := range map[string]float64{"batch_size_min": 17, "batch_size_max": 64, "batch_size_mean": 40.5, "request_duration_ms_min": 10, "request_duration_ms_max": 30, "request_duration_ms_mean": 20, "request_duration_ms_total": 40} {
|
||||
if summary[key] != want {
|
||||
t.Errorf("%s=%v want=%v", key, summary[key], want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -84,6 +84,8 @@ func unitValue(v *float64) bool {
|
||||
// Rank associates results by their documented input position, never by text or
|
||||
// model-supplied IDs. A single invalid result discards the whole operation.
|
||||
func (r *LayaHTTPRanker) Rank(ctx context.Context, mode string, assets []models.UserAsset, candidates []generation.Candidate) (result []generation.Candidate, rankErr error) {
|
||||
diagnostics := layaDiagnostics{candidates: len(candidates), assets: len(assets), started: time.Now()}
|
||||
defer func() { diagnostics.report(rankErr != nil) }()
|
||||
// Every returned adapter error below is constructed from fixed diagnostics
|
||||
// (plus numeric HTTP status), never raw transport errors or response bodies.
|
||||
defer func() {
|
||||
@ -155,6 +157,7 @@ func (r *LayaHTTPRanker) Rank(ctx context.Context, mode string, assets []models.
|
||||
}
|
||||
}
|
||||
|
||||
diagnostics.plan(len(tasks), r.batchSize)
|
||||
best := make([]float64, len(candidates))
|
||||
for i := range best {
|
||||
best[i] = math.Inf(1)
|
||||
@ -183,8 +186,11 @@ func (r *LayaHTTPRanker) Rank(ctx context.Context, mode string, assets []models.
|
||||
if r.key != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+r.key)
|
||||
}
|
||||
diagnostics.sending(len(states))
|
||||
requestStarted := time.Now()
|
||||
resp, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
diagnostics.finished(time.Since(requestStarted))
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
|
||||
return nil, errors.New("laya: timeout")
|
||||
}
|
||||
@ -195,11 +201,13 @@ func (r *LayaHTTPRanker) Rank(ctx context.Context, mode string, assets []models.
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
resp.Body.Close()
|
||||
diagnostics.finished(time.Since(requestStarted))
|
||||
return nil, fmt.Errorf("laya: HTTP status %d", resp.StatusCode)
|
||||
}
|
||||
// Bound decoding and reject a second JSON document or a truncated response.
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 4*1024*1024+1))
|
||||
resp.Body.Close()
|
||||
diagnostics.finished(time.Since(requestStarted))
|
||||
if err != nil {
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
|
||||
return nil, errors.New("laya: timeout")
|
||||
@ -240,6 +248,7 @@ func (r *LayaHTTPRanker) Rank(ctx context.Context, mode string, assets []models.
|
||||
best[tasks[start+i].article] = *answer.Score
|
||||
}
|
||||
}
|
||||
diagnostics.requestsValidated++
|
||||
}
|
||||
for i, candidate := range candidates {
|
||||
ranked = append(ranked, scored{candidate, best[i]})
|
||||
|
||||
Reference in New Issue
Block a user