feat: add FAQ uncovered workflow
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/faqtable"
|
||||
)
|
||||
|
||||
var (
|
||||
errFAQExportNilStore = errors.New("faq export store is unavailable")
|
||||
errFAQCaseIDRequired = errors.New("faq export case id is required")
|
||||
errFAQRecordIDRequired = errors.New("faq export record id is required")
|
||||
errFAQRowsAffected = errors.New("faq export RowsAffected != 1")
|
||||
errFAQFailureCodeInvalid = errors.New("faq export only remote_faq_table_insert_failed is accepted")
|
||||
)
|
||||
|
||||
type FAQExportRepository struct{ store *Store }
|
||||
|
||||
var _ faqtable.ExportRepository = (*FAQExportRepository)(nil)
|
||||
|
||||
func NewFAQExportRepository(store *Store) (*FAQExportRepository, error) {
|
||||
if store == nil || store.pool == nil {
|
||||
return nil, errFAQExportNilStore
|
||||
}
|
||||
return &FAQExportRepository{store: store}, nil
|
||||
}
|
||||
|
||||
func (r *FAQExportRepository) Claim(ctx context.Context, limit, maxAttempts int, staleBefore time.Time) ([]faqtable.PendingExport, error) {
|
||||
if r == nil || r.store == nil || r.store.pool == nil {
|
||||
return nil, errFAQExportNilStore
|
||||
}
|
||||
rows, err := r.store.pool.Query(ctx, `
|
||||
WITH candidates AS (
|
||||
SELECT sc.id
|
||||
FROM support_cases sc
|
||||
WHERE (sc.faq_export_status = 'pending'
|
||||
OR (sc.faq_export_status = 'export_failed' AND (sc.faq_next_attempt_at IS NULL OR sc.faq_next_attempt_at <= NOW()))
|
||||
OR (sc.faq_export_status = 'exporting' AND sc.faq_last_attempt_at < $3))
|
||||
AND sc.faq_export_attempts < $2
|
||||
ORDER BY sc.created_at, sc.id
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
),
|
||||
claimed AS (
|
||||
UPDATE support_cases sc
|
||||
SET faq_export_status = 'exporting',
|
||||
faq_export_attempts = sc.faq_export_attempts + 1,
|
||||
faq_last_attempt_at = NOW(),
|
||||
faq_next_attempt_at = NULL,
|
||||
faq_failure_code = '',
|
||||
updated_at = NOW()
|
||||
FROM candidates c
|
||||
WHERE sc.id = c.id
|
||||
RETURNING sc.id, sc.faq_export_attempts, sc.tenant_key, sc.channel, sc.turn_id, sc.created_at
|
||||
)
|
||||
SELECT cl.id, cl.faq_export_attempts, t.question,
|
||||
COALESCE(m.actor_name_snapshot, ''), COALESCE(m.actor_union_id_snapshot, '')
|
||||
FROM claimed cl
|
||||
JOIN turns t ON t.id = cl.turn_id
|
||||
AND t.tenant_key = cl.tenant_key AND t.channel = cl.channel
|
||||
JOIN messages m ON m.id = t.request_message_id
|
||||
AND m.tenant_key = cl.tenant_key AND m.channel = cl.channel
|
||||
ORDER BY cl.created_at, cl.id`, limit, maxAttempts, staleBefore)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("faq export claim: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var exports []faqtable.PendingExport
|
||||
for rows.Next() {
|
||||
var id, question, askerName, askerUnionID string
|
||||
var attempts int
|
||||
if err := rows.Scan(&id, &attempts, &question, &askerName, &askerUnionID); err != nil {
|
||||
return nil, fmt.Errorf("faq export claim scan: %w", err)
|
||||
}
|
||||
exports = append(exports, faqtable.PendingExport{
|
||||
CaseID: id, Attempts: attempts,
|
||||
Row: faqtable.Row{StandardQuestion: question, OriginalQuestion: question, AskerName: askerName, AskerUnionID: askerUnionID},
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("faq export claim rows: %w", err)
|
||||
}
|
||||
return exports, nil
|
||||
}
|
||||
|
||||
func (r *FAQExportRepository) MarkExported(ctx context.Context, caseID, recordID string) error {
|
||||
if strings.TrimSpace(caseID) == "" {
|
||||
return errFAQCaseIDRequired
|
||||
}
|
||||
if strings.TrimSpace(recordID) == "" {
|
||||
return errFAQRecordIDRequired
|
||||
}
|
||||
if r == nil || r.store == nil || r.store.pool == nil {
|
||||
return errFAQExportNilStore
|
||||
}
|
||||
tag, err := r.store.pool.Exec(ctx, `
|
||||
UPDATE support_cases
|
||||
SET faq_export_status = 'exported', faq_record_id = $2,
|
||||
faq_exported_at = NOW(), faq_failure_code = '', faq_next_attempt_at = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND faq_export_status = 'exporting'`, caseID, recordID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("faq export mark exported: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return errFAQRowsAffected
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *FAQExportRepository) MarkFailed(ctx context.Context, caseID, failureCode string) error {
|
||||
if strings.TrimSpace(caseID) == "" {
|
||||
return errFAQCaseIDRequired
|
||||
}
|
||||
if failureCode != faqtable.FailureCodeRemoteInsertFailed {
|
||||
return errFAQFailureCodeInvalid
|
||||
}
|
||||
if r == nil || r.store == nil || r.store.pool == nil {
|
||||
return errFAQExportNilStore
|
||||
}
|
||||
tag, err := r.store.pool.Exec(ctx, `
|
||||
UPDATE support_cases
|
||||
SET faq_export_status = 'export_failed', faq_failure_code = $2,
|
||||
faq_next_attempt_at = NOW() + CASE
|
||||
WHEN faq_export_attempts <= 1 THEN '5 seconds'::interval
|
||||
WHEN faq_export_attempts = 2 THEN '15 seconds'::interval
|
||||
WHEN faq_export_attempts = 3 THEN '45 seconds'::interval
|
||||
ELSE '5 minutes'::interval END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND faq_export_status = 'exporting'`, caseID, failureCode)
|
||||
if err != nil {
|
||||
return fmt.Errorf("faq export mark failed: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return errFAQRowsAffected
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func readFAQExportsSource(t *testing.T) string {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile("faq_exports.go")
|
||||
if err != nil {
|
||||
t.Fatalf("read faq_exports.go: %v", err)
|
||||
}
|
||||
return strings.ToUpper(string(data))
|
||||
}
|
||||
|
||||
func TestFAQExportsClaimIsAtomicScopedAndBounded(t *testing.T) {
|
||||
src := readFAQExportsSource(t)
|
||||
for _, fragment := range []string{
|
||||
"WITH CANDIDATES", "FOR UPDATE SKIP LOCKED", "UPDATE SUPPORT_CASES",
|
||||
"FAQ_EXPORT_STATUS = 'EXPORTING'", "FAQ_EXPORT_ATTEMPTS",
|
||||
"T.TENANT_KEY = CL.TENANT_KEY", "T.CHANNEL = CL.CHANNEL",
|
||||
"M.TENANT_KEY = CL.TENANT_KEY", "M.CHANNEL = CL.CHANNEL",
|
||||
"T.QUESTION", "M.ACTOR_NAME_SNAPSHOT", "M.ACTOR_UNION_ID_SNAPSHOT",
|
||||
} {
|
||||
if !strings.Contains(src, fragment) {
|
||||
t.Errorf("claim contract missing %q", fragment)
|
||||
}
|
||||
}
|
||||
if strings.Contains(src, "T.ANSWER") {
|
||||
t.Fatal("FAQ export must not read the generated answer")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFAQExportsSuccessAndFailureTransitionsAreGuarded(t *testing.T) {
|
||||
src := readFAQExportsSource(t)
|
||||
for _, fragment := range []string{
|
||||
"FAQ_EXPORT_STATUS = 'EXPORTED'", "FAQ_RECORD_ID = $2", "FAQ_EXPORTED_AT = NOW()",
|
||||
"FAQ_EXPORT_STATUS = 'EXPORT_FAILED'", "FAQ_FAILURE_CODE = $2", "FAQ_NEXT_ATTEMPT_AT",
|
||||
"WHERE ID = $1 AND FAQ_EXPORT_STATUS = 'EXPORTING'",
|
||||
"REMOTE_FAQ_TABLE_INSERT_FAILED",
|
||||
} {
|
||||
if !strings.Contains(src, fragment) {
|
||||
t.Errorf("transition contract missing %q", fragment)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,7 @@ func (s *Store) Claim(ctx context.Context, limit int, maxAttempts int, staleBefo
|
||||
FROM support_cases sc
|
||||
WHERE (sc.status = 'pending' OR sc.status = 'notification_failed'
|
||||
OR (sc.status = 'notifying' AND sc.last_notification_at < $3))
|
||||
AND sc.faq_export_status = 'exported'
|
||||
AND sc.notification_attempts < $2
|
||||
ORDER BY sc.created_at, sc.id
|
||||
LIMIT $1
|
||||
@@ -47,8 +48,8 @@ func (s *Store) Claim(ctx context.Context, limit int, maxAttempts int, staleBefo
|
||||
updated_at = NOW()
|
||||
FROM candidates c
|
||||
WHERE sc.id = c.id
|
||||
RETURNING sc.id, sc.tenant_key, sc.channel, sc.turn_id, sc.coverage_decision_id,
|
||||
sc.notification_attempts, sc.created_at
|
||||
RETURNING sc.id, sc.tenant_key, sc.channel, sc.turn_id,
|
||||
sc.notification_attempts, sc.created_at, sc.faq_record_id
|
||||
)
|
||||
SELECT
|
||||
cl.id,
|
||||
@@ -57,25 +58,37 @@ func (s *Store) Claim(ctx context.Context, limit int, maxAttempts int, staleBefo
|
||||
cl.turn_id,
|
||||
cl.notification_attempts,
|
||||
COALESCE(t.question, '') AS question,
|
||||
COALESCE(t.answer, '') AS answer,
|
||||
COALESCE(m.actor_name_snapshot, '') AS sender_name,
|
||||
COALESCE(c.conversation_type, 'direct') AS conversation_type,
|
||||
COALESCE(cd.reference_count, 0) AS reference_count,
|
||||
COALESCE(cd.top_score, 0) AS top_score
|
||||
m.created_at AS asked_at,
|
||||
COALESCE(history.previous_questions, ARRAY[]::TEXT[]) AS previous_questions,
|
||||
cl.faq_record_id
|
||||
FROM claimed cl
|
||||
JOIN turns t ON t.id = cl.turn_id
|
||||
AND t.tenant_key = cl.tenant_key
|
||||
AND t.channel = cl.channel
|
||||
LEFT JOIN messages m ON m.id = t.request_message_id
|
||||
JOIN messages m ON m.id = t.request_message_id
|
||||
AND m.tenant_key = cl.tenant_key
|
||||
AND m.channel = cl.channel
|
||||
LEFT JOIN channel_conversations c ON c.id = m.conversation_id
|
||||
AND c.tenant_key = cl.tenant_key
|
||||
AND c.channel = cl.channel
|
||||
JOIN coverage_decisions cd ON cd.id = cl.coverage_decision_id
|
||||
AND cd.tenant_key = cl.tenant_key
|
||||
AND cd.channel = cl.channel
|
||||
AND cd.turn_id = cl.turn_id
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT ARRAY_AGG(previous.question ORDER BY previous.created_at DESC) AS previous_questions
|
||||
FROM (
|
||||
SELECT t2.question, t2.created_at
|
||||
FROM turns t2
|
||||
JOIN messages m2 ON m2.id = t2.request_message_id
|
||||
AND m2.tenant_key = t2.tenant_key
|
||||
AND m2.channel = t2.channel
|
||||
WHERE t2.tenant_key = cl.tenant_key
|
||||
AND t2.channel = cl.channel
|
||||
AND m2.actor_id = m.actor_id
|
||||
AND t2.created_at < t.created_at
|
||||
ORDER BY t2.created_at DESC
|
||||
LIMIT 5
|
||||
) previous
|
||||
) history ON TRUE
|
||||
ORDER BY cl.created_at, cl.id`,
|
||||
limit, maxAttempts, staleBefore)
|
||||
if err != nil {
|
||||
@@ -86,34 +99,34 @@ func (s *Store) Claim(ctx context.Context, limit int, maxAttempts int, staleBefo
|
||||
var cases []coverage.PendingSupportCase
|
||||
for rows.Next() {
|
||||
var (
|
||||
id string
|
||||
tenantKey string
|
||||
channel string
|
||||
turnID string
|
||||
attempts int
|
||||
question string
|
||||
answer string
|
||||
senderName string
|
||||
conversationType string
|
||||
referenceCount int
|
||||
topScore float64
|
||||
id string
|
||||
tenantKey string
|
||||
channel string
|
||||
turnID string
|
||||
attempts int
|
||||
question string
|
||||
senderName string
|
||||
conversationType string
|
||||
askedAt time.Time
|
||||
previousQuestions []string
|
||||
faqRecordID string
|
||||
)
|
||||
if err := rows.Scan(&id, &tenantKey, &channel, &turnID, &attempts,
|
||||
&question, &answer, &senderName, &conversationType,
|
||||
&referenceCount, &topScore); err != nil {
|
||||
&question, &senderName, &conversationType, &askedAt,
|
||||
&previousQuestions, &faqRecordID); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("claim scan: %w", err)
|
||||
}
|
||||
cases = append(cases, coverage.PendingSupportCase{
|
||||
SupportNotification: coverage.SupportNotification{
|
||||
CaseID: id,
|
||||
Question: question,
|
||||
Answer: answer,
|
||||
SenderName: senderName,
|
||||
Channel: channel,
|
||||
ConversationType: core.ConversationType(conversationType),
|
||||
ReferenceCount: referenceCount,
|
||||
TopScore: topScore,
|
||||
CaseID: id,
|
||||
Question: question,
|
||||
SenderName: senderName,
|
||||
Channel: channel,
|
||||
ConversationType: core.ConversationType(conversationType),
|
||||
AskedAt: askedAt,
|
||||
PreviousQuestions: previousQuestions,
|
||||
FAQRecordID: faqRecordID,
|
||||
},
|
||||
Attempts: attempts,
|
||||
})
|
||||
|
||||
@@ -136,38 +136,34 @@ func TestSupportNotificationsClaimScopeJoins(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportNotificationsClaimUsesPersistedCoverageDecisionID(t *testing.T) {
|
||||
func TestSupportNotificationsClaimWaitsForFAQExport(t *testing.T) {
|
||||
joined := strings.ToUpper(strings.Join(extractSQLFromSupportNotifications(t), " "))
|
||||
if !strings.Contains(joined, "SC.COVERAGE_DECISION_ID") {
|
||||
t.Fatal("Claim must carry support_cases.coverage_decision_id through the claimed CTE")
|
||||
if !strings.Contains(joined, "FAQ_EXPORT_STATUS = 'EXPORTED'") {
|
||||
t.Fatal("Claim must wait until the FAQ record has been exported")
|
||||
}
|
||||
if !strings.Contains(joined, "CD.ID = CL.COVERAGE_DECISION_ID") {
|
||||
t.Fatal("Claim must join the exact persisted coverage decision ID")
|
||||
if !strings.Contains(joined, "FAQ_RECORD_ID") {
|
||||
t.Fatal("Claim must return the FAQ record ID for the action button")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportNotificationsClaimReadsQuestionAnswerFromTurns(t *testing.T) {
|
||||
sqls := extractSQLFromSupportNotifications(t)
|
||||
joined := strings.ToUpper(strings.Join(sqls, " "))
|
||||
|
||||
// Must read question/answer from turns table, not from support_cases
|
||||
if !strings.Contains(joined, "T.QUESTION") {
|
||||
t.Error("Claim must read question from turns table")
|
||||
}
|
||||
if !strings.Contains(joined, "T.ANSWER") {
|
||||
t.Error("Claim must read answer from turns table")
|
||||
func TestSupportNotificationsClaimReadsQuestionTimeAndFivePreviousQuestions(t *testing.T) {
|
||||
joined := strings.ToUpper(strings.Join(extractSQLFromSupportNotifications(t), " "))
|
||||
for _, required := range []string{
|
||||
"T.QUESTION", "M.CREATED_AT", "M2.ACTOR_ID = M.ACTOR_ID",
|
||||
"T2.CREATED_AT < T.CREATED_AT", "ORDER BY T2.CREATED_AT DESC", "LIMIT 5",
|
||||
} {
|
||||
if !strings.Contains(joined, required) {
|
||||
t.Errorf("Claim missing customer-history contract fragment %q", required)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportNotificationsClaimReadsReferenceCountAndTopScore(t *testing.T) {
|
||||
sqls := extractSQLFromSupportNotifications(t)
|
||||
joined := strings.ToUpper(strings.Join(sqls, " "))
|
||||
|
||||
if !strings.Contains(joined, "REFERENCE_COUNT") {
|
||||
t.Error("Claim must read reference_count from coverage_decisions")
|
||||
}
|
||||
if !strings.Contains(joined, "TOP_SCORE") {
|
||||
t.Error("Claim must read top_score from coverage_decisions")
|
||||
func TestSupportNotificationsClaimDoesNotReadAnswerOrRetrievalDiagnostics(t *testing.T) {
|
||||
joined := strings.ToUpper(strings.Join(extractSQLFromSupportNotifications(t), " "))
|
||||
for _, forbidden := range []string{"T.ANSWER", "REFERENCE_COUNT", "TOP_SCORE"} {
|
||||
if strings.Contains(joined, forbidden) {
|
||||
t.Errorf("Claim must not read notification field %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user