feat(laya): add sanitized ranking diagnostics

This commit is contained in:
2026-11-23 22:26:32 +01:00
parent 5afcbf4a6e
commit dba845199b
4 changed files with 327 additions and 0 deletions

View File

@ -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]})