package api_test import ( "encoding/json" "fmt" "os" "reflect" "strings" "testing" "github.com/tradarr/backend/internal/summaryqa" ) func TestTicket63OptionalPassageAPIIdempotenceAndOwnerScopePostgres(t *testing.T) { for _, web := range []bool{false, true} { t.Run(fmt.Sprint(web), func(t *testing.T) { f := qa53Setup(t) p := &web60Provider{result: summaryqa.AnswerResult{Answer: "chat answer", WebSearchPerformed: true, Citations: []summaryqa.Citation{{Title: "current source", URL: "https://example.com/current"}}}} if web { web60Bind(t, f, p) } path := qa53Path() + "/messages" body := fmt.Sprintf(`{"request_id":"%s","question":"GENERAL_QUESTION","use_web_search":%t}`, qa53Request, web) first := web60Turn(t, f.call(t, "POST", ticket14UserA, path, body, 200).Body.Bytes()) if first.Passage != "" || first.Answer == "" { t.Fatal("general chat requires a passage") } // Omitted and explicit empty passage represent the same idempotent payload. empty := strings.TrimSuffix(body, "}") + `,"passage":""}` replay := web60Turn(t, f.call(t, "POST", ticket14UserA, path, empty, 200).Body.Bytes()) if !replay.Replayed || replay.ID != first.ID || !reflect.DeepEqual(replay.Citations, first.Citations) { t.Fatal("empty passage replay changed result") } for _, changed := range []string{strings.TrimSuffix(body, "}") + `,"passage":"attached"}`, strings.Replace(body, "GENERAL_QUESTION", "changed", 1), strings.Replace(body, fmt.Sprintf(`"use_web_search":%t`, web), fmt.Sprintf(`"use_web_search":%t`, !web), 1)} { f.call(t, "POST", ticket14UserA, path, changed, 409) } f.call(t, "POST", ticket14UserB, path, body, 404) f.call(t, "GET", ticket14UserB, qa53Path(), "", 404) // A later attachment remains distinct from the question and is persisted. next := strings.Replace(empty, qa53Request, "00000000-0000-0000-0000-000000006302", 1) next = strings.Replace(next, `"passage":""`, `"passage":"ATTACHED_PASSAGE"`, 1) attached := web60Turn(t, f.call(t, "POST", ticket14UserA, path, next, 200).Body.Bytes()) if attached.Passage != "ATTACHED_PASSAGE" || attached.Question != "GENERAL_QUESTION" { t.Fatal("attachment not stored separately") } if web { if len(p.requests) != 2 || p.requests[0].Summary != "OWN_SYNTHESIS_MARKER" || p.requests[0].Passage != "" || len(p.requests[1].History) != 1 || p.requests[1].History[0].Answer != "chat answer" || len(f.provider.prompts) != 0 { t.Fatal("web request lost full summary/history") } } else { if len(f.provider.prompts) != 2 || !strings.Contains(f.provider.prompts[1], "OWN_SYNTHESIS_MARKER") || !strings.Contains(f.provider.prompts[1], "A safe answer") { t.Fatal("normal adapter lost full chat context") } } }) } } func TestTicket63OnlyAnsweredHistoryEntersWebContextPostgres(t *testing.T) { f := qa53Setup(t) p := &web60Provider{result: summaryqa.AnswerResult{Answer: "first answer", WebSearchPerformed: true, Citations: []summaryqa.Citation{{Title: "OLD_CITATION", URL: "https://example.com/OLD_CITATION"}}}} web60Bind(t, f, p) firstBody := `{"request_id":"` + qa53Request + `","question":"ANSWERED_QUESTION","use_web_search":true}` f.call(t, "POST", ticket14UserA, qa53Path()+"/messages", firstBody, 200) for _, row := range []struct { ordinal int status, marker string }{{2, "failed", "FAILED_CONTEXT"}, {3, "pending", "PENDING_CONTEXT"}} { _, err := f.db.Exec(`INSERT INTO summary_qa_turns(conversation_id,request_id,ordinal,passage,question,answer,status,created_at) SELECT id,gen_random_uuid(),$1,'old passage',$2,$2,$3,$4 FROM summary_qa_conversations`, row.ordinal, row.marker, row.status, f.now.Add(-3*summaryqa.PendingLifetime)) if err != nil { t.Fatal(err) } } body := `{"request_id":"00000000-0000-0000-0000-000000006303","question":"NEXT_QUESTION","use_web_search":true}` f.call(t, "POST", ticket14UserA, qa53Path()+"/messages", body, 200) if len(p.requests) != 2 || len(p.requests[1].History) != 1 || p.requests[1].History[0].Question != "ANSWERED_QUESTION" { t.Fatal("non-answered history entered provider context") } raw, _ := json.Marshal(p.requests[1]) for _, secret := range []string{"FAILED_CONTEXT", "PENDING_CONTEXT", "PRIVATE_SOURCE", "OLD_CITATION", "request_id", "response_id"} { if strings.Contains(string(raw), secret) { t.Fatal("forbidden context field", secret) } } } func TestTicket63ExactAPIContextBoundaryAndFailureReplayPostgres(t *testing.T) { for _, web := range []bool{false, true} { for _, delta := range []int{0, 1} { t.Run(fmt.Sprintf("web=%t/delta=%d", web, delta), func(t *testing.T) { f := qa53Setup(t) p := &web60Provider{result: summaryqa.AnswerResult{Answer: "answer"}} if web { web60Bind(t, f, p) } summary := strings.Repeat("s", summaryqa.MaxContextBytes-len("é")+delta) if _, err := f.db.Exec(`UPDATE summaries SET content=$1 WHERE id=$2`, summary, qa53Summary); err != nil { t.Fatal(err) } body := fmt.Sprintf(`{"request_id":"%s","question":"é","use_web_search":%t}`, qa53Request, web) want := 200 if delta > 0 { want = 422 } for i := 0; i < 2; i++ { w := f.call(t, "POST", ticket14UserA, qa53Path()+"/messages", body, want) if delta > 0 && !strings.Contains(w.Body.String(), "qa_context_limit") { t.Fatal("wrong limit error") } } count := len(f.provider.prompts) + len(p.requests) if (delta == 0 && count != 1) || (delta > 0 && count != 0) { t.Fatal("wrong call count at context boundary", count) } if web && delta == 0 && p.requests[0].Summary != summary { t.Fatal("summary truncated") } }) } } } func TestTicket63MigrationPreservesExistingTurnsAndAllowsEmptyPassagePostgres(t *testing.T) { f := qa53Setup(t) f.call(t, "POST", ticket14UserA, qa53Path()+"/messages", qa53Body(qa53Request, "historical question"), 200) for _, direction := range []string{"down", "up"} { raw, err := os.ReadFile("../database/migrations/000027_qa_optional_passage." + direction + ".sql") if err != nil { t.Fatal(err) } if _, err = f.db.Exec(string(raw)); err != nil { t.Fatal(err) } } var passage, question, answer string if err := f.db.QueryRow(`SELECT passage,question,answer FROM summary_qa_turns WHERE request_id=$1`, qa53Request).Scan(&passage, &question, &answer); err != nil || passage != "selected passage" || question != "historical question" || answer != "A safe answer" { t.Fatal("migration changed historical content", err) } if _, err := f.db.Exec(`INSERT INTO summary_qa_turns(conversation_id,request_id,ordinal,question,status,created_at) SELECT id,gen_random_uuid(),2,'general','answered',NOW() FROM summary_qa_conversations`); err != nil { t.Fatal("omitted passage has no empty default", err) } for _, bad := range []any{nil, strings.Repeat("x", summaryqa.MaxPassageRunes+1)} { if _, err := f.db.Exec(`UPDATE summary_qa_turns SET passage=$1 WHERE ordinal=2`, bad); err == nil { t.Fatal("invalid passage accepted") } } // Even the down migration must preserve new general-chat turns. raw, _ := os.ReadFile("../database/migrations/000027_qa_optional_passage.down.sql") if _, err := f.db.Exec(string(raw)); err != nil { t.Fatal("rollback purges or rejects new historical turns", err) } var n int if err := f.db.QueryRow(`SELECT count(*) FROM summary_qa_turns`).Scan(&n); err != nil || n != 2 { t.Fatal("turn history lost", err) } }