fix(ai): diagnose summary provider failures (#37)
This commit is contained in:
@ -60,7 +60,7 @@ func main() {
|
|||||||
models.SourceCNBCBusiness: cnbcbusiness.New(),
|
models.SourceCNBCBusiness: cnbcbusiness.New(),
|
||||||
}
|
}
|
||||||
|
|
||||||
app := server.New(repo, cfg, server.Dependencies{CompanyCatalog: catalog, LayaRanker: laya, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true})
|
app := server.New(repo, cfg, server.Dependencies{SummaryDiagnostics: ai.LogSummaryDiagnostic, CompanyCatalog: catalog, LayaRanker: laya, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true})
|
||||||
defer app.Close()
|
defer app.Close()
|
||||||
|
|
||||||
addr := fmt.Sprintf(":%s", cfg.Port)
|
addr := fmt.Sprintf(":%s", cfg.Port)
|
||||||
|
|||||||
@ -53,7 +53,7 @@ func (p *anthropicProvider) Summarize(ctx context.Context, prompt string, _ GenO
|
|||||||
|
|
||||||
raw, _ := io.ReadAll(resp.Body)
|
raw, _ := io.ReadAll(resp.Body)
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
return "", fmt.Errorf("anthropic API error %d: %s", resp.StatusCode, raw)
|
return "", &summaryHTTPError{status: resp.StatusCode, err: fmt.Errorf("anthropic API error %d: %s", resp.StatusCode, raw)}
|
||||||
}
|
}
|
||||||
|
|
||||||
var result struct {
|
var result struct {
|
||||||
|
|||||||
@ -53,7 +53,7 @@ func (p *geminiProvider) Summarize(ctx context.Context, prompt string, _ GenOpti
|
|||||||
|
|
||||||
raw, _ := io.ReadAll(resp.Body)
|
raw, _ := io.ReadAll(resp.Body)
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
return "", fmt.Errorf("gemini API error %d: %s", resp.StatusCode, raw)
|
return "", &summaryHTTPError{status: resp.StatusCode, err: fmt.Errorf("gemini API error %d: %s", resp.StatusCode, raw)}
|
||||||
}
|
}
|
||||||
|
|
||||||
var result struct {
|
var result struct {
|
||||||
|
|||||||
@ -5,6 +5,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/tradarr/backend/internal/companycatalog"
|
"github.com/tradarr/backend/internal/companycatalog"
|
||||||
|
"time"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
"github.com/tradarr/backend/internal/generation"
|
"github.com/tradarr/backend/internal/generation"
|
||||||
@ -42,11 +43,25 @@ func (a generationRanker) WithSelectionBudget(ctx context.Context) (context.Cont
|
|||||||
}
|
}
|
||||||
|
|
||||||
type generationSummarizer struct {
|
type generationSummarizer struct {
|
||||||
p *Pipeline
|
p *Pipeline
|
||||||
provider Provider
|
provider Provider
|
||||||
|
diagnostics SummaryDiagnosticCollector
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a generationSummarizer) Summarize(ctx context.Context, language string, assets []models.UserAsset, candidates []generation.Candidate) (string, error) {
|
func (a generationSummarizer) Summarize(ctx context.Context, language string, assets []models.UserAsset, candidates []generation.Candidate) (result string, summaryErr error) {
|
||||||
|
started := time.Now()
|
||||||
|
d := SummaryDiagnostic{ArticleCount: len(candidates), PromptBudgetBytes: 24 * 1024}
|
||||||
|
collector := a.diagnostics
|
||||||
|
if collector == nil && a.p != nil {
|
||||||
|
collector = a.p.summaryDiagnostics
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
if d.Category == "" {
|
||||||
|
classifySummaryDiagnostic(ctx, summaryErr, result, &d)
|
||||||
|
}
|
||||||
|
d.DurationMS = time.Since(started).Milliseconds()
|
||||||
|
emitSummaryDiagnostic(collector, d)
|
||||||
|
}()
|
||||||
provider := a.provider
|
provider := a.provider
|
||||||
if provider == nil {
|
if provider == nil {
|
||||||
return "", fmt.Errorf("summary_model_unavailable")
|
return "", fmt.Errorf("summary_model_unavailable")
|
||||||
@ -87,7 +102,9 @@ func (a generationSummarizer) Summarize(ctx context.Context, language string, as
|
|||||||
// slots for generation/framing in the conservative byte-token model.
|
// slots for generation/framing in the conservative byte-token model.
|
||||||
// Titles, candidate IDs, asset identities and article order are immutable.
|
// Titles, candidate IDs, asset identities and article order are immutable.
|
||||||
const promptByteBudget = 24 * 1024
|
const promptByteBudget = 24 * 1024
|
||||||
if len(build(0)) > promptByteBudget {
|
d.PromptBytes = len(build(0))
|
||||||
|
if d.PromptBytes > promptByteBudget {
|
||||||
|
d.Category = "metadata_budget_exceeded"
|
||||||
return "", fmt.Errorf("summary_prompt_metadata_exceeds_budget")
|
return "", fmt.Errorf("summary_prompt_metadata_exceeds_budget")
|
||||||
}
|
}
|
||||||
low, high := 0, promptByteBudget
|
low, high := 0, promptByteBudget
|
||||||
@ -100,6 +117,12 @@ func (a generationSummarizer) Summarize(ctx context.Context, language string, as
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
prompt := build(low)
|
prompt := build(low)
|
||||||
|
d.PromptBytes = len(prompt)
|
||||||
|
for _, article := range articles {
|
||||||
|
if article.ContentTruncated || len(utf8Prefix(article.Content, low)) < len(article.Content) {
|
||||||
|
d.TruncatedArticles++
|
||||||
|
}
|
||||||
|
}
|
||||||
if len(prompt) > promptByteBudget {
|
if len(prompt) > promptByteBudget {
|
||||||
return "", fmt.Errorf("summary_prompt_exceeds_budget")
|
return "", fmt.Errorf("summary_prompt_exceeds_budget")
|
||||||
}
|
}
|
||||||
|
|||||||
@ -82,7 +82,7 @@ func (p *OllamaProvider) Summarize(ctx context.Context, prompt string, opts GenO
|
|||||||
|
|
||||||
raw, _ := io.ReadAll(resp.Body)
|
raw, _ := io.ReadAll(resp.Body)
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
return "", fmt.Errorf("ollama API error %d: %s", resp.StatusCode, raw)
|
return "", &summaryHTTPError{status: resp.StatusCode, err: fmt.Errorf("ollama API error %d: %s", resp.StatusCode, raw)}
|
||||||
}
|
}
|
||||||
|
|
||||||
var result struct {
|
var result struct {
|
||||||
|
|||||||
@ -26,11 +26,12 @@ Structure ton résumé ainsi :
|
|||||||
4. **Synthèse** : points d'attention prioritaires pour la journée`
|
4. **Synthèse** : points d'attention prioritaires pour la journée`
|
||||||
|
|
||||||
type Pipeline struct {
|
type Pipeline struct {
|
||||||
generationUseCase generation.UseCase
|
summaryDiagnostics SummaryDiagnosticCollector
|
||||||
mentionNames generation.MentionNameResolver
|
generationUseCase generation.UseCase
|
||||||
repo *models.Repository
|
mentionNames generation.MentionNameResolver
|
||||||
enc *crypto.Encryptor
|
repo *models.Repository
|
||||||
generating atomic.Bool
|
enc *crypto.Encryptor
|
||||||
|
generating atomic.Bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPipeline(repo *models.Repository, enc *crypto.Encryptor) *Pipeline {
|
func NewPipeline(repo *models.Repository, enc *crypto.Encryptor) *Pipeline {
|
||||||
|
|||||||
110
backend/internal/ai/summary_diagnostics.go
Normal file
110
backend/internal/ai/summary_diagnostics.go
Normal file
@ -0,0 +1,110 @@
|
|||||||
|
package ai
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
openai "github.com/sashabaranov/go-openai"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SummaryDiagnostic contains only bounded categories and numeric aggregates.
|
||||||
|
// Never add model inputs, outputs, errors, identities or configuration here.
|
||||||
|
type SummaryDiagnostic struct {
|
||||||
|
Category string `json:"category"`
|
||||||
|
HTTPStatus int `json:"http_status"`
|
||||||
|
NetworkCategory string `json:"network_category"`
|
||||||
|
DurationMS int64 `json:"duration_ms"`
|
||||||
|
PromptBytes int `json:"prompt_bytes"`
|
||||||
|
PromptBudgetBytes int `json:"prompt_budget_bytes"`
|
||||||
|
ArticleCount int `json:"article_count"`
|
||||||
|
TruncatedArticles int `json:"truncated_articles"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SummaryDiagnosticCollector is optional. Install during composition, before use.
|
||||||
|
// Returned errors and panics are ignored; collectors should return promptly.
|
||||||
|
type SummaryDiagnosticCollector func(SummaryDiagnostic) error
|
||||||
|
|
||||||
|
func (p *Pipeline) SetSummaryDiagnosticCollector(collector SummaryDiagnosticCollector) {
|
||||||
|
p.summaryDiagnostics = collector
|
||||||
|
}
|
||||||
|
func emitSummaryDiagnostic(collector SummaryDiagnosticCollector, d SummaryDiagnostic) {
|
||||||
|
if collector == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer func() { _ = recover() }()
|
||||||
|
_ = collector(d)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LogSummaryDiagnostic is an explicit opt-in collector; it never receives an error.
|
||||||
|
func LogSummaryDiagnostic(d SummaryDiagnostic) error {
|
||||||
|
log.Printf("summary diagnostics category=%s http_status=%d network_category=%s duration_ms=%d prompt_bytes=%d prompt_budget_bytes=%d article_count=%d truncated_articles=%d", d.Category, d.HTTPStatus, d.NetworkCategory, d.DurationMS, d.PromptBytes, d.PromptBudgetBytes, d.ArticleCount, d.TruncatedArticles)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Preserve the original provider error and its chain, while exposing only status
|
||||||
|
// to diagnostics. Do not extract categories by parsing error messages/bodies.
|
||||||
|
type summaryHTTPError struct {
|
||||||
|
status int
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *summaryHTTPError) Error() string { return e.err.Error() }
|
||||||
|
func (e *summaryHTTPError) Unwrap() error { return e.err }
|
||||||
|
|
||||||
|
func classifySummaryDiagnostic(ctx context.Context, err error, result string, d *SummaryDiagnostic) {
|
||||||
|
var timeout interface{ Timeout() bool }
|
||||||
|
switch {
|
||||||
|
case errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded):
|
||||||
|
d.Category = "timeout"
|
||||||
|
return
|
||||||
|
case errors.Is(ctx.Err(), context.Canceled) || errors.Is(err, context.Canceled):
|
||||||
|
d.Category = "canceled"
|
||||||
|
return
|
||||||
|
case errors.As(err, &timeout) && timeout.Timeout():
|
||||||
|
d.Category = "timeout"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
d.Category = "success"
|
||||||
|
if strings.TrimSpace(result) == "" {
|
||||||
|
d.Category = "empty_response"
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
d.Category = "provider_response_error"
|
||||||
|
var local *summaryHTTPError
|
||||||
|
var api *openai.APIError
|
||||||
|
var request *openai.RequestError
|
||||||
|
status := 0
|
||||||
|
switch {
|
||||||
|
case errors.As(err, &local):
|
||||||
|
status = local.status
|
||||||
|
case errors.As(err, &api):
|
||||||
|
status = api.HTTPStatusCode
|
||||||
|
case errors.As(err, &request):
|
||||||
|
status = request.HTTPStatusCode
|
||||||
|
}
|
||||||
|
if status >= 100 && status <= 599 {
|
||||||
|
d.Category = "provider_http_error"
|
||||||
|
d.HTTPStatus = status
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var dns *net.DNSError
|
||||||
|
var op *net.OpError
|
||||||
|
var u *url.Error
|
||||||
|
switch {
|
||||||
|
case errors.As(err, &dns):
|
||||||
|
d.NetworkCategory = "dns"
|
||||||
|
case errors.As(err, &op):
|
||||||
|
d.NetworkCategory = "connection"
|
||||||
|
case errors.As(err, &u):
|
||||||
|
d.NetworkCategory = "transport"
|
||||||
|
}
|
||||||
|
if d.NetworkCategory != "" {
|
||||||
|
d.Category = "provider_http_error"
|
||||||
|
}
|
||||||
|
}
|
||||||
151
backend/internal/ai/summary_diagnostics_ticket37_test.go
Normal file
151
backend/internal/ai/summary_diagnostics_ticket37_test.go
Normal file
@ -0,0 +1,151 @@
|
|||||||
|
package ai
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
openai "github.com/sashabaranov/go-openai"
|
||||||
|
"github.com/tradarr/backend/internal/generation"
|
||||||
|
"github.com/tradarr/backend/internal/scraper"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTicket37TerminalDiagnosticsLocalTransport(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, category, network, body string
|
||||||
|
status int
|
||||||
|
err error
|
||||||
|
}{
|
||||||
|
{"success", "success", "", `{"response":"PRIVATE_RESULT"}`, 200, nil},
|
||||||
|
{"http", "provider_http_error", "", "PRIVATE_BODY", 429, nil},
|
||||||
|
{"response", "provider_response_error", "", "PRIVATE_BODY", 200, nil},
|
||||||
|
{"empty", "empty_response", "", `{"response":" "}`, 200, nil},
|
||||||
|
{"network", "provider_http_error", "transport", "", 0, &url.Error{URL: "https://PRIVATE_URL", Err: errors.New("PRIVATE_SECRET")}},
|
||||||
|
{"timeout", "timeout", "", "", 0, context.DeadlineExceeded},
|
||||||
|
{"canceled", "canceled", "", "", 0, context.Canceled},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
p := newOllama("https://PRIVATE_ENDPOINT", "PRIVATE_MODEL")
|
||||||
|
calls := 0
|
||||||
|
p.client = &http.Client{Transport: ticket31Transport(func(*http.Request) (*http.Response, error) {
|
||||||
|
calls++
|
||||||
|
if tc.err != nil {
|
||||||
|
return nil, tc.err
|
||||||
|
}
|
||||||
|
return &http.Response{StatusCode: tc.status, Header: http.Header{"PRIVATE_HEADER": []string{"PRIVATE_SECRET"}}, Body: io.NopCloser(strings.NewReader(tc.body))}, nil
|
||||||
|
})}
|
||||||
|
var events []SummaryDiagnostic
|
||||||
|
var logs bytes.Buffer
|
||||||
|
old := log.Writer()
|
||||||
|
log.SetOutput(&logs)
|
||||||
|
defer log.SetOutput(old)
|
||||||
|
a := generationSummarizer{provider: p, diagnostics: func(d SummaryDiagnostic) error { events = append(events, d); return LogSummaryDiagnostic(d) }}
|
||||||
|
result, err := a.Summarize(context.Background(), "fr", nil, []generation.Candidate{{ID: "PRIVATE_ID", Article: scraper.Article{Title: "PRIVATE_TITLE", Content: strings.Repeat("PRIVATE_CONTENT", 5000)}}})
|
||||||
|
if calls != 1 || len(events) != 1 {
|
||||||
|
t.Fatal("expected one event/request")
|
||||||
|
}
|
||||||
|
d := events[0]
|
||||||
|
status := 0
|
||||||
|
if tc.name == "http" {
|
||||||
|
status = 429
|
||||||
|
}
|
||||||
|
if d.Category != tc.category || d.HTTPStatus != status || d.NetworkCategory != tc.network || d.ArticleCount != 1 || d.PromptBytes <= 0 || d.PromptBytes > d.PromptBudgetBytes || d.PromptBudgetBytes != 24576 || d.TruncatedArticles != 1 || d.DurationMS < 0 {
|
||||||
|
t.Fatalf("safe diagnostic incorrect: %+v", d)
|
||||||
|
}
|
||||||
|
if (err != nil) != (tc.err != nil || tc.name == "http" || tc.name == "response") || (tc.name == "success" && result != "PRIVATE_RESULT") {
|
||||||
|
t.Fatal("provider behavior changed")
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(events)
|
||||||
|
if strings.Contains(string(raw)+logs.String(), "PRIVATE_") {
|
||||||
|
t.Fatal("sensitive diagnostic")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestTicket37MetadataAndCollectorIsolation(t *testing.T) {
|
||||||
|
p := &contentProvider{}
|
||||||
|
var events []SummaryDiagnostic
|
||||||
|
a := generationSummarizer{provider: p, diagnostics: func(d SummaryDiagnostic) error { events = append(events, d); return nil }}
|
||||||
|
_, err := a.Summarize(context.Background(), "fr", nil, []generation.Candidate{{Article: scraper.Article{Title: strings.Repeat("PRIVATE_TITLE", 3000)}}})
|
||||||
|
if err == nil || p.calls != 0 || len(events) != 1 || events[0].Category != "metadata_budget_exceeded" || events[0].PromptBytes <= 24576 {
|
||||||
|
t.Fatal("missing preflight diagnostic")
|
||||||
|
}
|
||||||
|
sentinel := errors.New("PRIVATE_ERROR")
|
||||||
|
for _, failure := range []string{"error", "panic", "nil"} {
|
||||||
|
for _, providerErr := range []error{nil, sentinel} {
|
||||||
|
provider := &incident37Provider{err: providerErr}
|
||||||
|
collector := SummaryDiagnosticCollector(func(SummaryDiagnostic) error {
|
||||||
|
if failure == "panic" {
|
||||||
|
panic("PRIVATE_PANIC")
|
||||||
|
}
|
||||||
|
return errors.New("PRIVATE_COLLECTOR")
|
||||||
|
})
|
||||||
|
if failure == "nil" {
|
||||||
|
collector = nil
|
||||||
|
}
|
||||||
|
got, e := (generationSummarizer{provider: provider, diagnostics: collector}).Summarize(context.Background(), "fr", nil, nil)
|
||||||
|
if e != providerErr || got != "synthetic synthesis" || provider.calls != 1 {
|
||||||
|
t.Fatal("collector changed provider outcome")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTicket37HTTPStatusAcrossProviderAdapters(t *testing.T) {
|
||||||
|
transport := ticket31Transport(func(*http.Request) (*http.Response, error) {
|
||||||
|
return &http.Response{StatusCode: 503, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"error":{"message":"PRIVATE_BODY","type":"PRIVATE_TYPE"}}`))}, nil
|
||||||
|
})
|
||||||
|
client := &http.Client{Transport: transport}
|
||||||
|
ollama := newOllama("https://PRIVATE_URL", "PRIVATE_MODEL")
|
||||||
|
ollama.client = client
|
||||||
|
anthropic := newAnthropic("PRIVATE_KEY", "PRIVATE_MODEL")
|
||||||
|
anthropic.client = client
|
||||||
|
gemini := newGemini("PRIVATE_KEY", "PRIVATE_MODEL")
|
||||||
|
gemini.client = client
|
||||||
|
cfg := openai.DefaultConfig("PRIVATE_KEY")
|
||||||
|
cfg.HTTPClient = client
|
||||||
|
oa := &openAIProvider{client: openai.NewClientWithConfig(cfg), model: "PRIVATE_MODEL"}
|
||||||
|
for _, p := range []Provider{ollama, anthropic, gemini, oa} {
|
||||||
|
t.Run(p.Name(), func(t *testing.T) {
|
||||||
|
events := []SummaryDiagnostic{}
|
||||||
|
_, err := (generationSummarizer{provider: p, diagnostics: func(d SummaryDiagnostic) error { events = append(events, d); return nil }}).Summarize(context.Background(), "fr", nil, nil)
|
||||||
|
if err == nil || len(events) != 1 || events[0].Category != "provider_http_error" || events[0].HTTPStatus != 503 {
|
||||||
|
t.Fatal("HTTP status lost")
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(events)
|
||||||
|
if strings.Contains(string(raw), "PRIVATE_") {
|
||||||
|
t.Fatal("provider data leaked")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTicket37PipelineCollectorAndDefaultSilence(t *testing.T) {
|
||||||
|
var logs bytes.Buffer
|
||||||
|
old := log.Writer()
|
||||||
|
log.SetOutput(&logs)
|
||||||
|
defer log.SetOutput(old)
|
||||||
|
pipeline := NewPipeline(nil, nil)
|
||||||
|
_, _ = (generationSummarizer{p: pipeline, provider: &contentProvider{}}).Summarize(context.Background(), "fr", nil, nil)
|
||||||
|
if logs.Len() != 0 {
|
||||||
|
t.Fatal("default diagnostic must be silent")
|
||||||
|
}
|
||||||
|
count := 0
|
||||||
|
pipeline.SetSummaryDiagnosticCollector(func(d SummaryDiagnostic) error {
|
||||||
|
count++
|
||||||
|
if d.Category != "success" {
|
||||||
|
t.Fatal("missing success")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
_, _ = (generationSummarizer{p: pipeline, provider: &contentProvider{}}).Summarize(context.Background(), "fr", nil, nil)
|
||||||
|
if count != 1 {
|
||||||
|
t.Fatal("pipeline collector not wired")
|
||||||
|
}
|
||||||
|
}
|
||||||
152
backend/internal/ai/summary_incident_ticket37_test.go
Normal file
152
backend/internal/ai/summary_incident_ticket37_test.go
Normal file
@ -0,0 +1,152 @@
|
|||||||
|
package ai
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/tradarr/backend/internal/generation"
|
||||||
|
"github.com/tradarr/backend/internal/models"
|
||||||
|
"github.com/tradarr/backend/internal/scraper"
|
||||||
|
)
|
||||||
|
|
||||||
|
type incident37Repo struct{ saved []generation.GenerationRecord }
|
||||||
|
|
||||||
|
func (*incident37Repo) LoadUserInput(context.Context, string) (generation.UserInput, error) {
|
||||||
|
key := models.SourceYahooFinance
|
||||||
|
return generation.UserInput{Language: "fr", RankingMode: "title_content", GlobalLimit: 90, Assets: []models.UserAsset{{Name: "Followed Company"}}, Sources: []models.Source{{ID: "s", SourceKey: &key, Enabled: true, ArticleLimit: 90}}}, nil
|
||||||
|
}
|
||||||
|
func (r *incident37Repo) SaveGeneration(_ context.Context, _ string, v generation.GenerationRecord) error {
|
||||||
|
r.saved = append(r.saved, v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type incident37Feed struct{ oversized bool }
|
||||||
|
|
||||||
|
func (incident37Feed) Name() string { return "fixture" }
|
||||||
|
func (f incident37Feed) Scrape(context.Context, []string) ([]scraper.Article, error) {
|
||||||
|
out := make([]scraper.Article, 90)
|
||||||
|
for i := range out {
|
||||||
|
title := fmt.Sprintf("PRIVATE_TITLE_%03d", i)
|
||||||
|
if f.oversized {
|
||||||
|
title += strings.Repeat("x", 500)
|
||||||
|
}
|
||||||
|
out[i] = scraper.Article{Title: title, URL: fmt.Sprintf("https://PRIVATE_URL.invalid/%d", i), Content: strings.Repeat("PRIVATE_CONTENT漢<&", 1024)}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type incident37Laya struct{ direct int }
|
||||||
|
|
||||||
|
func (d *incident37Laya) DecideMentions(_ context.Context, _, pass string, _ []models.UserAsset, c []generation.Candidate) ([]generation.Candidate, error) {
|
||||||
|
out := []generation.Candidate{}
|
||||||
|
if pass == generation.MentionDirect {
|
||||||
|
for _, v := range c {
|
||||||
|
if d.direct%3 != 0 {
|
||||||
|
out = append(out, v)
|
||||||
|
}
|
||||||
|
d.direct++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type incident37Provider struct {
|
||||||
|
contentProvider
|
||||||
|
err error
|
||||||
|
empty bool
|
||||||
|
options GenOptions
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *incident37Provider) Summarize(ctx context.Context, prompt string, opts GenOptions) (string, error) {
|
||||||
|
p.options = opts
|
||||||
|
result, _ := p.contentProvider.Summarize(ctx, prompt, opts)
|
||||||
|
if p.empty {
|
||||||
|
result = ""
|
||||||
|
}
|
||||||
|
return result, p.err
|
||||||
|
}
|
||||||
|
|
||||||
|
// This is an offline characterization, not a reconstruction of production's
|
||||||
|
// unknown provider response. All scenario labels and assertions are sanitized.
|
||||||
|
func TestTicket37NinetyCandidatesSixtySelectedSummary(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, code string
|
||||||
|
err error
|
||||||
|
oversized, empty bool
|
||||||
|
}{
|
||||||
|
{name: "success"},
|
||||||
|
{name: "provider_rejection", code: "summary_failed", err: errors.New("PRIVATE_BODY context limit PRIVATE_SECRET")},
|
||||||
|
{name: "timeout", code: "summary_timeout", err: fmt.Errorf("PRIVATE_BODY: %w", context.DeadlineExceeded)},
|
||||||
|
{name: "canceled", code: "summary_canceled", err: fmt.Errorf("PRIVATE_BODY: %w", context.Canceled)},
|
||||||
|
{name: "empty_response", code: "summary_failed", empty: true},
|
||||||
|
{name: "immutable_metadata_over_budget", code: "summary_failed", oversized: true},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
repo := &incident37Repo{}
|
||||||
|
laya := &incident37Laya{}
|
||||||
|
provider := &incident37Provider{err: tc.err, empty: tc.empty}
|
||||||
|
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, Decider: laya, Summarizer: generationSummarizer{provider: provider}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: incident37Feed{oversized: tc.oversized}}})
|
||||||
|
result, err := uc.Generate(context.Background(), "fixture")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("unexpected repository/use-case error")
|
||||||
|
}
|
||||||
|
o := result.Outcome
|
||||||
|
if o.TotalCandidates != 90 || o.LayaSelected != 60 || o.Selected != 60 || laya.direct != 90 {
|
||||||
|
t.Fatal("90 -> 60 -> 60 invariant broken")
|
||||||
|
}
|
||||||
|
if o.FailureCode != tc.code || (result.Summary != nil) != (tc.code == "") {
|
||||||
|
t.Fatal("incorrect terminal classification")
|
||||||
|
}
|
||||||
|
calls := 1
|
||||||
|
if tc.oversized {
|
||||||
|
calls = 0
|
||||||
|
}
|
||||||
|
if provider.calls != calls {
|
||||||
|
t.Fatal("unexpected provider call count or fallback")
|
||||||
|
}
|
||||||
|
if calls == 1 {
|
||||||
|
if len(provider.prompt) > 24*1024 || provider.options.NumCtx != 32768 {
|
||||||
|
t.Fatal("prompt budget/context contract broken")
|
||||||
|
}
|
||||||
|
var payload struct {
|
||||||
|
Articles []struct {
|
||||||
|
ID, Title, Content string
|
||||||
|
Truncated bool `json:"content_truncated"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
at := strings.Index(provider.prompt, "\n")
|
||||||
|
if at < 0 || json.Unmarshal([]byte(provider.prompt[at+1:]), &payload) != nil || len(payload.Articles) != 60 {
|
||||||
|
t.Fatal("invalid summary payload/count")
|
||||||
|
}
|
||||||
|
selected := 0
|
||||||
|
for i := 0; i < 90; i++ {
|
||||||
|
if i%3 == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
a := payload.Articles[selected]
|
||||||
|
if a.Title != fmt.Sprintf("PRIVATE_TITLE_%03d", i) || a.ID == "" || !a.Truncated || a.Content == "" {
|
||||||
|
t.Fatal("identity/order/excerpt contract broken")
|
||||||
|
}
|
||||||
|
selected++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(repo.saved) != 1 {
|
||||||
|
t.Fatal("terminal record missing")
|
||||||
|
}
|
||||||
|
raw, e := json.Marshal(repo.saved)
|
||||||
|
if e != nil {
|
||||||
|
t.Fatal("cannot encode terminal record")
|
||||||
|
}
|
||||||
|
for _, secret := range []string{"PRIVATE_TITLE", "PRIVATE_CONTENT", "PRIVATE_URL", "PRIVATE_BODY", "PRIVATE_SECRET"} {
|
||||||
|
if strings.Contains(string(raw), secret) {
|
||||||
|
t.Fatal("sensitive data persisted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Logf("candidates=90 laya_selected=60 selected=60 provider_calls=%d prompt_bytes=%d failure_code=%s", provider.calls, len(provider.prompt), o.FailureCode)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -19,12 +19,13 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Dependencies struct {
|
type Dependencies struct {
|
||||||
CompanyCatalog companycatalog.CompanyCatalog
|
SummaryDiagnostics ai.SummaryDiagnosticCollector
|
||||||
LayaRanker generation.LayaRanker
|
CompanyCatalog companycatalog.CompanyCatalog
|
||||||
Feeds map[string]scraper.Scraper
|
LayaRanker generation.LayaRanker
|
||||||
IndexSearcher indices.IndexSearcher
|
Feeds map[string]scraper.Scraper
|
||||||
GenerationFactory func(*ai.Pipeline) generation.UseCase
|
IndexSearcher indices.IndexSearcher
|
||||||
EnableScheduler bool
|
GenerationFactory func(*ai.Pipeline) generation.UseCase
|
||||||
|
EnableScheduler bool
|
||||||
}
|
}
|
||||||
type App struct {
|
type App struct {
|
||||||
Router *gin.Engine
|
Router *gin.Engine
|
||||||
@ -34,6 +35,7 @@ type App struct {
|
|||||||
func New(repo *models.Repository, cfg *config.Config, deps Dependencies) *App {
|
func New(repo *models.Repository, cfg *config.Config, deps Dependencies) *App {
|
||||||
enc := crypto.New(cfg.EncryptionKey)
|
enc := crypto.New(cfg.EncryptionKey)
|
||||||
pipeline := ai.NewPipeline(repo, enc)
|
pipeline := ai.NewPipeline(repo, enc)
|
||||||
|
pipeline.SetSummaryDiagnosticCollector(deps.SummaryDiagnostics)
|
||||||
if names, ok := deps.CompanyCatalog.(generation.MentionNameResolver); ok {
|
if names, ok := deps.CompanyCatalog.(generation.MentionNameResolver); ok {
|
||||||
pipeline.SetMentionNameResolver(names)
|
pipeline.SetMentionNameResolver(names)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user