feat(qa): add synthesis conversations with source retention (#52)
This commit is contained in:
@ -34,7 +34,7 @@ func (safeSummarizer) Summarize(context.Context, string, []models.UserAsset, []g
|
||||
func TestGenerationSucceedsWithoutArticleTablesAndRollsBackSummaryPostgres(t *testing.T) {
|
||||
db, _ := ticket7DB(t)
|
||||
for _, statement := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,language TEXT DEFAULT 'fr',ranking_mode TEXT DEFAULT 'title',summary_prompt_token_budget INT NOT NULL DEFAULT 250000,ranking_model_id UUID,summary_model_id UUID NULL)`,
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,language TEXT DEFAULT 'fr',ranking_mode TEXT DEFAULT 'title',summary_prompt_token_budget INT NOT NULL DEFAULT 250000,ranking_model_id UUID,source_article_retention_days INT NOT NULL DEFAULT 7,summary_model_id UUID NULL)`,
|
||||
`CREATE TABLE user_assets(id UUID PRIMARY KEY,user_id UUID,symbol TEXT,name TEXT,figi TEXT NULL,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE sources(id UUID PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,article_limit INTEGER DEFAULT 20,source_key TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE settings(key TEXT PRIMARY KEY,value TEXT)`,
|
||||
@ -47,6 +47,7 @@ func TestGenerationSucceedsWithoutArticleTablesAndRollsBackSummaryPostgres(t *te
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
installQATables53(t, db)
|
||||
repo := models.NewRepository(db)
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: repo}, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: memoryFeed{}}, Ranker: passRanker{}, Summarizer: safeSummarizer{}})
|
||||
result, err := uc.Generate(context.Background(), "00000000-0000-0000-0000-000000000001")
|
||||
|
||||
@ -13,9 +13,11 @@ import (
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scheduler"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"github.com/tradarr/backend/internal/summaryqa"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
summaryQA summaryqa.UseCase
|
||||
modelTester interface {
|
||||
Test(context.Context, string) error
|
||||
}
|
||||
@ -52,7 +54,12 @@ func New(
|
||||
if enc != nil {
|
||||
decryptor = enc
|
||||
}
|
||||
var qa summaryqa.UseCase
|
||||
if repo != nil {
|
||||
qa = summaryqa.New(repo, ai.QAResolver{Repo: repo, Encryptor: enc})
|
||||
}
|
||||
return &Handler{
|
||||
summaryQA: qa,
|
||||
companyCatalog: catalog,
|
||||
modelTester: ai.NewModelTester(repo, decryptor, ai.NewProvider),
|
||||
connectionTester: ai.NewConnectionTester(repo, enc, func(name, key, endpoint string) (ai.Provider, error) {
|
||||
|
||||
@ -12,6 +12,10 @@ import (
|
||||
)
|
||||
|
||||
func preferencesError(c *gin.Context, err error) {
|
||||
if errors.Is(err, models.ErrInvalidRetention) {
|
||||
c.JSON(400, gin.H{"error": "invalid_source_article_retention_days"})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, models.ErrRankingModelIncompatible) {
|
||||
c.JSON(400, gin.H{"error": "ranking_model_incompatible", "reason": "ranking_structured_output_unsupported", "message": "Ce modèle reste disponible pour la synthèse mais sa sortie JSON structurée n’est pas prise en charge pour le classement."})
|
||||
return
|
||||
@ -51,6 +55,7 @@ func (h *Handler) GetMyPreferences(c *gin.Context) {
|
||||
|
||||
func (h *Handler) UpdateMyPreferences(c *gin.Context) {
|
||||
var body struct {
|
||||
Retention json.RawMessage `json:"source_article_retention_days"`
|
||||
RankingModelID *string `json:"ranking_model_id" binding:"omitempty,uuid"`
|
||||
Language string `json:"language" binding:"required,oneof=fr en"`
|
||||
RankingMode string `json:"ranking_mode" binding:"required,oneof=title title_content"`
|
||||
@ -66,6 +71,10 @@ func (h *Handler) UpdateMyPreferences(c *gin.Context) {
|
||||
c.JSON(400, gin.H{"error": "invalid_prompt_budget"})
|
||||
return
|
||||
}
|
||||
if len(body.Retention) > 0 && (string(body.Retention) == "null" || json.Unmarshal(body.Retention, &req.SourceArticleRetentionDays) != nil || req.SourceArticleRetentionDays < 1 || req.SourceArticleRetentionDays > 30) {
|
||||
c.JSON(400, gin.H{"error": "invalid_source_article_retention_days"})
|
||||
return
|
||||
}
|
||||
p, err := h.repo.UpdateUserPreferences(c.GetString("userID"), req)
|
||||
if err != nil {
|
||||
preferencesError(c, err)
|
||||
|
||||
99
backend/internal/api/handlers/summary_qa.go
Normal file
99
backend/internal/api/handlers/summary_qa.go
Normal file
@ -0,0 +1,99 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/httputil"
|
||||
"github.com/tradarr/backend/internal/summaryqa"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func (h *Handler) SetQAUseCase(uc summaryqa.UseCase) { h.summaryQA = uc }
|
||||
func qaError(c *gin.Context, err error) {
|
||||
code, status := "qa_unavailable", 503
|
||||
var limited *summaryqa.RateLimitError
|
||||
if errors.Is(err, summaryqa.ErrRateLimited) {
|
||||
seconds := 1
|
||||
if errors.As(err, &limited) {
|
||||
seconds = max(1, limited.RetryAfterSeconds)
|
||||
}
|
||||
c.Header("Retry-After", strconv.Itoa(seconds))
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, summaryqa.ErrRateLimited):
|
||||
code, status = "qa_rate_limited", 429
|
||||
case errors.Is(err, summaryqa.ErrNotFound):
|
||||
code, status = "qa_not_found", 404
|
||||
case errors.Is(err, summaryqa.ErrInvalid):
|
||||
code, status = "qa_invalid_request", 400
|
||||
case errors.Is(err, summaryqa.ErrConflict):
|
||||
code, status = "qa_idempotency_conflict", 409
|
||||
case errors.Is(err, summaryqa.ErrBusy):
|
||||
code, status = "qa_question_in_progress", 409
|
||||
case errors.Is(err, summaryqa.ErrLimit):
|
||||
code, status = "qa_context_limit", 422
|
||||
case errors.Is(err, summaryqa.ErrModel):
|
||||
code, status = "qa_model_unavailable", 409
|
||||
case errors.Is(err, summaryqa.ErrProvider):
|
||||
code, status = "qa_provider_failed", 502
|
||||
}
|
||||
c.JSON(status, gin.H{"error": code})
|
||||
}
|
||||
func (h *Handler) qaReady(c *gin.Context) bool {
|
||||
if !assetUUID.MatchString(c.Param("id")) {
|
||||
qaError(c, summaryqa.ErrNotFound)
|
||||
return false
|
||||
}
|
||||
if h.summaryQA == nil {
|
||||
qaError(c, errors.New("unavailable"))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
func (h *Handler) GetSummaryConversation(c *gin.Context) {
|
||||
if !h.qaReady(c) {
|
||||
return
|
||||
}
|
||||
result, err := h.summaryQA.Get(c.Request.Context(), c.GetString("userID"), c.Param("id"))
|
||||
if err != nil {
|
||||
qaError(c, err)
|
||||
return
|
||||
}
|
||||
httputil.OK(c, result)
|
||||
}
|
||||
func (h *Handler) AskSummaryQuestion(c *gin.Context) {
|
||||
if !h.qaReady(c) {
|
||||
return
|
||||
}
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 65536)
|
||||
var q summaryqa.Question
|
||||
decoder := json.NewDecoder(c.Request.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&q) != nil {
|
||||
qaError(c, summaryqa.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if decoder.Decode(new(any)) != io.EOF {
|
||||
qaError(c, summaryqa.ErrInvalid)
|
||||
return
|
||||
}
|
||||
result, err := h.summaryQA.Ask(c.Request.Context(), c.GetString("userID"), c.Param("id"), q)
|
||||
if err != nil {
|
||||
qaError(c, err)
|
||||
return
|
||||
}
|
||||
httputil.OK(c, result)
|
||||
}
|
||||
func (h *Handler) DeleteSummaryConversation(c *gin.Context) {
|
||||
if !h.qaReady(c) {
|
||||
return
|
||||
}
|
||||
if err := h.summaryQA.Delete(c.Request.Context(), c.GetString("userID"), c.Param("id")); err != nil {
|
||||
qaError(c, err)
|
||||
return
|
||||
}
|
||||
c.Status(204)
|
||||
}
|
||||
@ -53,7 +53,7 @@ func TestPreferencesPersistPerUserPostgres(t *testing.T) {
|
||||
if _, err = db.Exec(string(migration)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(`ALTER TABLE users ADD COLUMN ranking_model_id UUID, ADD COLUMN summary_model_id UUID NULL, ADD COLUMN summary_prompt_token_budget INT NOT NULL DEFAULT 250000`); err != nil {
|
||||
if _, err = db.Exec(`ALTER TABLE users ADD COLUMN source_article_retention_days INT NOT NULL DEFAULT 7, ADD COLUMN ranking_model_id UUID, ADD COLUMN summary_model_id UUID NULL, ADD COLUMN summary_prompt_token_budget INT NOT NULL DEFAULT 250000`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The two accounts predate migration 11: defaults must backfill both,
|
||||
|
||||
@ -15,7 +15,7 @@ import (
|
||||
|
||||
func TestTicket39PromptBudgetMigrationAndAccountAPIIsolatedPostgres(t *testing.T) {
|
||||
db := ticket14DB(t)
|
||||
if _, err := db.Exec(`CREATE TABLE users(id UUID PRIMARY KEY,language TEXT DEFAULT 'fr',ranking_mode TEXT DEFAULT 'title',ranking_model_id UUID,summary_model_id UUID,updated_at TIMESTAMPTZ DEFAULT NOW()); INSERT INTO users(id) VALUES('00000000-0000-0000-0000-000000003901'),('00000000-0000-0000-0000-000000003902')`); err != nil {
|
||||
if _, err := db.Exec(`CREATE TABLE users(id UUID PRIMARY KEY,language TEXT DEFAULT 'fr',ranking_mode TEXT DEFAULT 'title',ranking_model_id UUID,source_article_retention_days INT NOT NULL DEFAULT 7,summary_model_id UUID,updated_at TIMESTAMPTZ DEFAULT NOW()); INSERT INTO users(id) VALUES('00000000-0000-0000-0000-000000003901'),('00000000-0000-0000-0000-000000003902')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
migration, err := os.ReadFile("../database/migrations/000020_summary_prompt_budget.up.sql")
|
||||
|
||||
266
backend/internal/api/qa_concurrency_ticket55_postgres_test.go
Normal file
266
backend/internal/api/qa_concurrency_ticket55_postgres_test.go
Normal file
@ -0,0 +1,266 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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/config"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/summaryqa"
|
||||
)
|
||||
|
||||
// Each instance owns a different database/sql pool and physical connection.
|
||||
// Only PostgreSQL coordinates them; no in-process limiter is shared.
|
||||
func qa55Instance(t *testing.T, base *qa53Fixture, provider ai.Provider) *qa53Fixture {
|
||||
t.Helper()
|
||||
var schema string
|
||||
if err := base.db.QueryRow(`SELECT current_schema()`).Scan(&schema); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db, err := sql.Open("postgres", os.Getenv("TEST_DATABASE_URL"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
if _, err = db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Admission must remain correct even when an application instance uses a
|
||||
// stricter connection default. The limiter explicitly selects READ COMMITTED.
|
||||
if _, err = db.Exec(`SET default_transaction_isolation='repeatable read'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := models.NewRepository(db)
|
||||
service := summaryqa.New(repo, ai.QAResolver{Repo: repo, Factory: func(models.ResolvedSummaryModel) (ai.Provider, error) { return provider, nil }})
|
||||
service.Clock = func() time.Time { return base.now }
|
||||
h := handlers.New(repo, &config.Config{JWTSecret: "qa53"}, nil, nil, nil, nil)
|
||||
h.SetQAUseCase(service)
|
||||
return &qa53Fixture{db: db, repo: repo, service: service, router: api.SetupRouter(h, "qa53"), now: base.now}
|
||||
}
|
||||
func qa55Summary(t *testing.T, f *qa53Fixture, id, owner string) string {
|
||||
t.Helper()
|
||||
if _, err := f.db.Exec(`INSERT INTO summaries(id,user_id,content,generated_at,summary_model_id) SELECT $1,$2,content,generated_at,summary_model_id FROM summaries WHERE id=$3`, id, owner, qa53Summary); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return "/api/summaries/" + id + "/conversation/messages"
|
||||
}
|
||||
|
||||
type qa55Gate struct {
|
||||
mu sync.Mutex
|
||||
active, max map[string]int
|
||||
started chan string
|
||||
release chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (g *qa55Gate) close() { g.once.Do(func() { close(g.release) }) }
|
||||
|
||||
type qa55GateProvider struct {
|
||||
gate *qa55Gate
|
||||
owner string
|
||||
wait bool
|
||||
}
|
||||
|
||||
func (p qa55GateProvider) Name() string { return "fixture" }
|
||||
func (p qa55GateProvider) ListModels(context.Context) ([]string, error) { return nil, nil }
|
||||
func (p qa55GateProvider) Summarize(context.Context, string, ai.GenOptions) (string, error) {
|
||||
g := p.gate
|
||||
g.mu.Lock()
|
||||
g.active[p.owner]++
|
||||
if g.active[p.owner] > g.max[p.owner] {
|
||||
g.max[p.owner] = g.active[p.owner]
|
||||
}
|
||||
g.mu.Unlock()
|
||||
g.started <- p.owner
|
||||
// Deliberately ignore request cancellation: the permit must last until the
|
||||
// actual provider invocation returns, not until pending metadata expires.
|
||||
if p.wait {
|
||||
<-g.release
|
||||
}
|
||||
g.mu.Lock()
|
||||
g.active[p.owner]--
|
||||
g.mu.Unlock()
|
||||
return "A safe answer", nil
|
||||
}
|
||||
func qa55Async(t *testing.T, f *qa53Fixture, owner, path, id string) <-chan *httptest.ResponseRecorder {
|
||||
done := make(chan *httptest.ResponseRecorder, 1)
|
||||
go func() { done <- qa55Call(t, f, owner, path, id, "question") }()
|
||||
return done
|
||||
}
|
||||
func TestTicket55TrueProviderConcurrencyAcrossConversationsAndInstancesPostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
path1 := qa53Path() + "/messages"
|
||||
path2 := qa55Summary(t, f, qa55ID(100), ticket14UserA)
|
||||
path3 := qa55Summary(t, f, qa55ID(101), ticket14UserA)
|
||||
pathB := qa55Summary(t, f, qa55ID(102), ticket14UserB)
|
||||
gate := &qa55Gate{active: map[string]int{}, max: map[string]int{}, started: make(chan string, 16), release: make(chan struct{})}
|
||||
defer gate.close()
|
||||
a := qa55GateProvider{gate: gate, owner: ticket14UserA, wait: true}
|
||||
b := qa55GateProvider{gate: gate, owner: ticket14UserB}
|
||||
one, two, three, other := qa55Instance(t, f, a), qa55Instance(t, f, a), qa55Instance(t, f, a), qa55Instance(t, f, b)
|
||||
first := qa55Async(t, one, ticket14UserA, path1, qa55ID(1))
|
||||
select {
|
||||
case <-gate.started:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("first call never started")
|
||||
}
|
||||
second := qa55Async(t, two, ticket14UserA, path2, qa55ID(2))
|
||||
select {
|
||||
case <-gate.started:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("second call never started")
|
||||
}
|
||||
third := qa55Async(t, three, ticket14UserA, path3, qa55ID(3))
|
||||
select {
|
||||
case response := <-third:
|
||||
if response.Code != 429 || response.Header().Get("Retry-After") != "1" {
|
||||
t.Fatalf("third call: %d %s", response.Code, response.Body)
|
||||
}
|
||||
case <-gate.started:
|
||||
gate.close()
|
||||
<-first
|
||||
<-second
|
||||
<-third
|
||||
t.Fatal("third provider call really started while two were active")
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("third admission blocked instead of returning 429")
|
||||
}
|
||||
// Remove the pending marker while the real provider is still running. A
|
||||
// counter based only on turn status/TTL would now incorrectly admit more work.
|
||||
if _, err := f.db.Exec(`UPDATE summary_qa_turns SET status='failed',failure_code='qa_provider_failed' WHERE status='pending'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stillLimited := qa55Call(t, three, ticket14UserA, path3, qa55ID(3), "question")
|
||||
if stillLimited.Code != 429 {
|
||||
t.Fatalf("pending metadata released live provider permits: %d %s", stillLimited.Code, stillLimited.Body)
|
||||
}
|
||||
isolated := qa55Call(t, other, ticket14UserB, pathB, qa55ID(4), "question")
|
||||
if isolated.Code != 200 {
|
||||
t.Fatalf("account isolation broken: %d %s", isolated.Code, isolated.Body)
|
||||
}
|
||||
gate.close()
|
||||
for _, done := range []<-chan *httptest.ResponseRecorder{first, second} {
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("provider permit not released")
|
||||
}
|
||||
}
|
||||
retry := qa55Call(t, three, ticket14UserA, path3, qa55ID(3), "question")
|
||||
if retry.Code != 200 {
|
||||
t.Fatalf("429 request could not retry after calls returned: %d %s", retry.Code, retry.Body)
|
||||
}
|
||||
gate.mu.Lock()
|
||||
defer gate.mu.Unlock()
|
||||
if gate.max[ticket14UserA] != 2 {
|
||||
t.Fatalf("actual concurrent provider calls=%d", gate.max[ticket14UserA])
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket55AtomicLastMinuteCreditAcrossIndependentServerInstancesPostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
if _, err := f.db.Exec(`INSERT INTO summary_qa_provider_calls(user_id,turn_id,started_at) SELECT $1,gen_random_uuid(),clock_timestamp() FROM generate_series(1,9)`, ticket14UserA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const workers = 8
|
||||
instances := make([]*qa53Fixture, workers)
|
||||
paths := make([]string, workers)
|
||||
for i := 0; i < workers; i++ {
|
||||
paths[i] = qa55Summary(t, f, qa55ID(100+i), ticket14UserA)
|
||||
instances[i] = qa55Instance(t, f, &qa53Provider{})
|
||||
}
|
||||
start := make(chan struct{})
|
||||
responses := make(chan *httptest.ResponseRecorder, workers)
|
||||
for i := 0; i < workers; i++ {
|
||||
go func(i int) {
|
||||
<-start
|
||||
responses <- qa55Call(t, instances[i], ticket14UserA, paths[i], qa55ID(i), "question")
|
||||
}(i)
|
||||
}
|
||||
close(start)
|
||||
accepted, limited := 0, 0
|
||||
for i := 0; i < workers; i++ {
|
||||
select {
|
||||
case w := <-responses:
|
||||
switch w.Code {
|
||||
case 200:
|
||||
accepted++
|
||||
case 429:
|
||||
limited++
|
||||
default:
|
||||
t.Fatalf("unexpected admission %d %s", w.Code, w.Body)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("cross-instance admission deadlocked")
|
||||
}
|
||||
}
|
||||
if accepted != 1 || limited != workers-1 {
|
||||
t.Fatalf("quota check+insert was not atomic: accepted=%d limited=%d", accepted, limited)
|
||||
}
|
||||
var n int
|
||||
if err := f.db.QueryRow(`SELECT count(*) FROM summary_qa_provider_calls WHERE user_id=$1`, ticket14UserA).Scan(&n); err != nil || n != 10 {
|
||||
t.Fatal("account admitted more than 10 attempts", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket55UUIDRepresentationsShareProviderConcurrencySlotsPostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
owner := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
|
||||
if _, err := f.db.Exec(`INSERT INTO users(id,email,password_hash) VALUES($1,'alias@test','hash')`, owner); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths := []string{qa55Summary(t, f, qa55ID(200), owner), qa55Summary(t, f, qa55ID(201), owner), qa55Summary(t, f, qa55ID(202), owner)}
|
||||
gate := &qa55Gate{active: map[string]int{}, max: map[string]int{}, started: make(chan string, 8), release: make(chan struct{})}
|
||||
defer gate.close()
|
||||
provider := qa55GateProvider{gate: gate, owner: owner, wait: true}
|
||||
one, two, three := qa55Instance(t, f, provider), qa55Instance(t, f, provider), qa55Instance(t, f, provider)
|
||||
first := qa55Async(t, one, owner, paths[0], qa55ID(1))
|
||||
select {
|
||||
case <-gate.started:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("first not started")
|
||||
}
|
||||
second := qa55Async(t, two, strings.ToUpper(owner), paths[1], qa55ID(2))
|
||||
select {
|
||||
case <-gate.started:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("second not started")
|
||||
}
|
||||
third := qa55Async(t, three, owner, paths[2], qa55ID(3))
|
||||
select {
|
||||
case w := <-third:
|
||||
if w.Code != 429 {
|
||||
t.Fatal("expected shared account limit", w.Code, w.Body)
|
||||
}
|
||||
case <-gate.started:
|
||||
gate.close()
|
||||
<-first
|
||||
<-second
|
||||
<-third
|
||||
t.Fatal("UUID case alias bypassed per-account provider concurrency")
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("admission blocked")
|
||||
}
|
||||
gate.close()
|
||||
for _, done := range []<-chan *httptest.ResponseRecorder{first, second} {
|
||||
select {
|
||||
case w := <-done:
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("call did not finish")
|
||||
}
|
||||
}
|
||||
}
|
||||
397
backend/internal/api/qa_flow_ticket53_postgres_test.go
Normal file
397
backend/internal/api/qa_flow_ticket53_postgres_test.go
Normal file
@ -0,0 +1,397 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"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/models"
|
||||
"github.com/tradarr/backend/internal/summaryqa"
|
||||
)
|
||||
|
||||
const qa53Summary = "00000000-0000-0000-0000-000000005310"
|
||||
const qa53Request = "00000000-0000-0000-0000-000000005311"
|
||||
|
||||
type qa53Provider struct {
|
||||
mu sync.Mutex
|
||||
prompts []string
|
||||
err error
|
||||
started, release chan struct{}
|
||||
}
|
||||
|
||||
func (*qa53Provider) Name() string { return "fixture" }
|
||||
func (*qa53Provider) ListModels(context.Context) ([]string, error) { return nil, nil }
|
||||
func (p *qa53Provider) Summarize(ctx context.Context, prompt string, opts ai.GenOptions) (string, error) {
|
||||
p.mu.Lock()
|
||||
p.prompts = append(p.prompts, prompt)
|
||||
p.mu.Unlock()
|
||||
if p.started != nil {
|
||||
p.started <- struct{}{}
|
||||
}
|
||||
if p.release != nil {
|
||||
select {
|
||||
case <-p.release:
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
}
|
||||
}
|
||||
if opts.MaxOutputTokens != 4096 || !opts.RequireComplete {
|
||||
return "", errors.New("unbounded Q&A generation")
|
||||
}
|
||||
return "A safe answer", p.err
|
||||
}
|
||||
|
||||
type qa53Fixture struct {
|
||||
db *sql.DB
|
||||
repo *models.Repository
|
||||
router *gin.Engine
|
||||
service *summaryqa.Service
|
||||
provider *qa53Provider
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func qa53Setup(t *testing.T) *qa53Fixture {
|
||||
t.Helper()
|
||||
seedDB := ticket14DB(t)
|
||||
var schema string
|
||||
if err := seedDB.QueryRow(`SELECT current_schema()`).Scan(&schema); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dsn := postgresTestURL(t)
|
||||
if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") {
|
||||
var err error
|
||||
dsn, err = pq.ParseURL(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
db, err := sql.Open("postgres", dsn+" search_path="+pq.QuoteLiteral(schema))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.SetMaxOpenConns(8)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
for _, q := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,email TEXT,password_hash TEXT,role TEXT DEFAULT 'user',language TEXT DEFAULT 'fr',ranking_mode TEXT DEFAULT 'title',summary_prompt_token_budget INT DEFAULT 250000,summary_model_id UUID,ranking_model_id UUID,updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE summaries(id UUID PRIMARY KEY,user_id UUID REFERENCES users(id),content TEXT,ai_provider_id UUID,generated_at TIMESTAMPTZ,summary_model_id UUID,provider_name TEXT,model_name TEXT)`,
|
||||
`CREATE TABLE summary_generations(id UUID PRIMARY KEY,user_id UUID,summary_id UUID,outcome JSONB,created_at TIMESTAMPTZ)`,
|
||||
`CREATE TABLE ai_providers(id UUID PRIMARY KEY,name TEXT,endpoint TEXT,api_key_encrypted TEXT)`,
|
||||
`CREATE TABLE ai_provider_models(id UUID PRIMARY KEY,provider_id UUID,model TEXT,enabled BOOLEAN)`,
|
||||
`CREATE TABLE articles(id TEXT PRIMARY KEY,content TEXT)`,
|
||||
`CREATE TABLE report_messages(id TEXT PRIMARY KEY,content TEXT)`,
|
||||
`INSERT INTO articles VALUES('legacy','preserve article')`,
|
||||
`INSERT INTO report_messages VALUES('legacy','preserve message')`,
|
||||
`INSERT INTO users(id,email,password_hash) VALUES('` + ticket14UserA + `','a@test','hash'),('` + ticket14UserB + `','b@test','hash')`,
|
||||
`INSERT INTO ai_providers VALUES('` + ticket14ProviderA + `','openai','https://fixture.invalid','')`,
|
||||
`INSERT INTO ai_provider_models VALUES('` + ticket14ModelA + `','` + ticket14ProviderA + `','gpt-4o-mini',true)`,
|
||||
} {
|
||||
if _, err := db.Exec(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
raw, err := os.ReadFile("../database/migrations/000024_summary_qa.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(string(raw)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
quotaMigration, err := os.ReadFile("../database/migrations/000025_qa_provider_quota.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(string(quotaMigration)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := models.NewRepository(db)
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
model, provider := ticket14ModelA, ticket14ProviderA
|
||||
summary := &models.Summary{ID: qa53Summary, UserID: ticket14UserA, Content: "OWN_SYNTHESIS_MARKER", GeneratedAt: now, SummaryModelID: &model, AIProviderID: &provider}
|
||||
sources := []models.SummarySourceArticle{{Title: "PRIVATE_SOURCE_TITLE", Content: "PRIVATE_SOURCE_BODY", URL: "https://fixture.invalid/PRIVATE_SOURCE_URL", Source: "bloomberg"}}
|
||||
if err = repo.SaveGenerationWithQASources(context.Background(), ticket14UserA, "00000000-0000-0000-0000-000000005312", summary, json.RawMessage(`{"status":"succeeded"}`), now, sources, 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := &qa53Provider{}
|
||||
resolver := ai.QAResolver{Repo: repo, Factory: func(models.ResolvedSummaryModel) (ai.Provider, error) { return p, nil }}
|
||||
f := &qa53Fixture{db: db, repo: repo, provider: p, now: now}
|
||||
f.service = summaryqa.New(repo, resolver)
|
||||
f.service.Clock = func() time.Time { return f.now }
|
||||
h := handlers.New(repo, &config.Config{JWTSecret: "qa53"}, nil, nil, nil, nil)
|
||||
h.SetQAUseCase(f.service)
|
||||
f.router = api.SetupRouter(h, "qa53")
|
||||
return f
|
||||
}
|
||||
func (f *qa53Fixture) call(t *testing.T, method, owner, path, body string, want int) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if owner != "" {
|
||||
token, err := auth.GenerateToken(owner, "fixture@test", "user", "qa53")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
f.router.ServeHTTP(w, req)
|
||||
if w.Code != want {
|
||||
t.Fatalf("%s %s status=%d want=%d body=%s", method, path, w.Code, want, w.Body)
|
||||
}
|
||||
return w
|
||||
}
|
||||
func qa53Body(id, question string) string {
|
||||
raw, _ := json.Marshal(summaryqa.Question{RequestID: id, Passage: "selected passage", Question: question})
|
||||
return string(raw)
|
||||
}
|
||||
func qa53Path() string { return "/api/summaries/" + qa53Summary + "/conversation" }
|
||||
|
||||
func TestTicket53OwnerScopedConversationIdempotencyExpirationAndDeletionPostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
path := qa53Path()
|
||||
f.call(t, "GET", "", path, "", 401)
|
||||
for _, method := range []string{"GET", "POST", "DELETE"} {
|
||||
p := path
|
||||
if method == "POST" {
|
||||
p += "/messages"
|
||||
}
|
||||
f.call(t, method, ticket14UserB, p, qa53Body(qa53Request, "foreign"), 404)
|
||||
}
|
||||
first := f.call(t, "GET", ticket14UserA, path, "", 200)
|
||||
if !strings.Contains(first.Body.String(), `"mode":"stateless"`) || !strings.Contains(first.Body.String(), `"source_count":1`) || strings.Contains(first.Body.String(), "PRIVATE_SOURCE_") {
|
||||
t.Fatal("unexpected conversation metadata", first.Body)
|
||||
}
|
||||
f.call(t, "POST", ticket14UserA, path+"/messages", qa53Body(qa53Request, "QUESTION_ONE"), 200)
|
||||
replay := f.call(t, "POST", ticket14UserA, path+"/messages", qa53Body(qa53Request, "QUESTION_ONE"), 200)
|
||||
if !strings.Contains(replay.Body.String(), `"replayed":true`) || len(f.provider.prompts) != 1 {
|
||||
t.Fatal("replay invoked provider")
|
||||
}
|
||||
f.call(t, "POST", ticket14UserA, path+"/messages", qa53Body(qa53Request, "changed"), 409)
|
||||
f.call(t, "POST", ticket14UserA, path+"/messages", qa53Body("00000000-0000-0000-0000-000000005313", "QUESTION_TWO"), 200)
|
||||
if len(f.provider.prompts) != 2 || !strings.Contains(f.provider.prompts[1], "OWN_SYNTHESIS_MARKER") || !strings.Contains(f.provider.prompts[1], "QUESTION_ONE") {
|
||||
t.Fatal("missing own synthesis/history")
|
||||
}
|
||||
for _, prompt := range f.provider.prompts {
|
||||
if strings.Contains(prompt, "PRIVATE_SOURCE_") {
|
||||
t.Fatal("stateless answer sent articles")
|
||||
}
|
||||
}
|
||||
f.now = f.now.Add(7 * 24 * time.Hour)
|
||||
expired := f.call(t, "GET", ticket14UserA, path, "", 200)
|
||||
if !strings.Contains(expired.Body.String(), `"sources_expired":true`) || !strings.Contains(expired.Body.String(), `"source_count":0`) || !strings.Contains(expired.Body.String(), "QUESTION_ONE") {
|
||||
t.Fatal("expiration erased messages or exposed sources", expired.Body)
|
||||
}
|
||||
var n int
|
||||
if err := f.db.QueryRow(`SELECT count(*) FROM summary_qa_sources`).Scan(&n); err != nil || n != 0 {
|
||||
t.Fatal("expired sources not deleted", n, err)
|
||||
}
|
||||
f.call(t, "POST", ticket14UserA, path+"/messages", qa53Body("00000000-0000-0000-0000-000000005314", "after expiry"), 200)
|
||||
f.call(t, "DELETE", ticket14UserA, path, "", 204)
|
||||
for _, table := range []string{"summary_qa_sources", "summary_qa_turns"} {
|
||||
if err := f.db.QueryRow(`SELECT count(*) FROM ` + table).Scan(&n); err != nil || n != 0 {
|
||||
t.Fatal("new Q&A data not deleted", table, n, err)
|
||||
}
|
||||
}
|
||||
for _, table := range []string{"articles", "report_messages", "summaries"} {
|
||||
if err := f.db.QueryRow(`SELECT count(*) FROM ` + table).Scan(&n); err != nil || n != 1 {
|
||||
t.Fatal("unrelated history modified", table, n, err)
|
||||
}
|
||||
}
|
||||
recreated := f.call(t, "GET", ticket14UserA, path, "", 200)
|
||||
if strings.Contains(recreated.Body.String(), "QUESTION_ONE") || !strings.Contains(recreated.Body.String(), `"source_count":0`) {
|
||||
t.Fatal("deleted data resurrected")
|
||||
}
|
||||
}
|
||||
func TestTicket53RetentionDecreasePurgesAndIncreaseNeverRestoresPostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
if _, err := f.db.Exec(`UPDATE summary_qa_conversations SET generated_at=generated_at-interval '2 days',source_expires_at=source_expires_at-interval '2 days'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, value := range []string{"0", "31", "null", "1.5", "\"7\""} {
|
||||
f.call(t, "PUT", ticket14UserA, "/api/me/preferences", `{"language":"fr","ranking_mode":"title","source_article_retention_days":`+value+`}`, 400)
|
||||
}
|
||||
f.call(t, "PUT", ticket14UserA, "/api/me/preferences", `{"language":"fr","ranking_mode":"title","source_article_retention_days":1}`, 200)
|
||||
var first time.Time
|
||||
var count int
|
||||
if err := f.db.QueryRow(`SELECT source_expires_at FROM summary_qa_conversations`).Scan(&first); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.db.QueryRow(`SELECT count(*) FROM summary_qa_sources`).Scan(&count); err != nil || count != 0 {
|
||||
t.Fatal("decrease left expired sources", count, err)
|
||||
}
|
||||
f.call(t, "PUT", ticket14UserA, "/api/me/preferences", `{"language":"fr","ranking_mode":"title","source_article_retention_days":30}`, 200)
|
||||
var after time.Time
|
||||
if err := f.db.QueryRow(`SELECT source_expires_at FROM summary_qa_conversations`).Scan(&after); err != nil || !first.Equal(after) {
|
||||
t.Fatal("increase extended existing expiry", first, after, err)
|
||||
}
|
||||
f.call(t, "PUT", ticket14UserA, "/api/me/preferences", `{"language":"en","ranking_mode":"title"}`, 200)
|
||||
pref, err := f.repo.GetUserPreferences(ticket14UserA)
|
||||
if err != nil || pref.SourceArticleRetentionDays != 30 {
|
||||
t.Fatal("omission reset preference", pref, err)
|
||||
}
|
||||
}
|
||||
func TestTicket53ConcurrentQuestionsAreSerializedAndErrorsContainNoPayloadPostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
path := qa53Path() + "/messages"
|
||||
f.provider.started = make(chan struct{}, 1)
|
||||
f.provider.release = make(chan struct{})
|
||||
done := make(chan *httptest.ResponseRecorder, 1)
|
||||
go func() { done <- f.call(t, "POST", ticket14UserA, path, qa53Body(qa53Request, "pending"), 200) }()
|
||||
select {
|
||||
case <-f.provider.started:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("provider not reached")
|
||||
}
|
||||
f.call(t, "POST", ticket14UserA, path, qa53Body(qa53Request, "pending"), 409)
|
||||
f.call(t, "POST", ticket14UserA, path, qa53Body("00000000-0000-0000-0000-000000005315", "another"), 409)
|
||||
close(f.provider.release)
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("provider did not finish")
|
||||
}
|
||||
f.provider.started = nil
|
||||
f.provider.release = nil
|
||||
f.provider.err = errors.New("PRIVATE_PROVIDER_PAYLOAD")
|
||||
failure := f.call(t, "POST", ticket14UserA, path, qa53Body("00000000-0000-0000-0000-000000005316", "failed"), 502)
|
||||
if strings.Contains(failure.Body.String(), "PRIVATE_PROVIDER") {
|
||||
t.Fatal("provider payload exposed")
|
||||
}
|
||||
before := len(f.provider.prompts)
|
||||
f.call(t, "POST", ticket14UserA, path, qa53Body("00000000-0000-0000-0000-000000005316", "failed"), 502)
|
||||
if len(f.provider.prompts) != before {
|
||||
t.Fatal("failed replay regenerated")
|
||||
}
|
||||
}
|
||||
func TestTicket53JanitorAndModelAvailabilityAndLogConfidentialityPostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
path := qa53Path()
|
||||
var logs bytes.Buffer
|
||||
old := gin.DefaultWriter
|
||||
gin.DefaultWriter = &logs
|
||||
defer func() { gin.DefaultWriter = old }()
|
||||
// Recreate the logger after setting its destination; never record the query or body.
|
||||
h := handlers.New(f.repo, &config.Config{JWTSecret: "qa53"}, nil, nil, nil, nil)
|
||||
h.SetQAUseCase(f.service)
|
||||
f.router = api.SetupRouter(h, "qa53")
|
||||
f.call(t, "POST", ticket14UserA, path+"/messages?secret=PRIVATE_QUERY", qa53Body(qa53Request, "PRIVATE_QUESTION"), 200)
|
||||
if strings.Contains(logs.String(), "PRIVATE_") {
|
||||
t.Fatal("content appeared in access logs")
|
||||
}
|
||||
if _, err := f.db.Exec(`UPDATE ai_provider_models SET enabled=false`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.call(t, "POST", ticket14UserA, path+"/messages", qa53Body("00000000-0000-0000-0000-000000005317", "unavailable model"), 409)
|
||||
if err := f.repo.PurgeExpiredQASources(context.Background(), f.now.Add(7*24*time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var n int
|
||||
if err := f.db.QueryRow(`SELECT count(*) FROM summary_qa_sources`).Scan(&n); err != nil || n != 0 {
|
||||
t.Fatal("janitor did not purge", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket53QuestionRejectsUnknownFieldsAndTrailingJSONPostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
body := qa53Body(qa53Request, "question")
|
||||
for _, raw := range []string{strings.TrimSuffix(body, "}") + `,"user_id":"` + ticket14UserB + `"}`, body + ` {}`, body + ` trailing`} {
|
||||
f.call(t, "POST", ticket14UserA, qa53Path()+"/messages", raw, 400)
|
||||
}
|
||||
if len(f.provider.prompts) != 0 {
|
||||
t.Fatal("invalid JSON reached provider")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket53PendingRecoveryDeletionAndCapturedExpiryPostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
ctx := context.Background()
|
||||
q := summaryqa.Question{RequestID: qa53Request, Passage: "p", Question: "q"}
|
||||
work, err := f.repo.BeginQAQuestion(ctx, ticket14UserA, qa53Summary, q, f.now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recovered, err := f.repo.BeginQAQuestion(ctx, ticket14UserA, qa53Summary, q, f.now.Add(summaryqa.PendingLifetime))
|
||||
if err != nil || !recovered.Replay || recovered.Turn.Status != "failed" {
|
||||
t.Fatal("stale pending not recoverable", recovered, err)
|
||||
}
|
||||
if _, err = f.repo.FinishQAQuestion(ctx, ticket14UserA, qa53Summary, work.Turn.ID, "late answer", "", f.now.Add(summaryqa.PendingLifetime)); !errors.Is(err, summaryqa.ErrConflict) {
|
||||
t.Fatal("late answer resurrected failed turn", err)
|
||||
}
|
||||
if _, err = f.db.Exec(`UPDATE users SET source_article_retention_days=30`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := f.repo.GetQAConversation(ctx, ticket14UserA, qa53Summary, f.now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = f.repo.DeleteQAConversation(ctx, ticket14UserA, qa53Summary); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := f.repo.GetQAConversation(ctx, ticket14UserA, qa53Summary, f.now)
|
||||
if err != nil || !before.SourceExpiresAt.Equal(after.SourceExpiresAt) || after.SourceCount != 0 || len(after.Messages) != 0 {
|
||||
t.Fatal("deletion extended expiry or resurrected data", before, after, err)
|
||||
}
|
||||
if _, err = f.db.Exec(`INSERT INTO summary_qa_conversations(summary_id,user_id,generated_at,source_expires_at,retention_days) VALUES($1,$2,NOW(),NOW(),7)`, qa53Summary, ticket14UserB); err == nil {
|
||||
t.Fatal("owner mismatch permitted by database")
|
||||
}
|
||||
}
|
||||
func TestTicket53GenerationRetentionAndOutcomeAreAtomicPostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
ctx := context.Background()
|
||||
model := ticket14ModelA
|
||||
id := "00000000-0000-0000-0000-000000005320"
|
||||
s := &models.Summary{ID: id, Content: "new summary", GeneratedAt: f.now, SummaryModelID: &model}
|
||||
if _, err := f.db.Exec(`UPDATE users SET source_article_retention_days=30 WHERE id=$1`, ticket14UserA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := []models.SummarySourceArticle{{Title: "transient", Content: "body", Source: "bloomberg"}}
|
||||
err := f.repo.SaveGenerationWithQASources(ctx, ticket14UserA, "00000000-0000-0000-0000-000000005321", s, json.RawMessage(`{"status":"succeeded"}`), f.now, source, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var expires time.Time
|
||||
if err = f.db.QueryRow(`SELECT source_expires_at FROM summary_qa_conversations WHERE summary_id=$1`, id).Scan(&expires); err != nil || !expires.Equal(f.now.Add(24*time.Hour)) {
|
||||
t.Fatal("captured generation duration extended", expires, err)
|
||||
}
|
||||
s.ID = "00000000-0000-0000-0000-000000005322"
|
||||
err = f.repo.SaveGenerationWithQASources(ctx, ticket14UserA, "00000000-0000-0000-0000-000000005323", s, json.RawMessage(`invalid`), f.now, source, 7)
|
||||
if err == nil {
|
||||
t.Fatal("invalid outcome accepted")
|
||||
}
|
||||
var n int
|
||||
if err = f.db.QueryRow(`SELECT count(*) FROM summaries WHERE id=$1`, s.ID).Scan(&n); err != nil || n != 0 {
|
||||
t.Fatal("summary survived rollback", n, err)
|
||||
}
|
||||
if err = f.db.QueryRow(`SELECT count(*) FROM summary_qa_conversations WHERE summary_id=$1`, s.ID).Scan(&n); err != nil || n != 0 {
|
||||
t.Fatal("QA snapshot survived rollback", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket53ExchangeOrderDoesNotDependOnUUIDOrClockPrecisionPostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
path := qa53Path() + "/messages"
|
||||
second := "00000000-0000-0000-0000-000000005318"
|
||||
f.call(t, "POST", ticket14UserA, path, qa53Body(qa53Request, "FIRST"), 200)
|
||||
f.call(t, "POST", ticket14UserA, path, qa53Body(second, "SECOND"), 200)
|
||||
if _, err := f.db.Exec(`UPDATE summary_qa_turns SET id=CASE WHEN request_id=$1 THEN 'ffffffff-ffff-ffff-ffff-ffffffffffff'::uuid ELSE '00000000-0000-0000-0000-000000000001'::uuid END`, qa53Request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, err := f.repo.GetQAConversation(context.Background(), ticket14UserA, qa53Summary, f.now)
|
||||
if err != nil || len(c.Messages) != 2 || c.Messages[0].Question != "FIRST" || c.Messages[1].Question != "SECOND" {
|
||||
t.Fatalf("conversation reordered: %+v %v", c.Messages, err)
|
||||
}
|
||||
}
|
||||
147
backend/internal/api/qa_quota_ticket55_postgres_test.go
Normal file
147
backend/internal/api/qa_quota_ticket55_postgres_test.go
Normal file
@ -0,0 +1,147 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func qa55Call(t *testing.T, f *qa53Fixture, owner, path, id, question string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
token, err := auth.GenerateToken(owner, "fixture@test", "user", "qa53")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := httptest.NewRequest("POST", path, strings.NewReader(qa53Body(id, question)))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
w := httptest.NewRecorder()
|
||||
f.router.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
func qa55ID(i int) string { return fmt.Sprintf("00000000-0000-0000-0000-%012d", 550000+i) }
|
||||
func TestTicket55MinuteQuotaReturns429AndReplayIsFreePostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
path := qa53Path() + "/messages"
|
||||
for i := 0; i < 10; i++ {
|
||||
w := qa55Call(t, f, ticket14UserA, path, qa55ID(i), "question")
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("call %d status=%d body=%s", i, w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
replay := qa55Call(t, f, ticket14UserA, path, qa55ID(0), "question")
|
||||
if replay.Code != 200 || !strings.Contains(replay.Body.String(), `"replayed":true`) || len(f.provider.prompts) != 10 {
|
||||
t.Fatal("replay consumed a call", replay.Code, replay.Body)
|
||||
}
|
||||
f.now = f.now.Add(24 * time.Hour) // application clock skew must not reset server quota
|
||||
limited := qa55Call(t, f, ticket14UserA, path, qa55ID(10), "question")
|
||||
if limited.Code != 429 {
|
||||
t.Fatalf("11th call was not rate limited: status=%d body=%s providerCalls=%d", limited.Code, limited.Body, len(f.provider.prompts))
|
||||
}
|
||||
var body map[string]string
|
||||
_ = json.Unmarshal(limited.Body.Bytes(), &body)
|
||||
seconds, err := strconv.Atoi(limited.Header().Get("Retry-After"))
|
||||
if body["error"] != "qa_rate_limited" || err != nil || seconds < 1 || seconds > 60 || len(f.provider.prompts) != 10 {
|
||||
t.Fatalf("invalid quota response: headers=%v body=%s", limited.Header(), limited.Body)
|
||||
}
|
||||
var turns int
|
||||
if err := f.db.QueryRow(`SELECT count(*) FROM summary_qa_turns`).Scan(&turns); err != nil || turns != 10 {
|
||||
t.Fatal("429 consumed a conversation turn", turns, err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestTicket55FailureConsumesQuotaButDenialAndIdempotentReplayDoNotPostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
path := qa53Path() + "/messages"
|
||||
for i := 0; i < 9; i++ {
|
||||
if w := qa55Call(t, f, ticket14UserA, path, qa55ID(i), "question"); w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
f.provider.err = errors.New("PRIVATE_PROVIDER_FAILURE")
|
||||
failed := qa55Call(t, f, ticket14UserA, path, qa55ID(9), "failed")
|
||||
if failed.Code != 502 {
|
||||
t.Fatal(failed.Code, failed.Body)
|
||||
}
|
||||
replay := qa55Call(t, f, ticket14UserA, path, qa55ID(9), "failed")
|
||||
if replay.Code != 502 || len(f.provider.prompts) != 10 {
|
||||
t.Fatal("failed replay consumed quota", replay.Code)
|
||||
}
|
||||
rejected := qa55Call(t, f, ticket14UserA, path, qa55ID(10), "retry me")
|
||||
if rejected.Code != 429 {
|
||||
t.Fatal("failed invocation not counted", rejected.Code, rejected.Body)
|
||||
}
|
||||
f.call(t, "DELETE", ticket14UserA, qa53Path(), "", 204)
|
||||
if w := qa55Call(t, f, ticket14UserA, path, qa55ID(10), "retry me"); w.Code != 429 {
|
||||
t.Fatal("deleting conversation reset quota", w.Code, w.Body)
|
||||
}
|
||||
var calls, turns int
|
||||
if err := f.db.QueryRow(`SELECT count(*) FROM summary_qa_provider_calls WHERE user_id=$1`, ticket14UserA).Scan(&calls); err != nil || calls != 10 {
|
||||
t.Fatal("attempt accounting", calls, err)
|
||||
}
|
||||
if err := f.db.QueryRow(`SELECT count(*) FROM summary_qa_turns`).Scan(&turns); err != nil || turns != 0 {
|
||||
t.Fatal("429 exhausted conversation turns", turns, err)
|
||||
}
|
||||
// Exact rolling minute boundary: these events no longer occupy the window.
|
||||
if _, err := f.db.Exec(`UPDATE summary_qa_provider_calls SET started_at=clock_timestamp()-interval '60 seconds'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.provider.err = nil
|
||||
accepted := qa55Call(t, f, ticket14UserA, path, qa55ID(10), "retry me")
|
||||
if accepted.Code != 200 {
|
||||
t.Fatal("429 key poisoned after window elapsed", accepted.Code, accepted.Body)
|
||||
}
|
||||
}
|
||||
func TestTicket55SlidingDayQuotaAndAccountIsolationPostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
path := qa53Path() + "/messages"
|
||||
if _, err := f.db.Exec(`INSERT INTO summary_qa_provider_calls(user_id,turn_id,started_at) SELECT $1,gen_random_uuid(),clock_timestamp()-interval '2 hours' FROM generate_series(1,100)`, ticket14UserA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
limited := qa55Call(t, f, ticket14UserA, path, qa55ID(0), "question")
|
||||
seconds, err := strconv.Atoi(limited.Header().Get("Retry-After"))
|
||||
if limited.Code != 429 || err != nil || seconds < 78000 || seconds > 79200 || len(f.provider.prompts) != 0 {
|
||||
t.Fatalf("day window not enforced: %d retry=%d body=%s", limited.Code, seconds, limited.Body)
|
||||
}
|
||||
pathB := qa55Summary(t, f, qa55ID(100), ticket14UserB)
|
||||
if w := qa55Call(t, f, ticket14UserB, pathB, qa55ID(1), "question"); w.Code != 200 {
|
||||
t.Fatal("account quota leaked", w.Code, w.Body)
|
||||
}
|
||||
if _, err = f.db.Exec(`UPDATE summary_qa_provider_calls SET started_at=clock_timestamp()-interval '24 hours' WHERE user_id=$1 AND turn_id=(SELECT turn_id FROM summary_qa_provider_calls WHERE user_id=$1 ORDER BY started_at,turn_id LIMIT 1)`, ticket14UserA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := qa55Call(t, f, ticket14UserA, path, qa55ID(0), "question"); w.Code != 200 {
|
||||
t.Fatal("24h boundary did not release quota", w.Code, w.Body)
|
||||
}
|
||||
var n int
|
||||
if err = f.db.QueryRow(`SELECT count(*) FROM summary_qa_provider_calls WHERE user_id=$1`, ticket14UserA).Scan(&n); err != nil || n != 100 {
|
||||
t.Fatal("sliding day accounting wrong", n, err)
|
||||
}
|
||||
}
|
||||
func TestTicket55OnlyActualProviderInvocationsConsumeQuotaPostgres(t *testing.T) {
|
||||
f := qa53Setup(t)
|
||||
path := qa53Path() + "/messages"
|
||||
if _, err := f.db.Exec(`UPDATE ai_provider_models SET enabled=false`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := qa55Call(t, f, ticket14UserA, path, qa55ID(1), "no model"); w.Code != 409 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if _, err := f.db.Exec(`UPDATE ai_provider_models SET enabled=true; UPDATE summaries SET content=repeat('x',128000)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := qa55Call(t, f, ticket14UserA, path, qa55ID(2), "too much context"); w.Code != 422 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
var n int
|
||||
if err := f.db.QueryRow(`SELECT count(*) FROM summary_qa_provider_calls`).Scan(&n); err != nil || n != 0 || len(f.provider.prompts) != 0 {
|
||||
t.Fatal("unlaunched calls counted", n, err)
|
||||
}
|
||||
}
|
||||
76
backend/internal/api/qa_ticket53_postgres_test.go
Normal file
76
backend/internal/api/qa_ticket53_postgres_test.go
Normal file
@ -0,0 +1,76 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTicket53RetentionPreferenceHasExplicitUnitAndDefault(t *testing.T) {
|
||||
f, ok := reflect.TypeOf(models.UserPreferences{}).FieldByName("SourceArticleRetentionDays")
|
||||
if !ok || f.Type.Kind() != reflect.Int || f.Tag.Get("json") != "source_article_retention_days" {
|
||||
t.Fatal("missing bounded source_article_retention_days preference")
|
||||
}
|
||||
}
|
||||
func TestTicket53NewStorageMigrationPreservesLegacyPostgres(t *testing.T) {
|
||||
db := ticket14DB(t)
|
||||
for _, q := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY)`,
|
||||
`CREATE TABLE summaries(id UUID PRIMARY KEY,user_id UUID REFERENCES users(id))`,
|
||||
`CREATE TABLE articles(id TEXT PRIMARY KEY,content TEXT)`,
|
||||
`CREATE TABLE report_messages(id TEXT PRIMARY KEY,content TEXT)`,
|
||||
`INSERT INTO articles VALUES('legacy','keep article')`,
|
||||
`INSERT INTO report_messages VALUES('legacy','keep message')`,
|
||||
`INSERT INTO users VALUES('` + ticket14UserA + `')`,
|
||||
} {
|
||||
if _, err := db.Exec(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
raw, err := os.ReadFile("../database/migrations/000024_summary_qa.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(string(raw)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var days int
|
||||
if err = db.QueryRow(`SELECT source_article_retention_days FROM users`).Scan(&days); err != nil || days != 7 {
|
||||
t.Fatalf("retention=%d err=%v", days, err)
|
||||
}
|
||||
for _, days := range []int{0, 31} {
|
||||
if _, err = db.Exec(`UPDATE users SET source_article_retention_days=$1`, days); err == nil {
|
||||
t.Fatalf("invalid retention accepted: %d", days)
|
||||
}
|
||||
}
|
||||
for _, table := range []string{"summary_qa_conversations", "summary_qa_sources", "summary_qa_turns"} {
|
||||
var n int
|
||||
if err = db.QueryRow(`SELECT COUNT(*) FROM ` + table).Scan(&n); err != nil || n != 0 {
|
||||
t.Fatalf("new table %s: count=%d err=%v", table, n, err)
|
||||
}
|
||||
}
|
||||
for _, table := range []string{"articles", "report_messages"} {
|
||||
var n int
|
||||
if err = db.QueryRow(`SELECT COUNT(*) FROM ` + table).Scan(&n); err != nil || n != 1 {
|
||||
t.Fatal("legacy modified", table, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func installQATables53(t *testing.T, db *sql.DB) {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile("../database/migrations/000024_summary_qa.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parts := strings.SplitN(string(raw), "CREATE UNIQUE INDEX", 2)
|
||||
if len(parts) != 2 {
|
||||
t.Fatal("Q&A schema marker missing")
|
||||
}
|
||||
if _, err = db.Exec("CREATE UNIQUE INDEX" + parts[1]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@ -16,7 +16,7 @@ import (
|
||||
func TestTicket50IncompatibleRankingRemainsAvailableForSynthesisPostgres(t *testing.T) {
|
||||
db := ticket14DB(t)
|
||||
for _, q := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,language TEXT,ranking_mode TEXT,summary_prompt_token_budget INT,summary_model_id UUID,ranking_model_id UUID,updated_at TIMESTAMPTZ)`,
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,language TEXT,ranking_mode TEXT,summary_prompt_token_budget INT,source_article_retention_days INT NOT NULL DEFAULT 7,summary_model_id UUID,ranking_model_id UUID,updated_at TIMESTAMPTZ)`,
|
||||
`CREATE TABLE ai_providers(id UUID PRIMARY KEY,name TEXT,endpoint TEXT,api_key_encrypted TEXT)`,
|
||||
`CREATE TABLE ai_provider_models(id UUID PRIMARY KEY,provider_id UUID,model TEXT,enabled BOOLEAN)`,
|
||||
`INSERT INTO users(id) VALUES('` + ticket14UserA + `')`,
|
||||
|
||||
@ -17,7 +17,7 @@ import (
|
||||
func TestTicket49RankingPreferenceMigrationValidationResolutionPostgres(t *testing.T) {
|
||||
db := ticket14DB(t)
|
||||
for _, q := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,language TEXT DEFAULT 'fr',ranking_mode TEXT DEFAULT 'title',summary_prompt_token_budget INT DEFAULT 250000,summary_model_id UUID,updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,language TEXT DEFAULT 'fr',ranking_mode TEXT DEFAULT 'title',summary_prompt_token_budget INT DEFAULT 250000,source_article_retention_days INT NOT NULL DEFAULT 7,summary_model_id UUID,updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE ai_providers(id UUID PRIMARY KEY,name TEXT,endpoint TEXT,api_key_encrypted TEXT)`,
|
||||
`CREATE TABLE ai_provider_models(id UUID PRIMARY KEY,provider_id UUID REFERENCES ai_providers(id),model TEXT,enabled BOOLEAN)`,
|
||||
`INSERT INTO users(id) VALUES('` + ticket14UserA + `'),('` + ticket14UserB + `')`,
|
||||
|
||||
@ -4,6 +4,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/api/handlers"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
|
||||
@ -13,7 +14,9 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
|
||||
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" },
|
||||
Skip: func(c *gin.Context) bool {
|
||||
return c.FullPath() == "/api/admin/ai-models/:id/test" || (strings.HasPrefix(c.Request.URL.Path, "/api/summaries/") && strings.Contains(c.Request.URL.Path, "/conversation"))
|
||||
},
|
||||
}))
|
||||
|
||||
r.Use(func(c *gin.Context) {
|
||||
@ -53,6 +56,10 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
|
||||
authed.GET("/summaries/status", h.GetGeneratingStatus)
|
||||
authed.POST("/summaries/generate", h.GenerateSummary)
|
||||
|
||||
authed.GET("/summaries/:id/conversation", h.GetSummaryConversation)
|
||||
authed.POST("/summaries/:id/conversation/messages", h.AskSummaryQuestion)
|
||||
authed.DELETE("/summaries/:id/conversation", h.DeleteSummaryConversation)
|
||||
|
||||
authed.GET("/reports", h.ListReports)
|
||||
authed.POST("/reports", h.CreateReport)
|
||||
authed.DELETE("/reports/:id", h.DeleteReport)
|
||||
|
||||
@ -65,7 +65,7 @@ func TestManualGenerationResolvesAccountModelsAndSnapshotsWithoutGlobalFallbackP
|
||||
db := ticket14DB(t)
|
||||
const rankingModel = "00000000-0000-0000-0000-000000001530"
|
||||
for _, q := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,email TEXT,password_hash TEXT,role TEXT,language TEXT DEFAULT 'en',ranking_mode TEXT DEFAULT 'title',summary_prompt_token_budget INT NOT NULL DEFAULT 250000,ranking_model_id UUID,summary_model_id UUID,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,email TEXT,password_hash TEXT,role TEXT,language TEXT DEFAULT 'en',ranking_mode TEXT DEFAULT 'title',summary_prompt_token_budget INT NOT NULL DEFAULT 250000,ranking_model_id UUID,source_article_retention_days INT NOT NULL DEFAULT 7,summary_model_id UUID,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE ai_providers(id UUID PRIMARY KEY,name TEXT,api_key_encrypted TEXT DEFAULT '',model TEXT,endpoint TEXT,is_active BOOLEAN DEFAULT false)`,
|
||||
`CREATE TABLE ai_provider_models(id UUID PRIMARY KEY,provider_id UUID REFERENCES ai_providers(id),model TEXT,enabled BOOLEAN DEFAULT true)`,
|
||||
`CREATE TABLE settings(key TEXT PRIMARY KEY,value TEXT)`,
|
||||
@ -89,6 +89,7 @@ func TestManualGenerationResolvesAccountModelsAndSnapshotsWithoutGlobalFallbackP
|
||||
if _, err := db.Exec(`UPDATE users SET ranking_model_id=CASE WHEN summary_model_id='` + ticket14ModelA + `' THEN '` + rankingModel + `'::uuid WHEN summary_model_id='` + ticket14ModelB + `' THEN '` + ticket14ModelA + `'::uuid ELSE NULL END`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
installQATables53(t, db)
|
||||
installJobSchema(t, db)
|
||||
repo := models.NewRepository(db)
|
||||
feed := &selectionFeed{}
|
||||
|
||||
@ -28,7 +28,7 @@ const (
|
||||
func TestPerUserSummaryModelCatalogAPIIsSafeScopedAndPersistsPreferencePostgres(t *testing.T) {
|
||||
db := ticket14DB(t)
|
||||
for _, statement := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,email TEXT NOT NULL,password_hash TEXT NOT NULL,role TEXT NOT NULL,language TEXT NOT NULL DEFAULT 'fr',ranking_mode TEXT NOT NULL DEFAULT 'title',summary_prompt_token_budget INT NOT NULL DEFAULT 250000,ranking_model_id UUID,summary_model_id UUID,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,email TEXT NOT NULL,password_hash TEXT NOT NULL,role TEXT NOT NULL,language TEXT NOT NULL DEFAULT 'fr',ranking_mode TEXT NOT NULL DEFAULT 'title',summary_prompt_token_budget INT NOT NULL DEFAULT 250000,ranking_model_id UUID,source_article_retention_days INT NOT NULL DEFAULT 7,summary_model_id UUID,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE ai_providers(id UUID PRIMARY KEY,name TEXT NOT NULL,api_key_encrypted TEXT NOT NULL,model TEXT NOT NULL,endpoint TEXT NOT NULL,is_active BOOLEAN NOT NULL DEFAULT FALSE,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE ai_provider_models(id UUID PRIMARY KEY,provider_id UUID NOT NULL REFERENCES ai_providers(id),model TEXT NOT NULL,enabled BOOLEAN NOT NULL DEFAULT TRUE,UNIQUE(provider_id,model))`,
|
||||
`ALTER TABLE users ADD CONSTRAINT users_summary_model_fk FOREIGN KEY(summary_model_id) REFERENCES ai_provider_models(id) ON DELETE RESTRICT`,
|
||||
@ -119,7 +119,7 @@ func TestPerUserSummaryModelCatalogAPIIsSafeScopedAndPersistsPreferencePostgres(
|
||||
func TestAdminSummaryModelCatalogCRUDIsSeparateFromProviderConfigAndProtectsSelectedModelPostgres(t *testing.T) {
|
||||
db := ticket14DB(t)
|
||||
for _, statement := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,email TEXT NOT NULL,password_hash TEXT NOT NULL,role TEXT NOT NULL,summary_prompt_token_budget INT NOT NULL DEFAULT 250000,ranking_model_id UUID,summary_model_id UUID,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,email TEXT NOT NULL,password_hash TEXT NOT NULL,role TEXT NOT NULL,summary_prompt_token_budget INT NOT NULL DEFAULT 250000,ranking_model_id UUID,source_article_retention_days INT NOT NULL DEFAULT 7,summary_model_id UUID,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE ai_providers(id UUID PRIMARY KEY,name TEXT NOT NULL,api_key_encrypted TEXT NOT NULL,model TEXT NOT NULL,endpoint TEXT NOT NULL,is_active BOOLEAN NOT NULL DEFAULT FALSE,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE ai_provider_models(id UUID PRIMARY KEY,provider_id UUID NOT NULL REFERENCES ai_providers(id),model TEXT NOT NULL,enabled BOOLEAN NOT NULL DEFAULT TRUE,UNIQUE(provider_id,model))`,
|
||||
`ALTER TABLE users ADD CONSTRAINT users_summary_model_fk FOREIGN KEY(summary_model_id) REFERENCES ai_provider_models(id) ON DELETE RESTRICT`,
|
||||
|
||||
Reference in New Issue
Block a user