137 lines
5.4 KiB
Go
137 lines
5.4 KiB
Go
package ai
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"github.com/tradarr/backend/internal/generation"
|
|
"github.com/tradarr/backend/internal/models"
|
|
"github.com/tradarr/backend/internal/scraper"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
type reliabilityRepo struct{ saved []generation.GenerationRecord }
|
|
|
|
func (r *reliabilityRepo) LoadUserInput(context.Context, string) (generation.UserInput, error) {
|
|
key := models.SourceBloomberg
|
|
return generation.UserInput{Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: &key, Enabled: true, ArticleLimit: 1}}}, nil
|
|
}
|
|
func (r *reliabilityRepo) SaveGeneration(ctx context.Context, _ string, record generation.GenerationRecord) error {
|
|
if ctx.Err() != nil {
|
|
return ctx.Err()
|
|
}
|
|
r.saved = append(r.saved, record)
|
|
return nil
|
|
}
|
|
|
|
type reliabilityFeed struct{}
|
|
|
|
func (reliabilityFeed) Name() string { return "fixture" }
|
|
func (reliabilityFeed) Scrape(context.Context, []string) ([]scraper.Article, error) {
|
|
return []scraper.Article{{Title: "Fixture Company"}}, nil
|
|
}
|
|
|
|
type reliabilityDecider struct{}
|
|
|
|
func (reliabilityDecider) DecideMentions(context.Context, string, string, []models.UserAsset, []generation.Candidate) ([]generation.Candidate, error) {
|
|
return nil, errors.New("unexpected ranking for exact mention")
|
|
}
|
|
|
|
func TestTicket35HTTPProviderFailureReachesSafeGenerationOutcome(t *testing.T) {
|
|
for _, kind := range []string{"timeout", "canceled", "provider"} {
|
|
t.Run(kind, func(t *testing.T) {
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
provider := newOllama("http://PRIVATE_URL.invalid", "fixture")
|
|
provider.client = &http.Client{Transport: ticket31Transport(func(*http.Request) (*http.Response, error) {
|
|
if kind == "timeout" {
|
|
return nil, &url.Error{URL: "http://PRIVATE_URL.invalid", Err: context.DeadlineExceeded}
|
|
}
|
|
if kind == "canceled" {
|
|
cancel()
|
|
return nil, context.Canceled
|
|
}
|
|
return &http.Response{StatusCode: 503, Body: io.NopCloser(strings.NewReader("PRIVATE_BODY PRIVATE_SECRET")), Header: make(http.Header)}, nil
|
|
})}
|
|
repo := &reliabilityRepo{}
|
|
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, Decider: reliabilityDecider{}, Summarizer: generationSummarizer{providerName: "gemini", model: "gemini-2.5-flash", provider: provider}, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: reliabilityFeed{}}})
|
|
r, err := uc.Generate(ctx, "fixture")
|
|
want := map[string]string{"timeout": "summary_timeout", "canceled": "summary_canceled", "provider": "summary_failed"}[kind]
|
|
if err != nil || r.Outcome.FailureCode != want || r.Summary != nil || len(repo.saved) != 1 {
|
|
t.Fatalf("code=%s err=%v", r.Outcome.FailureCode, err)
|
|
}
|
|
encoded, _ := json.Marshal(repo.saved)
|
|
if bytes.Contains(encoded, []byte("PRIVATE")) {
|
|
t.Fatal("raw provider error persisted")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
func TestTicket35RealAdapterKeepsFiveMinuteBudgetAcrossMentionPasses(t *testing.T) {
|
|
ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://fixture.invalid"})
|
|
ctx, cancel := ranker.WithSelectionBudget(context.Background())
|
|
defer cancel()
|
|
deadline, _ := ctx.Deadline()
|
|
calls := 0
|
|
ranker.client = &http.Client{Transport: ticket31Transport(func(req *http.Request) (*http.Response, error) {
|
|
calls++
|
|
actual, ok := req.Context().Deadline()
|
|
if !ok || !actual.Equal(deadline) || time.Until(actual) < 4*time.Minute+59*time.Second || time.Until(actual) > 5*time.Minute {
|
|
t.Fatal("shared default deadline changed")
|
|
}
|
|
var payload struct{ Questions map[string]any }
|
|
_ = json.NewDecoder(req.Body).Decode(&payload)
|
|
key := ""
|
|
for k := range payload.Questions {
|
|
key = k
|
|
}
|
|
raw := `{"results":[{"answers":{"` + key + `":{"type":"noul","noul":0.1,"answer_confidence":0.99}},"usage":{"truncated":false}}]}`
|
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(raw)), Header: make(http.Header)}, nil
|
|
})}
|
|
for _, pass := range []string{generation.MentionDirect, generation.MentionIndirect} {
|
|
got, err := ranker.DecideMentions(ctx, "title", pass, nil, []generation.Candidate{{ID: "fixture"}})
|
|
if err != nil || len(got) != 0 {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if calls != 2 {
|
|
t.Fatal(calls)
|
|
}
|
|
}
|
|
func TestTicket35ClaudeCLIErrorDoesNotExposeStdoutStderrOrRawError(t *testing.T) {
|
|
directory := t.TempDir()
|
|
binary := filepath.Join(directory, "claude")
|
|
if err := os.WriteFile(binary, []byte("#!/bin/sh\nprintf 'PRIVATE_STDOUT'\nprintf 'PRIVATE_STDERR' >&2\nexit 1\n"), 0700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", directory+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
reader, writer, err := os.Pipe()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
old := os.Stdout
|
|
os.Stdout = writer
|
|
t.Cleanup(func() { os.Stdout = old; reader.Close(); writer.Close() })
|
|
_, providerErr := newClaudeCode("fixture").Summarize(context.Background(), "PRIVATE_PROMPT", GenOptions{})
|
|
writer.Close()
|
|
os.Stdout = old
|
|
output, _ := io.ReadAll(reader)
|
|
if providerErr == nil || strings.Contains(providerErr.Error(), "PRIVATE") || bytes.Contains(output, []byte("PRIVATE")) {
|
|
t.Fatal("raw CLI diagnostics escaped")
|
|
}
|
|
canceled, cancel := context.WithCancel(context.Background())
|
|
cancel()
|
|
_, providerErr = newClaudeCode("fixture").Summarize(canceled, "fixture", GenOptions{})
|
|
if !errors.Is(providerErr, context.Canceled) {
|
|
t.Fatal("CLI cancellation identity lost")
|
|
}
|
|
}
|