feat(ai): test saved summary model generation (#43)
This commit is contained in:
@ -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 {
|
||||
|
||||
@ -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) {
|
||||
|
||||
@ -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
|
||||
|
||||
64
backend/internal/ai/generation_response.go
Normal file
64
backend/internal/ai/generation_response.go
Normal 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 ""
|
||||
}
|
||||
127
backend/internal/ai/model_probe_adapters_ticket43_test.go
Normal file
127
backend/internal/ai/model_probe_adapters_ticket43_test.go
Normal 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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
51
backend/internal/ai/model_probe_cli_ticket43_test.go
Normal file
51
backend/internal/ai/model_probe_cli_ticket43_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
121
backend/internal/ai/model_test_lock_ticket43_test.go
Normal file
121
backend/internal/ai/model_test_lock_ticket43_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
193
backend/internal/ai/model_test_service.go
Normal file
193
backend/internal/ai/model_test_service.go
Normal 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
|
||||
}
|
||||
117
backend/internal/ai/model_test_service_ticket43_test.go
Normal file
117
backend/internal/ai/model_test_service_ticket43_test.go
Normal 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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -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 {
|
||||
|
||||
@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user