feat(qa): add synthesis conversations with source retention (#52)
This commit is contained in:
@ -17,6 +17,12 @@ type GenerationHistory struct {
|
||||
|
||||
// SaveGeneration deliberately accepts no article data and commits both rows together.
|
||||
func (r *Repository) SaveGeneration(ctx context.Context, userID, id string, summary *Summary, outcome json.RawMessage, createdAt time.Time) error {
|
||||
return r.saveGeneration(ctx, userID, id, summary, outcome, createdAt, nil, 0, false)
|
||||
}
|
||||
func (r *Repository) SaveGenerationWithQASources(ctx context.Context, userID, id string, summary *Summary, outcome json.RawMessage, createdAt time.Time, sources []SummarySourceArticle, days int) error {
|
||||
return r.saveGeneration(ctx, userID, id, summary, outcome, createdAt, sources, days, true)
|
||||
}
|
||||
func (r *Repository) saveGeneration(ctx context.Context, userID, id string, summary *Summary, outcome json.RawMessage, createdAt time.Time, sources []SummarySourceArticle, days int, withQA bool) error {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
@ -27,6 +33,11 @@ func (r *Repository) SaveGeneration(ctx context.Context, userID, id string, summ
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO summaries (id,user_id,content,ai_provider_id,generated_at,summary_model_id,provider_name,model_name) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`, summary.ID, userID, summary.Content, summary.AIProviderID, summary.GeneratedAt, summary.SummaryModelID, summary.ProviderName, summary.ModelName); err != nil {
|
||||
return err
|
||||
}
|
||||
if withQA {
|
||||
if err = r.saveQASources(ctx, tx, userID, summary, sources, days); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
summaryID = &summary.ID
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO summary_generations (id,user_id,summary_id,outcome,created_at) VALUES ($1,$2,$3,$4,$5)`, id, userID, summaryID, string(outcome), createdAt); err != nil {
|
||||
|
||||
@ -13,19 +13,23 @@ var ErrInvalidPromptBudget = errors.New("invalid_prompt_budget")
|
||||
|
||||
// UserPreferences is scoped by the authenticated user ID, never by a client field.
|
||||
type UserPreferences struct {
|
||||
RankingModelID *string `json:"ranking_model_id" binding:"omitempty,uuid"`
|
||||
SummaryPromptTokenBudget int `json:"summary_prompt_token_budget" binding:"min=1,max=2000000"`
|
||||
Language string `json:"language" binding:"required,oneof=fr en"`
|
||||
RankingMode string `json:"ranking_mode" binding:"required,oneof=title title_content"`
|
||||
SummaryModelID *string `json:"summary_model_id" binding:"omitempty,uuid"`
|
||||
SourceArticleRetentionDays int `json:"source_article_retention_days" binding:"omitempty,min=1,max=30"`
|
||||
RankingModelID *string `json:"ranking_model_id" binding:"omitempty,uuid"`
|
||||
SummaryPromptTokenBudget int `json:"summary_prompt_token_budget" binding:"min=1,max=2000000"`
|
||||
Language string `json:"language" binding:"required,oneof=fr en"`
|
||||
RankingMode string `json:"ranking_mode" binding:"required,oneof=title title_content"`
|
||||
SummaryModelID *string `json:"summary_model_id" binding:"omitempty,uuid"`
|
||||
}
|
||||
|
||||
func (r *Repository) GetUserPreferences(userID string) (*UserPreferences, error) {
|
||||
p := &UserPreferences{}
|
||||
err := r.db.QueryRow(`SELECT language,ranking_mode,summary_model_id,summary_prompt_token_budget,ranking_model_id FROM users WHERE id=$1`, userID).Scan(&p.Language, &p.RankingMode, &p.SummaryModelID, &p.SummaryPromptTokenBudget, &p.RankingModelID)
|
||||
err := r.db.QueryRow(`SELECT language,ranking_mode,summary_model_id,summary_prompt_token_budget,ranking_model_id,source_article_retention_days FROM users WHERE id=$1`, userID).Scan(&p.Language, &p.RankingMode, &p.SummaryModelID, &p.SummaryPromptTokenBudget, &p.RankingModelID, &p.SourceArticleRetentionDays)
|
||||
return p, err
|
||||
}
|
||||
func (r *Repository) UpdateUserPreferences(userID string, preferences UserPreferences) (*UserPreferences, error) {
|
||||
if preferences.SourceArticleRetentionDays < 0 || preferences.SourceArticleRetentionDays > 30 {
|
||||
return nil, ErrInvalidRetention
|
||||
}
|
||||
if preferences.SummaryPromptTokenBudget < 1 || preferences.SummaryPromptTokenBudget > MaxSummaryPromptTokenBudget {
|
||||
return nil, ErrInvalidPromptBudget
|
||||
}
|
||||
@ -64,9 +68,17 @@ func (r *Repository) UpdateUserPreferences(userID string, preferences UserPrefer
|
||||
}
|
||||
|
||||
p := &UserPreferences{}
|
||||
err = tx.QueryRow(`UPDATE users SET language=$1,ranking_mode=$2,summary_model_id=$3,summary_prompt_token_budget=$4,ranking_model_id=$5,updated_at=NOW() WHERE id=$6 RETURNING language,ranking_mode,summary_model_id,summary_prompt_token_budget,ranking_model_id`, preferences.Language, preferences.RankingMode, preferences.SummaryModelID, preferences.SummaryPromptTokenBudget, preferences.RankingModelID, userID).Scan(&p.Language, &p.RankingMode, &p.SummaryModelID, &p.SummaryPromptTokenBudget, &p.RankingModelID)
|
||||
err = tx.QueryRow(`UPDATE users SET language=$1,ranking_mode=$2,summary_model_id=$3,summary_prompt_token_budget=$4,ranking_model_id=$5,source_article_retention_days=CASE WHEN $6=0 THEN source_article_retention_days ELSE $6 END,updated_at=NOW() WHERE id=$7 RETURNING language,ranking_mode,summary_model_id,summary_prompt_token_budget,ranking_model_id,source_article_retention_days`, preferences.Language, preferences.RankingMode, preferences.SummaryModelID, preferences.SummaryPromptTokenBudget, preferences.RankingModelID, preferences.SourceArticleRetentionDays, userID).Scan(&p.Language, &p.RankingMode, &p.SummaryModelID, &p.SummaryPromptTokenBudget, &p.RankingModelID, &p.SourceArticleRetentionDays)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if preferences.SourceArticleRetentionDays > 0 {
|
||||
if _, err = tx.Exec(`UPDATE summary_qa_conversations SET source_expires_at=LEAST(source_expires_at,generated_at+make_interval(days=>$1)),retention_days=LEAST(retention_days,$1) WHERE user_id=$2`, preferences.SourceArticleRetentionDays, userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = tx.Exec(`DELETE FROM summary_qa_sources a USING summary_qa_conversations c WHERE a.conversation_id=c.id AND c.user_id=$1 AND c.source_expires_at<=NOW()`, userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return p, tx.Commit()
|
||||
}
|
||||
|
||||
247
backend/internal/models/summary_qa.go
Normal file
247
backend/internal/models/summary_qa.go
Normal file
@ -0,0 +1,247 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"github.com/tradarr/backend/internal/summaryqa"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SummarySourceArticle is stored only in the new temporary Q&A tables. It never
|
||||
// enters aggregate outcomes, access logs or legacy article/report tables.
|
||||
type SummarySourceArticle struct {
|
||||
Title, Source, Content, URL string
|
||||
PublishedAt *time.Time
|
||||
}
|
||||
|
||||
var ErrInvalidRetention = errors.New("invalid_source_article_retention_days")
|
||||
|
||||
func ensureQA(ctx context.Context, tx *sql.Tx, owner, summary string) error {
|
||||
result, err := tx.ExecContext(ctx, `INSERT INTO summary_qa_conversations(summary_id,user_id,generated_at,source_expires_at,retention_days)
|
||||
SELECT s.id,s.user_id,s.generated_at,s.generated_at+make_interval(days=>u.source_article_retention_days),u.source_article_retention_days FROM summaries s JOIN users u ON u.id=s.user_id
|
||||
WHERE s.id=$1 AND s.user_id=$2 ON CONFLICT(summary_id) DO NOTHING`, summary, owner)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = result.RowsAffected()
|
||||
return err
|
||||
}
|
||||
func lockQA(ctx context.Context, tx *sql.Tx, owner, summary string) (summaryqa.Conversation, error) {
|
||||
c := summaryqa.Conversation{Mode: "stateless", Messages: []summaryqa.Turn{}}
|
||||
err := tx.QueryRowContext(ctx, `SELECT c.id,c.summary_id,c.source_expires_at FROM summary_qa_conversations c JOIN summaries s ON s.id=c.summary_id AND s.user_id=c.user_id WHERE c.summary_id=$1 AND c.user_id=$2 FOR UPDATE OF c`, summary, owner).Scan(&c.ID, &c.SummaryID, &c.SourceExpiresAt)
|
||||
if err == sql.ErrNoRows {
|
||||
return c, summaryqa.ErrNotFound
|
||||
}
|
||||
return c, err
|
||||
}
|
||||
func purgeOwnedSources(ctx context.Context, tx *sql.Tx, id string, now time.Time) error {
|
||||
_, err := tx.ExecContext(ctx, `DELETE FROM summary_qa_sources a USING summary_qa_conversations c WHERE a.conversation_id=c.id AND c.id=$1 AND c.source_expires_at<=$2`, id, now)
|
||||
return err
|
||||
}
|
||||
func qaTurns(ctx context.Context, tx *sql.Tx, id string) ([]summaryqa.Turn, error) {
|
||||
rows, err := tx.QueryContext(ctx, `SELECT id,request_id,passage,question,answer,status,failure_code,created_at FROM summary_qa_turns WHERE conversation_id=$1 ORDER BY ordinal`, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
turns := []summaryqa.Turn{}
|
||||
for rows.Next() {
|
||||
var t summaryqa.Turn
|
||||
if err = rows.Scan(&t.ID, &t.RequestID, &t.Passage, &t.Question, &t.Answer, &t.Status, &t.FailureCode, &t.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
turns = append(turns, t)
|
||||
}
|
||||
return turns, rows.Err()
|
||||
}
|
||||
func (r *Repository) GetQAConversation(ctx context.Context, owner, summary string, now time.Time) (summaryqa.Conversation, error) {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return summaryqa.Conversation{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err = ensureQA(ctx, tx, owner, summary); err != nil {
|
||||
return summaryqa.Conversation{}, err
|
||||
}
|
||||
c, err := lockQA(ctx, tx, owner, summary)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
if err = purgeOwnedSources(ctx, tx, c.ID, now); err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.SourcesExpired = !now.Before(c.SourceExpiresAt)
|
||||
// The deadline predicate is mandatory even if physical deletion is delayed.
|
||||
if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM summary_qa_sources a JOIN summary_qa_conversations c ON c.id=a.conversation_id WHERE c.id=$1 AND c.source_expires_at>$2`, c.ID, now).Scan(&c.SourceCount); err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.Messages, err = qaTurns(ctx, tx, c.ID)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
return c, tx.Commit()
|
||||
}
|
||||
func (r *Repository) BeginQAQuestion(ctx context.Context, owner, summary string, q summaryqa.Question, now time.Time) (summaryqa.Work, error) {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return summaryqa.Work{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err = ensureQA(ctx, tx, owner, summary); err != nil {
|
||||
return summaryqa.Work{}, err
|
||||
}
|
||||
c, err := lockQA(ctx, tx, owner, summary)
|
||||
if err != nil {
|
||||
return summaryqa.Work{}, err
|
||||
}
|
||||
if err = purgeOwnedSources(ctx, tx, c.ID, now); err != nil {
|
||||
return summaryqa.Work{}, err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `UPDATE summary_qa_turns SET status='failed',failure_code='qa_provider_failed' WHERE conversation_id=$1 AND status='pending' AND created_at<=$2`, c.ID, now.Add(-summaryqa.PendingLifetime)); err != nil {
|
||||
return summaryqa.Work{}, err
|
||||
}
|
||||
turns, err := qaTurns(ctx, tx, c.ID)
|
||||
if err != nil {
|
||||
return summaryqa.Work{}, err
|
||||
}
|
||||
work := summaryqa.Work{Conversation: c, History: []summaryqa.Exchange{}}
|
||||
busy := false
|
||||
for _, turn := range turns {
|
||||
if turn.RequestID == q.RequestID {
|
||||
if turn.Passage != q.Passage || turn.Question != q.Question {
|
||||
return work, summaryqa.ErrConflict
|
||||
}
|
||||
if turn.Status == "pending" {
|
||||
return work, summaryqa.ErrBusy
|
||||
}
|
||||
work.Turn = turn
|
||||
work.Replay = true
|
||||
return work, tx.Commit()
|
||||
}
|
||||
if turn.Status == "pending" {
|
||||
busy = true
|
||||
}
|
||||
if turn.Status == "answered" {
|
||||
work.History = append(work.History, summaryqa.Exchange{Passage: turn.Passage, Question: turn.Question, Answer: turn.Answer})
|
||||
}
|
||||
}
|
||||
if busy {
|
||||
return work, summaryqa.ErrBusy
|
||||
}
|
||||
if len(turns) >= summaryqa.MaxTurns {
|
||||
return work, summaryqa.ErrLimit
|
||||
}
|
||||
if err = tx.QueryRowContext(ctx, `SELECT s.content,u.language FROM summaries s JOIN users u ON u.id=s.user_id WHERE s.id=$1 AND s.user_id=$2`, summary, owner).Scan(&work.Summary, &work.Language); err != nil {
|
||||
return work, err
|
||||
}
|
||||
work.Turn = summaryqa.Turn{RequestID: q.RequestID, Passage: q.Passage, Question: q.Question, Status: "pending", CreatedAt: now}
|
||||
err = tx.QueryRowContext(ctx, `INSERT INTO summary_qa_turns(conversation_id,request_id,passage,question,status,created_at,ordinal) VALUES($1,$2,$3,$4,'pending',$5,$6) RETURNING id`, c.ID, q.RequestID, q.Passage, q.Question, now, len(turns)+1).Scan(&work.Turn.ID)
|
||||
if err != nil {
|
||||
return work, err
|
||||
}
|
||||
return work, tx.Commit()
|
||||
}
|
||||
func (r *Repository) FinishQAQuestion(ctx context.Context, owner, summary, turnID, answer, code string, now time.Time) (summaryqa.Turn, error) {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return summaryqa.Turn{}, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
c, err := lockQA(ctx, tx, owner, summary)
|
||||
if err != nil {
|
||||
return summaryqa.Turn{}, err
|
||||
}
|
||||
status := "answered"
|
||||
if code != "" {
|
||||
status = "failed"
|
||||
answer = ""
|
||||
}
|
||||
var t summaryqa.Turn
|
||||
err = tx.QueryRowContext(ctx, `UPDATE summary_qa_turns SET answer=$1,status=$2,failure_code=$3 WHERE id=$4 AND conversation_id=$5 AND status='pending' AND created_at>$6 RETURNING id,request_id,passage,question,answer,status,failure_code,created_at`, answer, status, code, turnID, c.ID, now.Add(-summaryqa.PendingLifetime)).Scan(&t.ID, &t.RequestID, &t.Passage, &t.Question, &t.Answer, &t.Status, &t.FailureCode, &t.CreatedAt)
|
||||
if err == sql.ErrNoRows {
|
||||
return t, summaryqa.ErrConflict
|
||||
}
|
||||
if err != nil {
|
||||
return t, err
|
||||
}
|
||||
return t, tx.Commit()
|
||||
}
|
||||
func (r *Repository) DeleteQAConversation(ctx context.Context, owner, summary string) error {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var id string
|
||||
if err = tx.QueryRowContext(ctx, `SELECT id FROM summaries WHERE id=$1 AND user_id=$2`, summary, owner).Scan(&id); err == sql.ErrNoRows {
|
||||
return summaryqa.ErrNotFound
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
// Retain only the immutable identity/deadline metadata. Erasing content must
|
||||
// not let a subsequent read extend the generation's captured retention.
|
||||
c, lockErr := lockQA(ctx, tx, owner, summary)
|
||||
if errors.Is(lockErr, summaryqa.ErrNotFound) {
|
||||
return tx.Commit()
|
||||
}
|
||||
if lockErr != nil {
|
||||
return lockErr
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `DELETE FROM summary_qa_sources WHERE conversation_id=$1`, c.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `DELETE FROM summary_qa_turns WHERE conversation_id=$1`, c.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
func (r *Repository) PurgeExpiredQASources(ctx context.Context, now time.Time) error {
|
||||
_, err := r.db.ExecContext(ctx, `DELETE FROM summary_qa_sources a USING summary_qa_conversations c WHERE a.conversation_id=c.id AND c.source_expires_at<=$1`, now)
|
||||
return err
|
||||
}
|
||||
func (r *Repository) ResolveQAModel(ctx context.Context, owner, summary string) (ResolvedSummaryModel, error) {
|
||||
var m ResolvedSummaryModel
|
||||
err := r.db.QueryRowContext(ctx, `SELECT m.id,p.id,p.name,m.model,p.endpoint,p.api_key_encrypted FROM summaries s JOIN ai_provider_models m ON m.id=s.summary_model_id JOIN ai_providers p ON p.id=m.provider_id WHERE s.id=$1 AND s.user_id=$2 AND m.enabled`, summary, owner).Scan(&m.ID, &m.ProviderID, &m.Provider, &m.Model, &m.Endpoint, &m.APIKeyEncrypted)
|
||||
if err != nil || m.Model == "" {
|
||||
return m, summaryqa.ErrModel
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (r *Repository) saveQASources(ctx context.Context, tx *sql.Tx, owner string, s *Summary, sources []SummarySourceArticle, days int) error {
|
||||
if days == 0 {
|
||||
days = 7
|
||||
}
|
||||
if days < 1 || days > 30 {
|
||||
return ErrInvalidRetention
|
||||
}
|
||||
// A decrease during generation takes effect; an increase cannot prolong the
|
||||
// duration captured by generation input. Serialize with preference updates.
|
||||
var current int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT source_article_retention_days FROM users WHERE id=$1 FOR SHARE`, owner).Scan(¤t); err != nil {
|
||||
return err
|
||||
}
|
||||
if current < days {
|
||||
days = current
|
||||
}
|
||||
size := 0
|
||||
for _, a := range sources {
|
||||
size += len(a.Title) + len(a.Content) + len(a.URL) + len(a.Source)
|
||||
}
|
||||
if len(sources) > 2000 || size > 32<<20 {
|
||||
return errors.New("qa_source_storage_limit")
|
||||
}
|
||||
var conversation string
|
||||
err := tx.QueryRowContext(ctx, `INSERT INTO summary_qa_conversations(summary_id,user_id,generated_at,source_expires_at,retention_days) VALUES($1,$2,$3,$3::timestamptz+make_interval(days=>$4),$4) RETURNING id`, s.ID, owner, s.GeneratedAt, days).Scan(&conversation)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for i, a := range sources {
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO summary_qa_sources(conversation_id,article_index,title,source,content,url,published_at) SELECT $1,$2,$3,$4,$5,$6,$7 WHERE EXISTS(SELECT 1 FROM summary_qa_conversations WHERE id=$1 AND source_expires_at>NOW())`, conversation, i, a.Title, a.Source, a.Content, a.URL, a.PublishedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
144
backend/internal/models/summary_qa_quota.go
Normal file
144
backend/internal/models/summary_qa_quota.go
Normal file
@ -0,0 +1,144 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"math"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/tradarr/backend/internal/summaryqa"
|
||||
)
|
||||
|
||||
type qaProviderPermit struct {
|
||||
conn *sql.Conn
|
||||
key string
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (p *qaProviderPermit) Release() { p.once.Do(func() { releaseQAConn(p.conn, p.key) }) }
|
||||
func releaseQAConn(conn *sql.Conn, key string) {
|
||||
if key != "" {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
var unlocked bool
|
||||
if err := conn.QueryRowContext(ctx, `SELECT pg_advisory_unlock(hashtextextended($1,0))`, key).Scan(&unlocked); err != nil || !unlocked {
|
||||
// A session holding an unconfirmed lock must never return to the pool.
|
||||
_ = conn.Raw(func(any) error { return driver.ErrBadConn })
|
||||
}
|
||||
}
|
||||
_ = conn.Close()
|
||||
}
|
||||
|
||||
// AcquireQAProviderCall uses a dedicated connection for the full invocation.
|
||||
// Transaction-scoped account serialization makes quota check+insert atomic;
|
||||
// session-scoped slots track live calls independently of turn status or TTL.
|
||||
func (r *Repository) AcquireQAProviderCall(ctx context.Context, owner, summary, turn string) (summaryqa.ProviderPermit, error) {
|
||||
conn, err := r.db.Conn(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key := ""
|
||||
granted := false
|
||||
defer func() {
|
||||
if !granted {
|
||||
releaseQAConn(conn, key)
|
||||
}
|
||||
}()
|
||||
// Re-read committed quota history after the account lock, even if the
|
||||
// connection has a stricter default transaction isolation.
|
||||
tx, err := conn.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var canonicalOwner string
|
||||
if err = tx.QueryRowContext(ctx, `SELECT id FROM users WHERE id=$1 FOR UPDATE`, owner).Scan(&canonicalOwner); err == sql.ErrNoRows {
|
||||
return nil, summaryqa.ErrNotFound
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var valid bool
|
||||
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM summary_qa_turns t JOIN summary_qa_conversations c ON c.id=t.conversation_id JOIN summaries s ON s.id=c.summary_id AND s.user_id=c.user_id WHERE c.user_id=$1 AND c.summary_id=$2 AND t.id=$3 AND t.status='pending' AND t.created_at>clock_timestamp()-interval '2 minutes')`, owner, summary, turn).Scan(&valid); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !valid {
|
||||
return nil, summaryqa.ErrConflict
|
||||
}
|
||||
// PostgreSQL's clock is authoritative across application instances. Read it
|
||||
// after acquiring the account row, not at transaction start or from the client.
|
||||
var now time.Time
|
||||
if err = tx.QueryRowContext(ctx, `SELECT clock_timestamp()`).Scan(&now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `DELETE FROM summary_qa_provider_calls WHERE user_id=$1 AND started_at<=$2`, owner, now.Add(-24*time.Hour)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var duplicate bool
|
||||
if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM summary_qa_provider_calls WHERE user_id=$1 AND turn_id=$2)`, owner, turn).Scan(&duplicate); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if duplicate {
|
||||
return nil, summaryqa.ErrBusy
|
||||
}
|
||||
retryAt := now
|
||||
for _, window := range []struct {
|
||||
length time.Duration
|
||||
limit int
|
||||
}{{time.Minute, summaryqa.CallsPerMinute}, {24 * time.Hour, summaryqa.CallsPerDay}} {
|
||||
var started time.Time
|
||||
err = tx.QueryRowContext(ctx, `SELECT started_at FROM summary_qa_provider_calls WHERE user_id=$1 AND started_at>$2 ORDER BY started_at DESC OFFSET $3 LIMIT 1`, owner, now.Add(-window.length), window.limit-1).Scan(&started)
|
||||
if err != nil && err != sql.ErrNoRows {
|
||||
return nil, err
|
||||
}
|
||||
if err == nil && started.Add(window.length).After(retryAt) {
|
||||
retryAt = started.Add(window.length)
|
||||
}
|
||||
}
|
||||
if retryAt.After(now) {
|
||||
return nil, &summaryqa.RateLimitError{RetryAfterSeconds: max(1, int(math.Ceil(retryAt.Sub(now).Seconds())))}
|
||||
}
|
||||
for slot := 0; slot < summaryqa.ConcurrentCalls; slot++ {
|
||||
candidate := fmt.Sprintf("tradarr.summaryqa.provider:%s:%d", canonicalOwner, slot)
|
||||
var locked bool
|
||||
if err = tx.QueryRowContext(ctx, `SELECT pg_try_advisory_lock(hashtextextended($1,0))`, candidate).Scan(&locked); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if locked {
|
||||
key = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
if key == "" {
|
||||
return nil, &summaryqa.RateLimitError{RetryAfterSeconds: 1}
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO summary_qa_provider_calls(user_id,turn_id,started_at) VALUES($1,$2,$3)`, owner, turn, now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
granted = true
|
||||
return &qaProviderPermit{conn: conn, key: key}, nil
|
||||
}
|
||||
|
||||
// A denied admission has not invoked the provider. Remove its pending turn so
|
||||
// the same request_id can retry and denial cannot exhaust conversation turns.
|
||||
func (r *Repository) CancelQAQuestion(ctx context.Context, owner, summary, turn string) error {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
c, err := lockQA(ctx, tx, owner, summary)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `DELETE FROM summary_qa_turns t WHERE t.id=$1 AND t.conversation_id=$2 AND t.status='pending' AND NOT EXISTS(SELECT 1 FROM summary_qa_provider_calls p WHERE p.user_id=$3 AND p.turn_id=t.id)`, turn, c.ID, owner)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
Reference in New Issue
Block a user