feat(ai): test saved summary model generation (#43)

This commit is contained in:
2026-11-25 09:32:05 +01:00
parent 33dcc11aa5
commit a3738de516
27 changed files with 1595 additions and 43 deletions

View File

@ -26,6 +26,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/crypto"
"github.com/tradarr/backend/internal/database"
"github.com/tradarr/backend/internal/e2estack"
"github.com/tradarr/backend/internal/generation"
@ -113,7 +114,12 @@ func run(ctx context.Context) error {
provider := e2estack.FakeProvider{URL: fakeURL, Client: client}
gin.SetMode(gin.TestMode)
gin.DefaultWriter = io.Discard
app := server.New(repo, cfg, server.Dependencies{CompanyCatalog: e2estack.FakeCompanyCatalog{Fakes: fakes}, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{BaseURL: fakeURL}, client), EnableScheduler: false, GenerationFactory: func(p *ai.Pipeline) generation.UseCase {
probe := ai.NewModelTester(repo, crypto.New(cfg.EncryptionKey), func(_, _, model, _ string) (ai.Provider, error) {
selected := provider
selected.Model = model
return selected, nil
})
app := server.New(repo, cfg, server.Dependencies{ModelTester: probe, CompanyCatalog: e2estack.FakeCompanyCatalog{Fakes: fakes}, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{BaseURL: fakeURL}, client), EnableScheduler: false, GenerationFactory: func(p *ai.Pipeline) generation.UseCase {
return p.NewGenerationUseCaseWithFactory(feeds, e2estack.FakeLayaRanker{Provider: provider}, func(m models.ResolvedSummaryModel) (ai.Provider, error) {
selected := provider
selected.Model = m.Model

View File

@ -5,7 +5,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
@ -56,9 +55,9 @@ func (p *anthropicProvider) Summarize(ctx context.Context, prompt string, opts G
}
defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return "", &summaryHTTPError{status: resp.StatusCode, err: fmt.Errorf("anthropic API error %d: %s", resp.StatusCode, raw)}
raw, err := readGenerationResponse(resp)
if err != nil {
return "", err
}
var result struct {

View File

@ -3,9 +3,14 @@ package ai
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
type claudeCodeProvider struct {
@ -21,20 +26,76 @@ func newClaudeCode(model string) *claudeCodeProvider {
func (p *claudeCodeProvider) Name() string { return "claudecode" }
func (p *claudeCodeProvider) Summarize(ctx context.Context, prompt string, _ GenOptions) (string, error) {
var stdout, stderr bytes.Buffer
cmd := exec.CommandContext(ctx, "claude", "-p", prompt, "--model", p.model)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
// boundedCLICapture never writes model output to the process console and never
// returns silently truncated content as a successful generation.
type boundedCLICapture struct {
buffer bytes.Buffer
overflow bool
}
err := cmd.Run()
if err != nil {
if ctx.Err() != nil {
return "", ctx.Err()
func (b *boundedCLICapture) Write(p []byte) (int, error) {
remaining := maxGenerationResponseBytes - b.buffer.Len()
if len(p) > remaining {
b.overflow = true
}
if remaining > 0 {
b.buffer.Write(p[:min(len(p), remaining)])
}
return len(p), nil
}
func (p *claudeCodeProvider) Summarize(ctx context.Context, prompt string, opts GenOptions) (string, error) {
var stdout boundedCLICapture
testMode, _ := ctx.Value(modelTestContextKey{}).(bool)
args := []string{"-p", prompt, "--model", p.model}
if testMode {
args = append(args, "--output-format", "json", "--no-session-persistence")
}
cmd := exec.CommandContext(ctx, "claude", args...)
cmd.Stdout = &stdout
cmd.Stderr = io.Discard
cmd.WaitDelay = 250 * time.Millisecond
if testMode {
overrides := map[string]string{"CLAUDE_CODE_MAX_OUTPUT_TOKENS": strconv.Itoa(opts.MaxOutputTokens), "CLAUDE_CODE_MAX_RETRIES": "0", "CLAUDE_CODE_RETRY_WATCHDOG": "", "MAX_THINKING_TOKENS": "0"}
cmd.Env = []string{}
for _, entry := range os.Environ() {
key, _, _ := strings.Cut(entry, "=")
if _, replace := overrides[key]; !replace {
cmd.Env = append(cmd.Env, entry)
}
}
for key, value := range overrides {
cmd.Env = append(cmd.Env, key+"="+value)
}
}
err := cmd.Run()
if ctx.Err() != nil {
return "", ctx.Err()
}
if stdout.overflow {
return "", errors.New("claude cli: response unavailable")
}
if testMode {
raw := stdout.buffer.Bytes()
code := generationErrorCode(raw)
if code != "" {
return "", &summaryHTTPError{code: code, err: errors.New("claude cli: generation rejected")}
}
if err != nil {
return "", errors.New("claude cli: execution failed")
}
var envelope struct {
Type, Subtype, Result string
IsError *bool `json:"is_error"`
}
if json.Unmarshal(raw, &envelope) != nil || envelope.Type != "result" || envelope.Subtype != "success" || envelope.IsError == nil || *envelope.IsError {
return "", errors.New("claude cli: generation unavailable")
}
return strings.TrimSpace(envelope.Result), nil
}
if err != nil {
return "", errors.New("claude cli: execution failed")
}
return strings.TrimSpace(stdout.String()), nil
return strings.TrimSpace(stdout.buffer.String()), nil
}
func (p *claudeCodeProvider) ListModels(_ context.Context) ([]string, error) {

View File

@ -8,6 +8,7 @@ import (
"fmt"
"io"
"net/http"
neturl "net/url"
)
type geminiProvider struct {
@ -32,7 +33,7 @@ func (p *geminiProvider) Name() string { return "gemini" }
func (p *geminiProvider) Summarize(ctx context.Context, prompt string, opts GenOptions) (string, error) {
url := fmt.Sprintf(
"https://generativelanguage.googleapis.com/v1beta/models/%s:generateContent?key=%s",
p.model, p.apiKey,
neturl.PathEscape(p.model), neturl.QueryEscape(p.apiKey),
)
body := map[string]interface{}{
"contents": []map[string]interface{}{
@ -55,9 +56,9 @@ func (p *geminiProvider) Summarize(ctx context.Context, prompt string, opts GenO
}
defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return "", &summaryHTTPError{status: resp.StatusCode, err: fmt.Errorf("gemini API error %d: %s", resp.StatusCode, raw)}
raw, err := readGenerationResponse(resp)
if err != nil {
return "", err
}
var result struct {
@ -79,7 +80,7 @@ func (p *geminiProvider) Summarize(ctx context.Context, prompt string, opts GenO
}
func (p *geminiProvider) ListModels(ctx context.Context) ([]string, error) {
url := fmt.Sprintf("https://generativelanguage.googleapis.com/v1beta/models?key=%s", p.apiKey)
url := fmt.Sprintf("https://generativelanguage.googleapis.com/v1beta/models?key=%s", neturl.QueryEscape(p.apiKey))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err

View File

@ -0,0 +1,64 @@
package ai
import (
"encoding/json"
"errors"
"io"
"net/http"
"strings"
)
const maxGenerationResponseBytes = 2 << 20
type generationReadError struct{ cause error }
func (e *generationReadError) Error() string { return "provider generation response unavailable" }
func (e *generationReadError) Unwrap() error { return e.cause }
// Preserve only structured HTTP status and allowlisted error identifiers. Error
// messages and response bodies never become error strings or log arguments.
func readGenerationResponse(resp *http.Response) ([]byte, error) {
maximum := maxGenerationResponseBytes
if resp.StatusCode != http.StatusOK {
maximum = 64 << 10
}
raw, err := io.ReadAll(io.LimitReader(resp.Body, int64(maximum)+1))
if resp.StatusCode != http.StatusOK {
code := ""
if err == nil && len(raw) <= maximum {
code = generationErrorCode(raw)
}
return nil, &summaryHTTPError{status: resp.StatusCode, code: code, err: errors.New("provider generation rejected")}
}
if err != nil {
return nil, &generationReadError{cause: err}
}
if len(raw) > maximum {
return nil, errors.New("provider generation response unavailable")
}
return raw, nil
}
func generationErrorCode(raw []byte) string {
var payload struct {
Error struct {
Code any `json:"code"`
Type, Status string
Details []struct{ Reason string }
}
}
if json.Unmarshal(raw, &payload) != nil {
return ""
}
code, _ := payload.Error.Code.(string)
values := []string{code, payload.Error.Type, payload.Error.Status}
for _, detail := range payload.Error.Details {
values = append(values, detail.Reason)
}
for _, value := range values {
switch code := strings.ToLower(value); code {
case "invalid_api_key", "authentication_error", "permission_denied", "unauthenticated", "api_key_invalid", "api_key_expired", "model_not_found", "not_found_error", "not_found", "rate_limit_error", "rate_limit_exceeded", "resource_exhausted", "deadline_exceeded", "timeout_error":
return code
}
}
return ""
}

View File

@ -0,0 +1,127 @@
package ai
import (
"context"
"encoding/json"
openai "github.com/sashabaranov/go-openai"
"io"
"net/http"
"strings"
"testing"
)
func TestTicket43OllamaSmallGenerationHasExplicitOutputLimit(t *testing.T) {
p := newOllama("https://fixture.invalid", "exact-saved-model")
calls := 0
p.client = &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
calls++
var body struct {
Model, Prompt string
Options map[string]int
}
if json.NewDecoder(r.Body).Decode(&body) != nil || body.Model != "exact-saved-model" || body.Prompt != modelTestPrompt || body.Options["num_predict"] != modelTestMaxOutputTokens {
t.Error("Ollama test call omitted the fixed output cap or exact saved model")
}
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"response":"OK"}`))}, nil
})}
if _, err := p.Summarize(context.Background(), modelTestPrompt, GenOptions{MaxOutputTokens: modelTestMaxOutputTokens}); err != nil || calls != 1 {
t.Fatal("small generation retried or failed")
}
}
func TestTicket43AdapterStructuredErrorCodesAndRawBodiesAreNotExposed(t *testing.T) {
for _, tc := range []struct {
name, body string
want error
}{
{"anthropic", `{"error":{"type":"authentication_error","message":"PRIVATE_BODY"}}`, ErrModelTestAuth},
{"gemini", `{"error":{"status":"RESOURCE_EXHAUSTED","message":"PRIVATE_BODY"}}`, ErrModelTestRateLimited},
{"ollama", `{"error":{"code":"model_not_found","message":"PRIVATE_BODY"}}`, ErrModelTestModelUnavailable},
} {
t.Run(tc.name, func(t *testing.T) {
client := &http.Client{Transport: ticket31Transport(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: 400, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(tc.body))}, nil
})}
var provider Provider
switch tc.name {
case "anthropic":
p := newAnthropic("PRIVATE_KEY", "exact")
p.client = client
provider = p
case "gemini":
p := newGemini("PRIVATE_KEY", "exact")
p.client = client
provider = p
case "ollama":
p := newOllama("https://PRIVATE_ENDPOINT", "exact")
p.client = client
provider = p
}
_, err := provider.Summarize(context.Background(), modelTestPrompt, GenOptions{MaxOutputTokens: modelTestMaxOutputTokens})
if err == nil || strings.Contains(err.Error(), "PRIVATE") || classifyModelTestError(err) != tc.want {
t.Error("structured adapter rejection lost its category or exposed raw response")
}
})
}
}
func TestTicket43HTTPGenerationAdaptersUseExactModelCredentialsAndSmallOutput(t *testing.T) {
for _, name := range []string{"openai", "anthropic", "gemini", "ollama"} {
t.Run(name, func(t *testing.T) {
const key = "PRIVATE_KEY+&"
calls := 0
client := &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
calls++
var body map[string]any
if r.Method != "POST" || json.NewDecoder(r.Body).Decode(&body) != nil {
t.Error("generation was replaced by discovery")
}
response := ""
switch name {
case "openai":
if body["model"] != "exact-saved-model" || body["max_tokens"] != float64(modelTestMaxOutputTokens) || r.Header.Get("Authorization") != "Bearer "+key {
t.Error("OpenAI generation configuration changed")
}
response = `{"choices":[{"message":{"role":"assistant","content":"OK"}}]}`
case "anthropic":
if body["model"] != "exact-saved-model" || body["max_tokens"] != float64(modelTestMaxOutputTokens) || r.Header.Get("x-api-key") != key {
t.Error("Anthropic generation configuration changed")
}
response = `{"content":[{"type":"text","text":"OK"}]}`
case "gemini":
config, _ := body["generationConfig"].(map[string]any)
if !strings.HasSuffix(r.URL.Path, "/models/exact-saved-model:generateContent") || r.URL.Query().Get("key") != key || config["maxOutputTokens"] != float64(modelTestMaxOutputTokens) {
t.Error("Gemini generation configuration changed")
}
response = `{"candidates":[{"content":{"parts":[{"text":"OK"}]}}]}`
case "ollama":
config, _ := body["options"].(map[string]any)
if body["model"] != "exact-saved-model" || r.URL.Host != "saved-fixture.invalid" || config["num_predict"] != float64(modelTestMaxOutputTokens) {
t.Error("Ollama generation configuration changed")
}
response = `{"response":"OK"}`
}
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(response))}, nil
})}
provider, err := NewProvider(name, key, "exact-saved-model", "https://saved-fixture.invalid")
if err != nil {
t.Fatal(err)
}
switch p := provider.(type) {
case *openAIProvider:
cfg := openai.DefaultConfig(key)
cfg.HTTPClient = client
p.client = openai.NewClientWithConfig(cfg)
case *anthropicProvider:
p.client = client
case *geminiProvider:
p.client = client
case *OllamaProvider:
p.client = client
}
response, err := provider.Summarize(context.Background(), modelTestPrompt, GenOptions{MaxOutputTokens: modelTestMaxOutputTokens, NumCtx: 2048})
if err != nil || response != "OK" || calls != 1 {
t.Fatal("exact-model generation failed or retried")
}
})
}
}

View File

@ -0,0 +1,51 @@
package ai
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
)
func TestTicket43ClaudeModelTestUsesStructuredNonemptyResultAndBoundedChildOptions(t *testing.T) {
directory := t.TempDir()
script := `#!/bin/sh
[ "$CLAUDE_CODE_MAX_OUTPUT_TOKENS" = 16 ] || exit 1
[ "$CLAUDE_CODE_MAX_RETRIES" = 0 ] || exit 1
[ -z "$CLAUDE_CODE_RETRY_WATCHDOG" ] || exit 1
case " $* " in *" --output-format json "*) ;; *) exit 1;; esac
case " $* " in *" --no-session-persistence "*) ;; *) exit 1;; esac
printf '%s' '{"type":"result","subtype":"success","is_error":false,"result":"PRIVATE_GENERATED_RESULT"}'
printf '%s' 'PRIVATE_STDERR' >&2
`
if err := os.WriteFile(filepath.Join(directory, "claude"), []byte(script), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", directory+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("CLAUDE_CODE_MAX_OUTPUT_TOKENS", "9999")
t.Setenv("CLAUDE_CODE_MAX_RETRIES", "10")
t.Setenv("CLAUDE_CODE_RETRY_WATCHDOG", "1")
// Use the same marked context as the admin test service.
ctx := context.WithValue(context.Background(), modelTestContextKey{}, true)
response, err := newClaudeCode("exact-saved-model").Summarize(ctx, modelTestPrompt, GenOptions{MaxOutputTokens: modelTestMaxOutputTokens})
if err != nil || response != "PRIVATE_GENERATED_RESULT" {
t.Fatal("CLI test options or structured generation result missing")
}
}
func TestTicket43ClaudeErrorEnvelopeCannotBecomeSuccessfulGeneratedText(t *testing.T) {
directory := t.TempDir()
script := `#!/bin/sh
printf '%s' '{"type":"result","subtype":"error_during_execution","is_error":true,"result":"PRIVATE_ERROR_TEXT"}'
printf '%s' 'PRIVATE_STDERR' >&2
`
if err := os.WriteFile(filepath.Join(directory, "claude"), []byte(script), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", directory+string(os.PathListSeparator)+os.Getenv("PATH"))
ctx := context.WithValue(context.Background(), modelTestContextKey{}, true)
response, err := newClaudeCode("exact").Summarize(ctx, modelTestPrompt, GenOptions{MaxOutputTokens: modelTestMaxOutputTokens})
if err == nil || response != "" || strings.Contains(err.Error(), "PRIVATE") {
t.Fatal("CLI error envelope leaked or became generated content")
}
}

View File

@ -0,0 +1,121 @@
package ai
import (
"context"
"errors"
"github.com/tradarr/backend/internal/models"
"testing"
"time"
)
func TestTicket43ProviderLockSpansModelsAndDifferentProvidersRemainIndependent(t *testing.T) {
started, finish := make(chan struct{}), make(chan struct{})
provider := &model43Provider{generate: func(context.Context, string, GenOptions) (string, error) { close(started); <-finish; return "OK", nil }}
repo := model43Repo(func(_ context.Context, id string) (models.ResolvedSummaryModel, error) {
pid := "shared"
if id == "other" {
pid = "independent"
}
return models.ResolvedSummaryModel{ID: id, ProviderID: pid, Provider: "ollama", Model: id}, nil
})
builds := 0
service := NewModelTester(repo, nil, func(_, _, model, _ string) (Provider, error) {
builds++
if model == "other" {
return &model43Provider{generate: func(context.Context, string, GenOptions) (string, error) { return "OK", nil }}, nil
}
return provider, nil
})
done := make(chan error, 1)
go func() { done <- service.Test(context.Background(), "first") }()
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("first generation did not start")
}
if err := service.Test(context.Background(), "second"); !errors.Is(err, ErrModelTestBusy) {
t.Error("same-provider model test was not rejected")
}
if err := service.Test(context.Background(), "other"); err != nil {
t.Error("independent provider was blocked")
}
close(finish)
if err := <-done; err != nil || builds != 2 {
t.Fatal("provider lock retried or failed")
}
if err := service.Test(context.Background(), "other"); err != nil {
t.Fatal("completed lock was retained")
}
}
func TestTicket43TimeoutReturnsPromptlyButKeepsProviderLockedUntilCallExits(t *testing.T) {
started, finish := make(chan struct{}), make(chan struct{})
service := NewModelTester(model43Repo(func(_ context.Context, id string) (models.ResolvedSummaryModel, error) {
return models.ResolvedSummaryModel{ID: id, ProviderID: "p", Provider: "ollama", Model: id}, nil
}), nil, func(string, string, string, string) (Provider, error) {
return &model43Provider{generate: func(context.Context, string, GenOptions) (string, error) {
close(started)
<-finish
return "late output", nil
}}, nil
})
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
done := make(chan error, 1)
go func() { done <- service.Test(ctx, "m") }()
select {
case <-started:
case <-time.After(time.Second):
close(finish)
t.Fatal("generation did not start")
}
select {
case err := <-done:
if !errors.Is(err, ErrModelTestTimeout) {
t.Error("deadline not classified")
}
case <-time.After(time.Second):
close(finish)
t.Fatal("HTTP-level call ignored deadline")
}
if err := service.Test(context.Background(), "other-model"); !errors.Is(err, ErrModelTestBusy) {
t.Error("timeout released a still-running provider")
}
close(finish)
// Wait on the lock itself, without launching another generation or retry.
deadline := time.Now().Add(time.Second)
for {
service.mu.Lock()
busy := service.busy["p"]
service.mu.Unlock()
if !busy {
break
}
if time.Now().After(deadline) {
t.Fatal("finished provider lock leaked")
}
time.Sleep(time.Millisecond)
}
}
func TestTicket43FailuresAndPanicsReleaseProviderLockWithoutLeakingMessages(t *testing.T) {
for _, failure := range []string{"decrypt", "factory", "provider panic"} {
t.Run(failure, func(t *testing.T) {
service := NewModelTester(model43Repo(func(_ context.Context, id string) (models.ResolvedSummaryModel, error) {
cipher := ""
if failure == "decrypt" {
cipher = "PRIVATE_CIPHER"
}
return models.ResolvedSummaryModel{ID: id, ProviderID: "p", Provider: "ollama", Model: id, APIKeyEncrypted: cipher}, nil
}), model43Decrypt(func(string) (string, error) { return "", errors.New("PRIVATE_DECRYPT") }), func(string, string, string, string) (Provider, error) {
if failure == "factory" {
return nil, errors.New("PRIVATE_FACTORY")
}
return &model43Provider{generate: func(context.Context, string, GenOptions) (string, error) { panic("PRIVATE_PANIC") }}, nil
})
for i := 0; i < 2; i++ {
if err := service.Test(context.Background(), "m"); !errors.Is(err, ErrModelTestLocal) {
t.Fatal("local failure leaked or lock was retained")
}
}
})
}
}

View File

@ -0,0 +1,193 @@
package ai
import (
"context"
"database/sql"
"errors"
openai "github.com/sashabaranov/go-openai"
"github.com/tradarr/backend/internal/models"
"strings"
"sync"
"time"
)
var (
ErrModelTestEmpty = errors.New("empty_response")
ErrModelTestAuth = errors.New("auth_rejected")
ErrModelTestModelUnavailable = errors.New("model_unavailable")
ErrModelTestRateLimited = errors.New("rate_limited")
ErrModelTestTimeout = errors.New("timeout")
ErrModelTestUnavailable = errors.New("unavailable")
ErrModelTestNotFound = errors.New("catalog_model_not_found")
ErrModelTestBusy = errors.New("provider_test_busy")
ErrModelTestLocal = errors.New("model_test_local_failure")
)
const modelTestPrompt = "Reply with OK."
const modelTestMaxOutputTokens = 16
const modelTestTimeout = 30 * time.Second
type modelTestContextKey struct{}
type ModelTestRepository interface {
GetSummaryModelForTest(context.Context, string) (models.ResolvedSummaryModel, error)
}
type ModelProviderFactory func(name, key, model, endpoint string) (Provider, error)
type ModelTester struct {
repo ModelTestRepository
enc ConnectionDecryptor
build ModelProviderFactory
mu sync.Mutex
busy map[string]bool
}
func NewModelTester(repo ModelTestRepository, enc ConnectionDecryptor, build ModelProviderFactory) *ModelTester {
if build == nil {
build = NewProvider
}
return &ModelTester{repo: repo, enc: enc, build: build, busy: map[string]bool{}}
}
// Test runs against a saved catalogue snapshot, never user test parameters.
// It is a single shared service per HTTP server; locks are keyed by provider ID.
func (t *ModelTester) Test(parent context.Context, id string) (err error) {
defer func() {
if recover() != nil {
err = ErrModelTestLocal
}
}()
ctx, cancel := context.WithTimeout(parent, modelTestTimeout)
defer cancel()
ctx = context.WithValue(ctx, modelTestContextKey{}, true)
model, err := t.repo.GetSummaryModelForTest(ctx, id)
if ctx.Err() != nil {
return modelTestContextError(ctx.Err())
}
if errors.Is(err, sql.ErrNoRows) {
return ErrModelTestNotFound
}
if err != nil {
return ErrModelTestLocal
}
if model.ID == "" || model.ProviderID == "" || strings.TrimSpace(model.Provider) == "" || strings.TrimSpace(model.Model) == "" {
return ErrModelTestLocal
}
t.mu.Lock()
if t.busy[model.ProviderID] {
t.mu.Unlock()
return ErrModelTestBusy
}
t.busy[model.ProviderID] = true
t.mu.Unlock()
var once sync.Once
release := func() { once.Do(func() { t.mu.Lock(); delete(t.busy, model.ProviderID); t.mu.Unlock() }) }
handedOff := false
defer func() {
if !handedOff {
release()
}
}()
key := ""
if model.APIKeyEncrypted != "" {
if t.enc == nil {
return ErrModelTestLocal
}
key, err = t.enc.Decrypt(model.APIKeyEncrypted)
if err != nil {
return ErrModelTestLocal
}
}
provider, err := t.build(model.Provider, key, model.Model, model.Endpoint)
if err != nil || provider == nil {
return ErrModelTestLocal
}
if ctx.Err() != nil {
return modelTestContextError(ctx.Err())
}
done := make(chan error, 1)
handedOff = true
go func() {
outcome := runModelTestGeneration(ctx, provider)
// Keep a timed-out provider locked until its actual call exits. A provider
// ignoring cancellation must not permit a second concurrent generation.
release()
done <- outcome
}()
select {
case <-ctx.Done():
return modelTestContextError(ctx.Err())
case outcome := <-done:
if ctx.Err() != nil {
return modelTestContextError(ctx.Err())
}
return outcome
}
}
func runModelTestGeneration(ctx context.Context, provider Provider) (err error) {
defer func() {
if recover() != nil {
err = ErrModelTestLocal
}
}()
response, err := provider.Summarize(ctx, modelTestPrompt, GenOptions{MaxOutputTokens: modelTestMaxOutputTokens, NumCtx: 2048})
if ctx.Err() != nil {
return modelTestContextError(ctx.Err())
}
if err != nil {
return classifyModelTestError(err)
}
if strings.TrimSpace(response) == "" {
return ErrModelTestEmpty
}
return nil
}
func modelTestContextError(err error) error {
if errors.Is(err, context.DeadlineExceeded) {
return ErrModelTestTimeout
}
return ErrModelTestUnavailable
}
func classifyModelTestError(err error) error {
var timeout interface{ Timeout() bool }
if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &timeout) && timeout.Timeout()) {
return ErrModelTestTimeout
}
status, code := 0, ""
var local *summaryHTTPError
var api *openai.APIError
var request *openai.RequestError
switch {
case errors.As(err, &local):
status = local.status
code = local.code
case errors.As(err, &api):
status = api.HTTPStatusCode
code, _ = api.Code.(string)
if code == "" {
code = api.Type
}
case errors.As(err, &request):
status = request.HTTPStatusCode
}
switch status {
case 401, 403:
return ErrModelTestAuth
case 404, 410:
return ErrModelTestModelUnavailable
case 429:
return ErrModelTestRateLimited
case 408, 504:
return ErrModelTestTimeout
}
switch strings.ToLower(code) {
case "invalid_api_key", "authentication_error", "permission_denied", "unauthenticated", "api_key_invalid", "api_key_expired":
return ErrModelTestAuth
case "model_not_found", "not_found_error", "not_found":
return ErrModelTestModelUnavailable
case "rate_limit_error", "rate_limit_exceeded", "resource_exhausted":
return ErrModelTestRateLimited
case "deadline_exceeded", "timeout_error":
return ErrModelTestTimeout
}
return ErrModelTestUnavailable
}

View File

@ -0,0 +1,117 @@
package ai
import (
"bytes"
"context"
"database/sql"
"errors"
"fmt"
"log"
"testing"
"time"
openai "github.com/sashabaranov/go-openai"
"github.com/tradarr/backend/internal/models"
)
type model43Repo func(context.Context, string) (models.ResolvedSummaryModel, error)
func (f model43Repo) GetSummaryModelForTest(ctx context.Context, id string) (models.ResolvedSummaryModel, error) {
return f(ctx, id)
}
type model43Decrypt func(string) (string, error)
func (f model43Decrypt) Decrypt(value string) (string, error) { return f(value) }
type model43Provider struct {
generate func(context.Context, string, GenOptions) (string, error)
calls, discoveries int
}
func (*model43Provider) Name() string { return "fixture" }
func (p *model43Provider) ListModels(context.Context) ([]string, error) {
p.discoveries++
return nil, errors.New("discovery must not run")
}
func (p *model43Provider) Summarize(ctx context.Context, prompt string, opts GenOptions) (string, error) {
p.calls++
return p.generate(ctx, prompt, opts)
}
func TestTicket43ModelTestUsesExactSavedConfigurationAndStructuredOutcomes(t *testing.T) {
for _, tc := range []struct {
name, response string
upstream, want error
}{
{name: "success", response: " PRIVATE_GENERATED_TEXT "},
{name: "empty", response: " \t\n\u2003", want: ErrModelTestEmpty},
{name: "auth", upstream: &openai.APIError{HTTPStatusCode: 401, Message: "PRIVATE_BODY"}, want: ErrModelTestAuth},
{name: "forbidden", upstream: &openai.RequestError{HTTPStatusCode: 403}, want: ErrModelTestAuth},
{name: "missing", upstream: &openai.APIError{HTTPStatusCode: 404}, want: ErrModelTestModelUnavailable},
{name: "missing structured code", upstream: &openai.APIError{HTTPStatusCode: 400, Code: "model_not_found"}, want: ErrModelTestModelUnavailable},
{name: "limited", upstream: fmt.Errorf("PRIVATE: %w", &openai.APIError{HTTPStatusCode: 429}), want: ErrModelTestRateLimited},
{name: "unavailable", upstream: &summaryHTTPError{status: 503, err: errors.New("PRIVATE_BODY")}, want: ErrModelTestUnavailable},
{name: "HTTP timeout", upstream: &summaryHTTPError{status: 504, err: errors.New("PRIVATE_BODY")}, want: ErrModelTestTimeout},
{name: "deadline", upstream: context.DeadlineExceeded, want: ErrModelTestTimeout},
{name: "untrusted text", upstream: errors.New("401 429 model_not_found PRIVATE_SECRET https://private.invalid"), want: ErrModelTestUnavailable},
{name: "error wins over output", response: "PRIVATE_OUTPUT", upstream: errors.New("PRIVATE_ERROR"), want: ErrModelTestUnavailable},
} {
t.Run(tc.name, func(t *testing.T) {
var logs bytes.Buffer
old := log.Writer()
log.SetOutput(&logs)
defer log.SetOutput(old)
provider := &model43Provider{generate: func(ctx context.Context, prompt string, opts GenOptions) (string, error) {
deadline, ok := ctx.Deadline()
remaining := time.Until(deadline)
if !ok || remaining > 30*time.Second || remaining < 29*time.Second || prompt != modelTestPrompt || len(prompt) > 64 || opts.MaxOutputTokens != modelTestMaxOutputTokens || opts.Think || opts.JSONMode {
t.Error("fixed generation options or 30s deadline missing")
}
return tc.response, tc.upstream
}}
builds, decrypts := 0, 0
service := NewModelTester(model43Repo(func(_ context.Context, id string) (models.ResolvedSummaryModel, error) {
if id != "saved-id" {
t.Error("wrong catalogue entry")
}
return models.ResolvedSummaryModel{ID: id, ProviderID: "saved-provider", Provider: "ollama", Model: "exact-disabled-model", Endpoint: "https://PRIVATE_ENDPOINT", APIKeyEncrypted: "PRIVATE_CIPHER"}, nil
}), model43Decrypt(func(cipher string) (string, error) {
decrypts++
if cipher != "PRIVATE_CIPHER" {
t.Error("wrong encrypted key")
}
return "PRIVATE_KEY", nil
}), func(name, key, model, endpoint string) (Provider, error) {
builds++
if name != "ollama" || key != "PRIVATE_KEY" || model != "exact-disabled-model" || endpoint != "https://PRIVATE_ENDPOINT" {
t.Error("factory did not receive exact saved configuration")
}
return provider, nil
})
err := service.Test(context.Background(), "saved-id")
if !errors.Is(err, tc.want) || builds != 1 || decrypts != 1 || provider.calls != 1 || provider.discoveries != 0 || logs.Len() != 0 {
t.Fatalf("model test contract failed: calls=%d builds=%d decrypts=%d discovery=%d", provider.calls, builds, decrypts, provider.discoveries)
}
})
}
}
func TestTicket43ModelTestLocalFailuresAreSanitizedWithoutGeneration(t *testing.T) {
for _, tc := range []struct {
name string
model models.ResolvedSummaryModel
repoErr error
want error
}{
{name: "unknown", repoErr: sql.ErrNoRows, want: ErrModelTestNotFound},
{name: "database", repoErr: errors.New("PRIVATE_DATABASE_ENDPOINT"), want: ErrModelTestLocal},
{name: "blank model", model: models.ResolvedSummaryModel{ID: "m", ProviderID: "p", Provider: "ollama", Model: " "}, want: ErrModelTestLocal},
} {
t.Run(tc.name, func(t *testing.T) {
builds := 0
service := NewModelTester(model43Repo(func(context.Context, string) (models.ResolvedSummaryModel, error) { return tc.model, tc.repoErr }), nil, func(string, string, string, string) (Provider, error) { builds++; return nil, errors.New("PRIVATE") })
if err := service.Test(context.Background(), "m"); !errors.Is(err, tc.want) || builds != 0 {
t.Fatal("local failure escaped or reached generation")
}
})
}
}

View File

@ -64,6 +64,9 @@ func (p *OllamaProvider) Summarize(ctx context.Context, prompt string, opts GenO
"num_ctx": numCtx,
},
}
if opts.MaxOutputTokens > 0 {
body["options"].(map[string]interface{})["num_predict"] = opts.MaxOutputTokens
}
if opts.JSONMode {
body["format"] = "json"
}
@ -80,9 +83,9 @@ func (p *OllamaProvider) Summarize(ctx context.Context, prompt string, opts GenO
}
defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return "", &summaryHTTPError{status: resp.StatusCode, err: fmt.Errorf("ollama API error %d: %s", resp.StatusCode, raw)}
raw, err := readGenerationResponse(resp)
if err != nil {
return "", err
}
var result struct {

View File

@ -48,6 +48,7 @@ func LogSummaryDiagnostic(d SummaryDiagnostic) error {
// 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 {
code string
status int
err error
}

View File

@ -16,6 +16,9 @@ import (
)
type Handler struct {
modelTester interface {
Test(context.Context, string) error
}
connectionTester interface {
Test(context.Context, string) error
}
@ -45,8 +48,13 @@ func New(
if embedded, err := companycatalog.Default(); err == nil {
catalog = embedded
}
var decryptor ai.ConnectionDecryptor
if enc != nil {
decryptor = enc
}
return &Handler{
companyCatalog: catalog,
modelTester: ai.NewModelTester(repo, decryptor, ai.NewProvider),
connectionTester: ai.NewConnectionTester(repo, enc, func(name, key, endpoint string) (ai.Provider, error) {
return ai.NewProvider(name, key, "", endpoint)
}),
@ -72,3 +80,10 @@ func (h *Handler) SetGenerationJobs(jobs interface {
}
func (h *Handler) AdminOnly() gin.HandlerFunc { return auth.AdminOnly(h.repo) }
// SetModelTester supplies an isolated test port; production uses NewModelTester.
func (h *Handler) SetModelTester(tester interface {
Test(context.Context, string) error
}) {
h.modelTester = tester
}

View File

@ -0,0 +1,53 @@
package handlers
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/ai"
"net/http"
)
func (h *Handler) TestSummaryModel(c *gin.Context) {
// Defence against accidental panic logging by the outer recovery middleware.
defer func() {
if recover() != nil {
c.AbortWithStatusJSON(500, gin.H{"status": "unavailable"})
}
}()
// A no-body action: reject parameters without reading an unbounded/slow body.
if !assetUUID.MatchString(c.Param("id")) || c.Request.ContentLength != 0 || len(c.Request.TransferEncoding) > 0 || c.Request.URL.RawQuery != "" || c.Request.URL.ForceQuery {
c.JSON(http.StatusBadRequest, gin.H{"status": "unavailable"})
return
}
if h.modelTester == nil {
c.JSON(500, gin.H{"status": "unavailable"})
return
}
err := h.modelTester.Test(c.Request.Context(), c.Param("id"))
code, status := http.StatusOK, "success"
switch {
case err == nil:
case errors.Is(err, ai.ErrModelTestEmpty):
status = "empty_response"
case errors.Is(err, ai.ErrModelTestAuth):
status = "auth_rejected"
case errors.Is(err, ai.ErrModelTestModelUnavailable):
status = "model_unavailable"
case errors.Is(err, ai.ErrModelTestRateLimited):
status = "rate_limited"
case errors.Is(err, ai.ErrModelTestTimeout):
status = "timeout"
case errors.Is(err, ai.ErrModelTestUnavailable):
status = "unavailable"
case errors.Is(err, ai.ErrModelTestNotFound):
code = 404
status = "model_unavailable"
case errors.Is(err, ai.ErrModelTestBusy):
code = 409
status = "unavailable"
default:
code = 500
status = "unavailable"
}
c.JSON(code, gin.H{"status": status})
}

View File

@ -0,0 +1,53 @@
package handlers
import (
"context"
"errors"
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/ai"
"net/http/httptest"
"strings"
"testing"
)
type model43Tester struct {
err error
calls int
id string
}
func (f *model43Tester) Test(_ context.Context, id string) error { f.calls++; f.id = id; return f.err }
func TestTicket43ModelProbeHandlerOnlyReturnsBoundedStatus(t *testing.T) {
const id = "00000000-0000-0000-0000-000000004301"
for _, tc := range []struct {
err error
code int
status string
}{
{nil, 200, "success"}, {ai.ErrModelTestEmpty, 200, "empty_response"}, {ai.ErrModelTestAuth, 200, "auth_rejected"}, {ai.ErrModelTestModelUnavailable, 200, "model_unavailable"}, {ai.ErrModelTestRateLimited, 200, "rate_limited"}, {ai.ErrModelTestTimeout, 200, "timeout"}, {ai.ErrModelTestUnavailable, 200, "unavailable"}, {ai.ErrModelTestNotFound, 404, "model_unavailable"}, {ai.ErrModelTestBusy, 409, "unavailable"}, {errors.New("PRIVATE_BODY https://private.invalid"), 500, "unavailable"},
} {
fake := &model43Tester{err: tc.err}
h := &Handler{modelTester: fake}
router := gin.New()
router.POST("/api/admin/ai-models/:id/test", h.TestSummaryModel)
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest("POST", "/api/admin/ai-models/"+id+"/test", nil))
if w.Code != tc.code || w.Body.String() != `{"status":"`+tc.status+`"}` || fake.calls != 1 || fake.id != id {
t.Fatal("model test handler violated bounded response contract")
}
}
}
func TestTicket43ModelProbeRejectsAnyClientParametersBeforeService(t *testing.T) {
const path = "/api/admin/ai-models/00000000-0000-0000-0000-000000004301/test"
for _, tc := range []struct{ path, body string }{{path, `{"model":"PRIVATE","prompt":"PRIVATE","endpoint":"https://private.invalid","api_key":"PRIVATE"}`}, {path, `{}`}, {path + "?model=PRIVATE", ""}, {"/api/admin/ai-models/PRIVATE/test", ""}} {
fake := &model43Tester{}
h := &Handler{modelTester: fake}
router := gin.New()
router.POST("/api/admin/ai-models/:id/test", h.TestSummaryModel)
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body)))
if w.Code != 400 || w.Body.String() != `{"status":"unavailable"}` || fake.calls != 0 {
t.Fatal("client parameters reached model service")
}
}
}

View File

@ -0,0 +1,28 @@
package api_test
import (
"github.com/tradarr/backend/internal/api"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/config"
"net/http"
"net/http/httptest"
"testing"
)
func TestTicket43ModelGenerationTestRouteRequiresAuthentication(t *testing.T) {
router := api.SetupRouter(handlers.New(nil, &config.Config{}, nil, nil, nil, nil), "fixture43")
found := false
for _, route := range router.Routes() {
if route.Method == http.MethodPost && route.Path == "/api/admin/ai-models/:id/test" {
found = true
}
}
if !found {
t.Fatal("model generation test route missing")
}
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/admin/ai-models/00000000-0000-0000-0000-000000004301/test", nil))
if w.Code != 401 {
t.Fatal("model generation test is not authenticated")
}
}

View File

@ -0,0 +1,212 @@
package api_test
import (
"bytes"
"context"
"database/sql"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/lib/pq"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/api"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/crypto"
"github.com/tradarr/backend/internal/models"
)
type generationProbe43 struct {
generate func(context.Context, string, ai.GenOptions) (string, error)
}
func (*generationProbe43) Name() string { return "fixture" }
func (p *generationProbe43) Summarize(ctx context.Context, prompt string, opts ai.GenOptions) (string, error) {
return p.generate(ctx, prompt, opts)
}
func (*generationProbe43) ListModels(context.Context) ([]string, error) {
return nil, errors.New("discovery is not generation")
}
func TestTicket43SavedDisabledModelAdminGenerationAndNoMutationPostgres(t *testing.T) {
db, err := sql.Open("postgres", postgresTestURL(t))
if err != nil {
t.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(1)
schema := fmt.Sprintf("probe43_%d", time.Now().UnixNano())
if _, err = db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil {
t.Fatal(err)
}
defer db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
if _, err = db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
t.Fatal(err)
}
const mid = "00000000-0000-0000-0000-000000004301"
const sibling = "00000000-0000-0000-0000-000000004302"
const pid = "00000000-0000-0000-0000-000000004311"
for _, q := range []string{
`CREATE TABLE users(id TEXT PRIMARY KEY,email TEXT,password_hash TEXT,role TEXT,summary_model_id UUID,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,
`INSERT INTO users(id,email,password_hash,role,summary_model_id) VALUES('admin','admin@example.test','hash','admin','` + sibling + `'),('user','user@example.test','hash','user',NULL)`,
`CREATE TABLE ai_providers(id UUID PRIMARY KEY,name TEXT,model TEXT,endpoint TEXT,api_key_encrypted TEXT,is_active BOOLEAN)`,
`CREATE TABLE ai_provider_models(id UUID PRIMARY KEY,provider_id UUID REFERENCES ai_providers(id),model TEXT,enabled BOOLEAN)`,
} {
if _, err = db.Exec(q); err != nil {
t.Fatal(err)
}
}
enc := crypto.New([]byte("0123456789abcdef0123456789abcdef"))
cipher, err := enc.Encrypt("PRIVATE_SAVED_KEY")
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec(`INSERT INTO ai_providers VALUES($1,'ollama','wrong-provider-default','https://PRIVATE_ENDPOINT.invalid',$2,false)`, pid, cipher); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(`INSERT INTO ai_provider_models VALUES($1,$2,'exact-saved-model',false),($3,$2,'other-enabled-model',true)`, mid, pid, sibling); err != nil {
t.Fatal(err)
}
var logs bytes.Buffer
oldWriter, oldErr := gin.DefaultWriter, gin.DefaultErrorWriter
gin.DefaultWriter = &logs
gin.DefaultErrorWriter = &logs
defer func() { gin.DefaultWriter = oldWriter; gin.DefaultErrorWriter = oldErr }()
repo := models.NewRepository(db)
var mu sync.Mutex
calls, builds := 0, 0
response := " PRIVATE_GENERATED_BODY "
var upstream error
promptSeen := ""
var block chan struct{}
var started chan struct{}
service := ai.NewModelTester(repo, enc, func(name, key, model, endpoint string) (ai.Provider, error) {
mu.Lock()
builds++
mu.Unlock()
if name != "ollama" || key != "PRIVATE_SAVED_KEY" || model != "exact-saved-model" || endpoint != "https://PRIVATE_ENDPOINT.invalid" {
t.Error("factory did not use exact saved row/model/secret/endpoint")
}
return &generationProbe43{generate: func(ctx context.Context, prompt string, opts ai.GenOptions) (string, error) {
mu.Lock()
calls++
promptSeen = prompt
b, s := block, started
body, err := response, upstream
mu.Unlock()
if opts.MaxOutputTokens <= 0 || opts.MaxOutputTokens > 32 || len(prompt) > 64 {
t.Error("probe generation was not minimal")
}
if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > 30*time.Second {
t.Error("30s probe deadline missing")
}
if s != nil {
close(s)
}
if b != nil {
<-b
}
return body, err
}}, nil
})
const secret = "ticket43-fixture"
h := handlers.New(repo, &config.Config{JWTSecret: secret}, enc, nil, nil, nil)
h.SetModelTester(service)
router := api.SetupRouter(h, secret)
admin, _ := auth.GenerateToken("admin", "admin@example.test", "admin", secret)
user, _ := auth.GenerateToken("user", "user@example.test", "user", secret)
path := "/api/admin/ai-models/" + mid + "/test"
request := func(path, body, token string) *httptest.ResponseRecorder {
r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
if token != "" {
r.Header.Set("Authorization", "Bearer "+token)
}
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
return w
}
for _, tc := range []struct {
token string
code int
}{{"", 401}, {user, 403}} {
if w := request(path, "", tc.token); w.Code != tc.code {
t.Fatal("probe authorization failed")
}
}
for _, tc := range []struct{ path, body string }{{path, `{"prompt":"PRIVATE_CLIENT_PROMPT","model":"PRIVATE_OVERRIDE"}`}, {path + "?endpoint=https://PRIVATE_QUERY.invalid", ""}} {
w := request(tc.path, tc.body, admin)
if w.Code != 400 || w.Body.String() != `{"status":"unavailable"}` {
t.Fatal("client parameters were not rejected")
}
}
unknown := "/api/admin/ai-models/00000000-0000-0000-0000-000000004399/test"
if w := request(unknown, "", admin); w.Code != 404 || w.Body.String() != `{"status":"model_unavailable"}` {
t.Fatal("missing catalogue row was not sanitized")
}
if w := request(path, "", admin); w.Code != 200 || w.Body.String() != `{"status":"success"}` {
t.Fatal("disabled catalogue model/provider cannot be tested")
}
mu.Lock()
if calls != 1 || builds != 1 {
t.Error("probe ran discovery, retried, or accepted substitutions")
}
response = " \n\t"
mu.Unlock()
if w := request(path, "", admin); w.Code != 200 || w.Body.String() != `{"status":"empty_response"}` {
t.Fatal("empty response was treated as success")
}
mu.Lock()
upstream = errors.New("PRIVATE_UPSTREAM_ERROR https://PRIVATE_REMOTE.invalid")
mu.Unlock()
if w := request(path, "", admin); w.Code != 200 || w.Body.String() != `{"status":"unavailable"}` {
t.Fatal("raw upstream failure escaped")
}
mu.Lock()
upstream = nil
response = "OK"
block = make(chan struct{})
started = make(chan struct{})
start, finish := started, block
mu.Unlock()
done := make(chan *httptest.ResponseRecorder, 1)
go func() { done <- request(path, "", admin) }()
select {
case <-start:
case <-time.After(time.Second):
close(finish)
t.Fatal("blocking probe did not start")
}
if w := request(path, "", admin); w.Code != 409 || w.Body.String() != `{"status":"unavailable"}` {
t.Error("same-provider HTTP probe was not rejected")
}
close(finish)
if w := <-done; w.Code != 200 {
t.Fatal("first concurrent probe failed")
}
var modelEnabled, providerActive bool
var selected string
if err = db.QueryRow(`SELECT enabled FROM ai_provider_models WHERE id=$1`, mid).Scan(&modelEnabled); err != nil || modelEnabled {
t.Fatal("probe enabled saved model")
}
if err = db.QueryRow(`SELECT is_active FROM ai_providers WHERE id=$1`, pid).Scan(&providerActive); err != nil || providerActive {
t.Fatal("probe activated saved provider")
}
if err = db.QueryRow(`SELECT summary_model_id FROM users WHERE id='admin'`).Scan(&selected); err != nil || selected != sibling {
t.Fatal("probe changed user preference")
}
mu.Lock()
seen := promptSeen
mu.Unlock()
for _, private := range []string{"PRIVATE_", seen, "https://PRIVATE_ENDPOINT.invalid"} {
if private != "" && strings.Contains(logs.String(), private) {
t.Error("probe leaked prompt/response/configuration/error into logs")
}
}
}

View File

@ -11,6 +11,9 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
r.Use(gin.Recovery())
r.Use(gin.LoggerWithConfig(gin.LoggerConfig{
SkipPaths: []string{"/api/summaries/status"},
// Never log rejected test query parameters or arbitrary model IDs. Test
// outcomes are bounded responses; no generation data belongs in access logs.
Skip: func(c *gin.Context) bool { return c.FullPath() == "/api/admin/ai-models/:id/test" },
}))
r.Use(func(c *gin.Context) {
@ -65,6 +68,7 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
admin.GET("/ai-models", h.ListSummaryModels)
admin.POST("/ai-models", h.CreateSummaryModel)
admin.POST("/ai-models/:id/test", h.TestSummaryModel)
admin.PUT("/ai-models/:id", h.UpdateSummaryModel)
admin.DELETE("/ai-models/:id", h.DeleteSummaryModel)
admin.GET("/ai-providers", h.ListAIProviders)

View File

@ -100,3 +100,12 @@ func (r *Repository) ResolveSummaryModel(ctx context.Context, userID string, id
}
return m, nil
}
// GetSummaryModelForTest resolves the exact saved entry without requiring enabled,
// an active provider, a user preference, or a known synthesis capacity profile.
// It is read-only and belongs solely to the authenticated admin test use case.
func (r *Repository) GetSummaryModelForTest(ctx context.Context, id string) (ResolvedSummaryModel, error) {
var m ResolvedSummaryModel
err := r.db.QueryRowContext(ctx, `SELECT m.id,p.id,p.name,m.model,p.endpoint,p.api_key_encrypted FROM ai_provider_models m JOIN ai_providers p ON p.id=m.provider_id WHERE m.id=$1`, id).Scan(&m.ID, &m.ProviderID, &m.Provider, &m.Model, &m.Endpoint, &m.APIKeyEncrypted)
return m, err
}

View File

@ -3,6 +3,7 @@
package server
import (
"context"
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/api"
@ -19,6 +20,9 @@ import (
)
type Dependencies struct {
ModelTester interface {
Test(context.Context, string) error
}
SummaryDiagnostics ai.SummaryDiagnosticCollector
CompanyCatalog companycatalog.CompanyCatalog
LayaRanker generation.LayaRanker
@ -52,6 +56,9 @@ func New(repo *models.Repository, cfg *config.Config, deps Dependencies) *App {
}
}
h := handlers.New(repo, cfg, enc, registry, pipeline, sched)
if deps.ModelTester != nil {
h.SetModelTester(deps.ModelTester)
}
h.SetGenerationUseCase(uc)
h.SetIndexSearcher(deps.IndexSearcher)
if deps.CompanyCatalog != nil {