feat: sync DingTalk QA to Notable question table

This commit is contained in:
姚章浩
2026-07-23 14:38:50 +08:00
parent 5e0694835a
commit 0a3f62618e
22 changed files with 4351 additions and 77 deletions
@@ -14,8 +14,10 @@ func TestBeginTurnStoresDirectorySnapshotsAndGroupTitle(t *testing.T) {
src := strings.ToUpper(string(raw))
for _, required := range []string{
"DEPARTMENT_SNAPSHOT,REGION_SNAPSHOT",
"ACTOR_UNION_ID_SNAPSHOT",
"TURN.DEPARTMENTSNAPSHOT",
"TURN.REGIONSNAPSHOT",
"TURN.ACTORUNIONIDSNAPSHOT",
"TURN.CONVERSATIONTITLE",
} {
if !strings.Contains(src, required) {
@@ -0,0 +1,205 @@
// Package postgres contains source-level contract tests for the
// question_table_exports outbox: the store must enqueue inside
// FinishTurn's transaction, guarded by shouldCreateAnswerMessage.
// No database connection is required.
package postgres
import (
"os"
"strings"
"testing"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
)
// TestFinishTurnBeginTurnSnapshot verifies that the BeginTurn INSERT
// into messages includes trigger_person_snapshot, actor_union_id_snapshot,
// department_snapshot, and region_snapshot columns.
func TestFinishTurnBeginTurnSnapshot(t *testing.T) {
data, err := os.ReadFile("store.go")
if err != nil {
t.Fatalf("read store.go: %v", err)
}
src := string(data)
// The BeginTurn message INSERT must include trigger_person_snapshot
if !strings.Contains(src, "trigger_person_snapshot") {
t.Error("BeginTurn message INSERT must include trigger_person_snapshot column")
}
if !strings.Contains(src, "actor_union_id_snapshot") {
t.Error("BeginTurn message INSERT must include actor_union_id_snapshot column")
}
if !strings.Contains(src, "department_snapshot") {
t.Error("BeginTurn message INSERT must include department_snapshot column")
}
if !strings.Contains(src, "region_snapshot") {
t.Error("BeginTurn message INSERT must include region_snapshot column")
}
// The VALUES arguments must include turn.ActorUnionIDSnapshot
if !strings.Contains(src, "turn.ActorUnionIDSnapshot") {
t.Error("BeginTurn message INSERT VALUES must include turn.ActorUnionIDSnapshot argument")
}
}
func TestShouldEnqueueQuestionTableExportOnlyForDingTalkSucceededAnswers(t *testing.T) {
tests := []struct {
name string
turn core.Turn
want bool
}{
{name: "dingtalk success", turn: core.Turn{Channel: "dingtalk", Status: "succeeded", Answer: "answer", AnswerMessageID: "answer-1"}, want: true},
{name: "dingtalk case and space", turn: core.Turn{Channel: " DingTalk ", Status: "succeeded", Answer: "answer", AnswerMessageID: "answer-1"}, want: true},
{name: "web success", turn: core.Turn{Channel: "web", Status: "succeeded", Answer: "answer", AnswerMessageID: "answer-1"}},
{name: "http success", turn: core.Turn{Channel: "http", Status: "succeeded", Answer: "answer", AnswerMessageID: "answer-1"}},
{name: "empty channel", turn: core.Turn{Status: "succeeded", Answer: "answer", AnswerMessageID: "answer-1"}},
{name: "dingtalk failed", turn: core.Turn{Channel: "dingtalk", Status: "failed", Answer: "answer", AnswerMessageID: "answer-1"}},
{name: "dingtalk empty answer", turn: core.Turn{Channel: "dingtalk", Status: "succeeded", Answer: " ", AnswerMessageID: "answer-1"}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := shouldEnqueueQuestionTableExport(tc.turn); got != tc.want {
t.Fatalf("shouldEnqueueQuestionTableExport()=%v, want %v", got, tc.want)
}
})
}
}
// TestFinishTurnOutboxInsideTransaction verifies that the
// question_table_exports INSERT is inside the FinishTurn transaction
// (between tx begin and tx commit), uses 'pending' status, and has
// ON CONFLICT (tenant_key,channel,turn_id) DO NOTHING.
func TestFinishTurnOutboxInsideTransaction(t *testing.T) {
data, err := os.ReadFile("store.go")
if err != nil {
t.Fatalf("read store.go: %v", err)
}
src := string(data)
// Extract the FinishTurn function body using deterministic boundaries
finishStart := strings.Index(src, "func (s *Store) FinishTurn(")
if finishStart < 0 {
t.Fatal("cannot find FinishTurn signature")
}
finishEnd := strings.Index(src[finishStart:], "func (s *Store) RecordDelivery(")
if finishEnd < 0 {
t.Fatal("cannot find RecordDelivery signature after FinishTurn")
}
body := src[finishStart : finishStart+finishEnd]
// The outbox INSERT must use question_table_exports
if !strings.Contains(body, "question_table_exports") {
t.Error("FinishTurn must INSERT into question_table_exports")
}
// Must use 'pending' status for the outbox
if !strings.Contains(body, "'pending'") {
t.Error("question_table_exports INSERT must use status='pending'")
}
// Must use ON CONFLICT (tenant_key,channel,turn_id) DO NOTHING
if !strings.Contains(body, "ON CONFLICT (tenant_key,channel,turn_id) DO NOTHING") &&
!strings.Contains(body, "ON CONFLICT (tenant_key, channel, turn_id) DO NOTHING") {
t.Error("question_table_exports INSERT must use ON CONFLICT (tenant_key,channel,turn_id) DO NOTHING")
}
// The outbox INSERT must be after the tx begin and before tx commit
txBegin := strings.Index(body, "BeginTx")
txCommit := strings.Index(body, "tx.Commit")
outboxPos := strings.Index(body, "question_table_exports")
if txBegin < 0 || txCommit < 0 || outboxPos < 0 {
t.Fatal("cannot locate transaction boundaries or outbox insert")
}
if outboxPos < txBegin || outboxPos > txCommit {
t.Error("question_table_exports INSERT must be inside the transaction (between BeginTx and Commit)")
}
}
// TestFinishTurnOutboxGuardedByShouldCreateAnswerMessage verifies that
// the outbox INSERT is structurally inside the shouldCreateAnswerMessage
// guard. Failed, processing, and empty-answer turns must not enqueue.
func TestFinishTurnOutboxGuardedByShouldCreateAnswerMessage(t *testing.T) {
data, err := os.ReadFile("store.go")
if err != nil {
t.Fatalf("read store.go: %v", err)
}
src := string(data)
// The shouldCreateAnswerMessage function must guard on status succeeded,
// non-empty answer, and non-empty answer message ID
if !strings.Contains(src, "shouldCreateAnswerMessage") {
t.Fatal("shouldCreateAnswerMessage function must exist")
}
// Extract shouldCreateAnswerMessage function body using deterministic boundaries
shouldFuncStart := strings.Index(src, "func shouldCreateAnswerMessage(")
if shouldFuncStart < 0 {
t.Fatal("cannot find shouldCreateAnswerMessage signature")
}
// Find the closing brace of the function: the first top-level `}` after the signature
// The function body is simple: one return statement, so find the `}` that follows
shouldFuncBodyStart := strings.Index(src[shouldFuncStart:], "{")
if shouldFuncBodyStart < 0 {
t.Fatal("cannot find shouldCreateAnswerMessage opening brace")
}
shouldFuncBodyStart += shouldFuncStart + 1 // position after "{"
shouldFuncEnd := strings.Index(src[shouldFuncBodyStart:], "\n}\n")
if shouldFuncEnd < 0 {
t.Fatal("cannot find shouldCreateAnswerMessage closing brace")
}
shouldFuncEnd += shouldFuncBodyStart + 1 // position of the closing "}"
shouldBody := src[shouldFuncBodyStart:shouldFuncEnd]
if !strings.Contains(shouldBody, "succeeded") {
t.Error("shouldCreateAnswerMessage must check status == succeeded")
}
if !strings.Contains(shouldBody, "turn.Answer") {
t.Error("shouldCreateAnswerMessage must check non-empty answer")
}
if !strings.Contains(shouldBody, "turn.AnswerMessageID") {
t.Error("shouldCreateAnswerMessage must check non-empty AnswerMessageID")
}
// In FinishTurn, extract the guarded block using deterministic boundaries
finishStart := strings.Index(src, "func (s *Store) FinishTurn(")
if finishStart < 0 {
t.Fatal("cannot find FinishTurn signature")
}
finishEnd := strings.Index(src[finishStart:], "func (s *Store) RecordDelivery(")
if finishEnd < 0 {
t.Fatal("cannot find RecordDelivery signature after FinishTurn")
}
finishBody := src[finishStart : finishStart+finishEnd]
// Locate the guarded block: start at "if shouldCreateAnswerMessage(turn) {"
guardStart := strings.Index(finishBody, "if shouldCreateAnswerMessage(turn) {")
if guardStart < 0 {
t.Fatal("cannot find shouldCreateAnswerMessage guard in FinishTurn")
}
// The guarded block ends before the "UPDATE turns SET" statement that follows it
guardEnd := strings.Index(finishBody[guardStart:], "UPDATE turns SET")
if guardEnd < 0 {
t.Fatal("cannot find UPDATE turns SET after guarded block")
}
guardBlock := finishBody[guardStart : guardStart+guardEnd]
if !strings.Contains(guardBlock, "question_table_exports") {
t.Error("question_table_exports INSERT must be inside the shouldCreateAnswerMessage guard block")
}
if !strings.Contains(guardBlock, "if shouldEnqueueQuestionTableExport(turn) {") {
t.Error("question_table_exports INSERT must be guarded to DingTalk turns explicitly")
}
// The guard block must be the one that contains the messages INSERT
// (answer message creation), and after that the outbox INSERT
msgInsert := strings.Index(guardBlock, "INSERT INTO messages")
outboxInsert := strings.Index(guardBlock, "question_table_exports")
if msgInsert < 0 || outboxInsert < 0 {
t.Fatal("cannot locate messages INSERT or outbox INSERT in guard block")
}
if outboxInsert < msgInsert {
t.Error("outbox INSERT should come after answer message INSERT")
}
}
@@ -0,0 +1,219 @@
package postgres
import (
"context"
"errors"
"fmt"
"strings"
"time"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/questiontable"
)
var (
errExportIDRequired = errors.New("questiontable export: exportID is required")
errLocationRequired = errors.New("questiontable export: external record id is required")
errBadExportFailure = errors.New("questiontable export: only remote_question_table_insert_failed is accepted")
errExportRowsAffected = errors.New("questiontable export: RowsAffected != 1")
errExportNilStore = errors.New("questiontable export: store is nil")
)
// QuestionTableExportRepository implements questiontable.ExportRepository
// using a dedicated adapter type. It does NOT add methods to *Store directly
// to avoid conflicts with the existing coverage.NotificationRepository Claim
// and MarkFailed methods.
type QuestionTableExportRepository struct {
store *Store
}
// compile-time interface assertion
var _ questiontable.ExportRepository = (*QuestionTableExportRepository)(nil)
// NewQuestionTableExportRepository creates a validated repository adapter.
// It returns a stable error when store is nil or its pool is nil.
func NewQuestionTableExportRepository(store *Store) (*QuestionTableExportRepository, error) {
if store == nil || store.pool == nil {
return nil, errExportNilStore
}
return &QuestionTableExportRepository{store: store}, nil
}
// Claim implements questiontable.ExportRepository. It atomically claims up to
// limit pending exports whose attempt count is below maxAttempts and whose last
// claim time is before staleBefore. A single CTE with FOR UPDATE SKIP LOCKED
// and one UPDATE is used for atomicity.
func (r *QuestionTableExportRepository) Claim(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]questiontable.PendingExport, error) {
if r == nil || r.store == nil || r.store.pool == nil {
return nil, errExportNilStore
}
if limit <= 0 || limit > 1000 {
return nil, fmt.Errorf("questiontable export: limit must be 1..1000, got %d", limit)
}
if maxAttempts <= 0 || maxAttempts > 100 {
return nil, fmt.Errorf("questiontable export: maxAttempts must be 1..100, got %d", maxAttempts)
}
rows, err := r.store.pool.Query(ctx, `
WITH candidates AS (
SELECT qte.id
FROM question_table_exports qte
WHERE (qte.status = 'pending'
OR (qte.status = 'export_failed' AND (qte.next_attempt_at IS NULL OR qte.next_attempt_at <= NOW()))
OR (qte.status = 'exporting' AND qte.last_attempt_at < $3))
AND qte.attempts < $2
ORDER BY qte.created_at, qte.id
LIMIT $1
FOR UPDATE SKIP LOCKED
),
claimed AS (
UPDATE question_table_exports qte
SET status = 'exporting',
attempts = qte.attempts + 1,
last_attempt_at = NOW(),
next_attempt_at = NULL,
failure_code = '',
updated_at = NOW()
FROM candidates c
WHERE qte.id = c.id
RETURNING qte.id, qte.attempts, qte.tenant_key, qte.channel, qte.turn_id, qte.created_at
)
SELECT
cl.id,
cl.attempts,
t.question,
t.answer,
m.created_at,
COALESCE(m.actor_name_snapshot, '') AS actor_name_snapshot,
COALESCE(m.actor_union_id_snapshot, '') AS actor_union_id_snapshot,
COALESCE(m.trigger_person_snapshot, '') AS trigger_person_snapshot,
COALESCE(m.department_snapshot, '') AS department_snapshot,
COALESCE(m.region_snapshot, '') AS region_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("questiontable export claim: %w", err)
}
defer rows.Close()
var exports []questiontable.PendingExport
for rows.Next() {
var (
exportID string
attempts int
question string
answer string
askedTime time.Time
actorNameSnapshot string
actorUnionIDSnapshot string
triggerPersonSnap string
departmentSnap string
regionSnap string
)
if err := rows.Scan(&exportID, &attempts,
&question, &answer,
&askedTime,
&actorNameSnapshot, &actorUnionIDSnapshot,
&triggerPersonSnap, &departmentSnap, &regionSnap); err != nil {
rows.Close()
return nil, fmt.Errorf("questiontable export claim scan: %w", err)
}
exports = append(exports, questiontable.PendingExport{
ExportID: exportID,
Attempts: attempts,
Row: questiontable.Row{
Question: question,
Answer: answer,
AskedTime: askedTime,
AskerName: actorNameSnapshot,
AskerUnionID: actorUnionIDSnapshot,
TriggerPerson: triggerPersonSnap,
Department: departmentSnap,
Region: regionSnap,
},
})
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("questiontable export claim rows: %w", err)
}
return exports, nil
}
// MarkExported implements questiontable.ExportRepository.
// It records the Notable external record ID for a successfully exported row.
// It transitions the row from exporting to exported. RowsAffected must be exactly 1.
func (r *QuestionTableExportRepository) MarkExported(ctx context.Context, exportID, externalRecordID string) error {
if strings.TrimSpace(exportID) == "" {
return errExportIDRequired
}
if strings.TrimSpace(externalRecordID) == "" {
return errLocationRequired
}
if r == nil || r.store == nil || r.store.pool == nil {
return errExportNilStore
}
tag, err := r.store.pool.Exec(ctx, `
UPDATE question_table_exports
SET status = 'exported',
external_record_id = $2,
exported_at = NOW(),
failure_code = '',
next_attempt_at = NULL,
updated_at = NOW()
WHERE id = $1 AND status = 'exporting'`,
exportID, externalRecordID)
if err != nil {
return fmt.Errorf("questiontable export mark exported: %w", err)
}
if tag.RowsAffected() != 1 {
return errExportRowsAffected
}
return nil
}
// MarkFailed implements questiontable.ExportRepository.
// It records a failure for a row in exporting status with a stable failure code.
// Only FailureCodeRemoteInsertFailed is accepted. The raw error is never persisted.
// A bounded retry delay is computed based on the current attempt count.
// RowsAffected must be exactly 1.
func (r *QuestionTableExportRepository) MarkFailed(ctx context.Context, exportID, failureCode string) error {
if strings.TrimSpace(exportID) == "" {
return errExportIDRequired
}
if failureCode != questiontable.FailureCodeRemoteInsertFailed {
return errBadExportFailure
}
if r == nil || r.store == nil || r.store.pool == nil {
return errExportNilStore
}
tag, err := r.store.pool.Exec(ctx, `
UPDATE question_table_exports
SET status = 'export_failed',
failure_code = $2,
next_attempt_at = NOW() + (
CASE
WHEN attempts <= 1 THEN '5 seconds'::interval
WHEN attempts = 2 THEN '15 seconds'::interval
WHEN attempts = 3 THEN '45 seconds'::interval
ELSE '5 minutes'::interval
END
),
updated_at = NOW()
WHERE id = $1 AND status = 'exporting'`,
exportID, failureCode)
if err != nil {
return fmt.Errorf("questiontable export mark failed: %w", err)
}
if tag.RowsAffected() != 1 {
return errExportRowsAffected
}
return nil
}
@@ -0,0 +1,437 @@
// Source-level contract tests for the question table export repository SQL.
// No real database connection is used.
package postgres
import (
"os"
"regexp"
"strings"
"testing"
)
func readQuestionTableExportsSource(t *testing.T) string {
t.Helper()
data, err := os.ReadFile("question_table_exports.go")
if err != nil {
t.Fatalf("read question_table_exports.go: %v", err)
}
return string(data)
}
func extractSQLFromQuestionTableExports(t *testing.T) []string {
t.Helper()
src := readQuestionTableExportsSource(t)
var sqls []string
re := regexp.MustCompile("`([^`]*)`")
for _, m := range re.FindAllStringSubmatch(src, -1) {
upper := strings.ToUpper(m[1])
if strings.Contains(upper, "SELECT") || strings.Contains(upper, "UPDATE") ||
strings.Contains(upper, "INSERT") || strings.Contains(upper, "DELETE") ||
strings.Contains(upper, "WITH") {
sqls = append(sqls, m[1])
}
}
return sqls
}
// ---------------------------------------------------------------------------
// Claim SQL structure
// ---------------------------------------------------------------------------
func TestQuestionTableExportsClaimUsesCTE(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
found := false
for _, sql := range sqls {
upper := strings.ToUpper(sql)
if strings.Contains(upper, "WITH CANDIDATES") {
found = true
break
}
}
if !found {
t.Fatal("Claim SQL with CTE not found in question_table_exports.go")
}
}
func TestQuestionTableExportsClaimUsesForUpdateSkipLocked(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
found := false
for _, sql := range sqls {
upper := strings.ToUpper(sql)
if strings.Contains(upper, "FOR UPDATE SKIP LOCKED") {
found = true
break
}
}
if !found {
t.Fatal("Claim must use FOR UPDATE SKIP LOCKED for atomicity")
}
}
func TestQuestionTableExportsClaimUsesSingleUpdate(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
var claimSQL string
for _, sql := range sqls {
upper := strings.ToUpper(sql)
if strings.Contains(upper, "WITH CANDIDATES") {
claimSQL = upper
break
}
}
if claimSQL == "" {
t.Fatal("Claim SQL with CTE not found")
}
updateCount := strings.Count(claimSQL, "UPDATE QUESTION_TABLE_EXPORTS")
if updateCount != 1 {
t.Fatalf("Claim must use exactly one UPDATE, found %d", updateCount)
}
}
// ---------------------------------------------------------------------------
// Claim eligibility: statuses
// ---------------------------------------------------------------------------
func TestQuestionTableExportsClaimStatusAndAttempts(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
joined := strings.ToUpper(strings.Join(sqls, " "))
// Status filter: pending, export_failed, or stale exporting
if !strings.Contains(joined, "STATUS = 'PENDING'") {
t.Error("Claim must include pending cases")
}
if !strings.Contains(joined, "STATUS = 'EXPORT_FAILED'") {
t.Error("Claim must include retryable export_failed cases")
}
if !strings.Contains(joined, "STATUS = 'EXPORTING'") {
t.Error("Claim must include stale exporting cases")
}
// Attempts check
if !strings.Contains(joined, "ATTEMPTS <") {
t.Error("Claim must filter by attempts < maxAttempts")
}
// Stale check
if !strings.Contains(joined, "LAST_ATTEMPT_AT <") {
t.Error("Claim must check last_attempt_at for stale reclaim")
}
}
// ---------------------------------------------------------------------------
// Claim: next_attempt_at condition for export_failed
// ---------------------------------------------------------------------------
func TestQuestionTableExportsClaimNextAttemptAt(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
joined := strings.ToUpper(strings.Join(sqls, " "))
if !strings.Contains(joined, "NEXT_ATTEMPT_AT IS NULL OR NEXT_ATTEMPT_AT <= NOW()") ||
!strings.Contains(joined, "NEXT_ATTEMPT_AT IS NULL") {
// At least check that next_attempt_at appears in the export_failed condition
if !strings.Contains(joined, "NEXT_ATTEMPT_AT") {
t.Error("Claim must use next_attempt_at for retry backoff on export_failed")
}
}
}
// ---------------------------------------------------------------------------
// Claim: order and limit
// ---------------------------------------------------------------------------
func TestQuestionTableExportsClaimOrderAndLimit(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
joined := strings.ToUpper(strings.Join(sqls, " "))
if !strings.Contains(joined, "ORDER BY") {
t.Error("Claim must ORDER BY created_at, id")
}
if !strings.Contains(joined, "LIMIT") {
t.Error("Claim must use parameterized LIMIT")
}
}
// ---------------------------------------------------------------------------
// Claim: scope joins with tenant_key and channel
// ---------------------------------------------------------------------------
func TestQuestionTableExportsClaimScopeJoins(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
joined := strings.ToUpper(strings.Join(sqls, " "))
// Must join on tenant_key and channel for scoping on turns
if !strings.Contains(joined, "T.TENANT_KEY = CL.TENANT_KEY") {
t.Error("Claim turns join must include tenant_key scope")
}
if !strings.Contains(joined, "T.CHANNEL = CL.CHANNEL") {
t.Error("Claim turns join must include channel scope")
}
// Must join on tenant_key and channel for scoping on messages
if !strings.Contains(joined, "M.TENANT_KEY = CL.TENANT_KEY") {
t.Error("Claim messages join must include tenant_key scope")
}
if !strings.Contains(joined, "M.CHANNEL = CL.CHANNEL") {
t.Error("Claim messages join must include channel scope")
}
}
// ---------------------------------------------------------------------------
// Claim: reads question/answer from turns, not stored in export table
// ---------------------------------------------------------------------------
func TestQuestionTableExportsClaimReadsQuestionAnswerFromTurns(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
joined := strings.ToUpper(strings.Join(sqls, " "))
// Must read question/answer from turns table
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")
}
}
// ---------------------------------------------------------------------------
// Claim: reads actor_union_id_snapshot from messages
// ---------------------------------------------------------------------------
func TestQuestionTableExportsClaimReadsActorUnionIDSnapshot(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
joined := strings.ToUpper(strings.Join(sqls, " "))
if !strings.Contains(joined, "ACTOR_UNION_ID_SNAPSHOT") {
t.Error("Claim must read actor_union_id_snapshot from messages")
}
}
// ---------------------------------------------------------------------------
// Claim: transition clears next_attempt_at
// ---------------------------------------------------------------------------
func TestQuestionTableExportsClaimClearsNextAttemptAt(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
joined := strings.ToUpper(strings.Join(sqls, " "))
if !strings.Contains(joined, "NEXT_ATTEMPT_AT = NULL") {
t.Error("Claim UPDATE must clear next_attempt_at")
}
}
// ---------------------------------------------------------------------------
// MarkExported guards
// ---------------------------------------------------------------------------
func TestQuestionTableExportsMarkExportedGuard(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
var markSQL string
for _, sql := range sqls {
upper := strings.ToUpper(sql)
if strings.Contains(upper, "SET STATUS = 'EXPORTED'") {
markSQL = sql
break
}
}
if markSQL == "" {
t.Fatal("MarkExported SQL not found")
}
upper := strings.ToUpper(markSQL)
// Must guard on status = 'exporting'
if !strings.Contains(upper, "STATUS = 'EXPORTING'") {
t.Error("MarkExported must guard on status = 'exporting'")
}
// Must set external_record_id
if !strings.Contains(upper, "EXTERNAL_RECORD_ID") {
t.Error("MarkExported must set external_record_id")
}
// Must clear failure_code
if !strings.Contains(upper, "FAILURE_CODE = ''") {
t.Error("MarkExported must clear failure_code")
}
// Must clear next_attempt_at
if !strings.Contains(upper, "NEXT_ATTEMPT_AT = NULL") {
t.Error("MarkExported must clear next_attempt_at")
}
}
func TestQuestionTableExportsMarkExportedRowsAffected(t *testing.T) {
src := readQuestionTableExportsSource(t)
if !strings.Contains(src, "RowsAffected()") {
t.Error("MarkExported must check RowsAffected()")
}
}
// ---------------------------------------------------------------------------
// MarkFailed guards
// ---------------------------------------------------------------------------
func TestQuestionTableExportsMarkFailedGuard(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
var markSQL string
for _, sql := range sqls {
upper := strings.ToUpper(sql)
if strings.Contains(upper, "SET STATUS = 'EXPORT_FAILED'") {
markSQL = sql
break
}
}
if markSQL == "" {
t.Fatal("MarkFailed SQL not found")
}
upper := strings.ToUpper(markSQL)
// Must guard on status = 'exporting'
if !strings.Contains(upper, "STATUS = 'EXPORTING'") {
t.Error("MarkFailed must guard on status = 'exporting'")
}
// Must set failure_code
if !strings.Contains(upper, "FAILURE_CODE") {
t.Error("MarkFailed must set failure_code")
}
}
func TestQuestionTableExportsMarkFailedOnlyAcceptsStableCode(t *testing.T) {
src := readQuestionTableExportsSource(t)
if !strings.Contains(src, "FailureCodeRemoteInsertFailed") {
t.Error("MarkFailed must validate failureCode == FailureCodeRemoteInsertFailed")
}
}
func TestQuestionTableExportsMarkFailedRowsAffected(t *testing.T) {
src := readQuestionTableExportsSource(t)
if !strings.Contains(src, "RowsAffected()") {
t.Error("MarkFailed must check RowsAffected()")
}
}
// ---------------------------------------------------------------------------
// MarkFailed: backoff intervals
// ---------------------------------------------------------------------------
func TestQuestionTableExportsMarkFailedBackoffIntervals(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
joined := strings.ToUpper(strings.Join(sqls, " "))
if !strings.Contains(joined, "5 SECONDS") {
t.Error("MarkFailed must use 5s backoff for attempts <= 1")
}
if !strings.Contains(joined, "15 SECONDS") {
t.Error("MarkFailed must use 15s backoff for attempts = 2")
}
if !strings.Contains(joined, "45 SECONDS") {
t.Error("MarkFailed must use 45s backoff for attempts = 3")
}
if !strings.Contains(joined, "5 MINUTES") {
t.Error("MarkFailed must use 5m backoff for attempts >= 4")
}
}
// ---------------------------------------------------------------------------
// No raw error leak in SQL
// ---------------------------------------------------------------------------
func TestQuestionTableExportsNoRawErrorLeak(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
joined := strings.ToUpper(strings.Join(sqls, " "))
for _, forbidden := range []string{
"TOKEN", "WEBHOOK", "RAW_ERROR", "RAW_RESPONSE",
"GROUP_ID", "EXTERNAL_CHAT_ID", "EXTERNAL_USER_ID",
} {
if strings.Contains(joined, forbidden) {
t.Errorf("question table export SQL must not contain %q", forbidden)
}
}
}
// ---------------------------------------------------------------------------
// No question/answer bodies stored in export table
// ---------------------------------------------------------------------------
func TestQuestionTableExportsNoQuestionAnswerBodiesStored(t *testing.T) {
sqls := extractSQLFromQuestionTableExports(t)
// Only check standalone MarkExported/MarkFailed UPDATE statements, not the CTE
// which has a SELECT with t.question/t.answer (that's fine — they come from turns).
for _, sql := range sqls {
upper := strings.ToUpper(sql)
// Skip CTE SQL (contains WITH CANDIDATES)
if strings.Contains(upper, "WITH CANDIDATES") {
continue
}
if strings.Contains(upper, "UPDATE QUESTION_TABLE_EXPORTS") {
if strings.Contains(upper, "QUESTION") && !strings.Contains(upper, "QUESTION_TABLE_EXPORTS") {
t.Errorf("UPDATE must not set question column: %q", sql)
}
if strings.Contains(upper, "ANSWER") {
t.Errorf("UPDATE must not set answer column: %q", sql)
}
}
}
}
// ---------------------------------------------------------------------------
// Nil safety
// ---------------------------------------------------------------------------
func TestQuestionTableExportsNilSafe(t *testing.T) {
src := readQuestionTableExportsSource(t)
count := strings.Count(src, "r.store == nil || r.store.pool == nil")
if count < 3 {
t.Errorf("question table export methods must guard against nil store/pool, found %d guards", count)
}
}
// ---------------------------------------------------------------------------
// ExportID validation
// ---------------------------------------------------------------------------
func TestQuestionTableExportsExportIDValidation(t *testing.T) {
src := readQuestionTableExportsSource(t)
if !strings.Contains(src, "TrimSpace(exportID)") {
t.Error("MarkExported/MarkFailed must validate exportID is not empty")
}
}
// ---------------------------------------------------------------------------
// Adapter: compile-time assertion and constructor
// ---------------------------------------------------------------------------
func TestQuestionTableExportsCompileTimeAssertion(t *testing.T) {
src := readQuestionTableExportsSource(t)
if !strings.Contains(src, "var _ questiontable.ExportRepository = (*QuestionTableExportRepository)(nil)") {
t.Error("QuestionTableExportRepository must have compile-time interface assertion")
}
}
func TestQuestionTableExportsConstructorNilSafety(t *testing.T) {
src := readQuestionTableExportsSource(t)
if !strings.Contains(src, "NewQuestionTableExportRepository") {
t.Error("Must have a validated constructor NewQuestionTableExportRepository")
}
if !strings.Contains(src, "errExportNilStore") {
t.Error("Constructor must reject nil store with a stable error")
}
}
// ---------------------------------------------------------------------------
// Claim: input validation
// ---------------------------------------------------------------------------
func TestQuestionTableExportsClaimInputValidation(t *testing.T) {
src := readQuestionTableExportsSource(t)
if !strings.Contains(src, "limit <= 0") || !strings.Contains(src, "limit > 1000") {
t.Error("Claim must validate positive bounded limit")
}
if !strings.Contains(src, "maxAttempts <= 0") || !strings.Contains(src, "maxAttempts > 100") {
t.Error("Claim must validate positive bounded maxAttempts")
}
}
// ---------------------------------------------------------------------------
// MarkExported: external_record_id validation
// ---------------------------------------------------------------------------
func TestQuestionTableExportsMarkExportedLocationValidation(t *testing.T) {
src := readQuestionTableExportsSource(t)
if !strings.Contains(src, "TrimSpace(externalRecordID)") {
t.Error("MarkExported must validate externalRecordID is not empty")
}
}
// ---------------------------------------------------------------------------
// No a1_notation references
// ---------------------------------------------------------------------------
func TestQuestionTableExportsNoA1Notation(t *testing.T) {
src := readQuestionTableExportsSource(t)
if strings.Contains(src, "a1_notation") {
t.Error("question_table_exports.go must not reference stale a1_notation column")
}
}
+28 -6
View File
@@ -83,13 +83,13 @@ func (s *Store) BeginTurn(ctx context.Context, turn core.Turn) (core.Turn, bool,
if err = tx.QueryRow(ctx, `INSERT INTO messages
(id,tenant_key,channel,conversation_id,actor_id,external_message_id,correlation_id,
direction,role,message_type,text_content,media_json,status,actor_name_snapshot,department_snapshot,region_snapshot,safe_metadata_json)
VALUES($1,$2,$3,$4,$5,$6,$7,'inbound','user',$8,$9,$10,'received',$11,$12,$13,'{}'::JSONB)
direction,role,message_type,text_content,media_json,status,actor_name_snapshot,trigger_person_snapshot,actor_union_id_snapshot,department_snapshot,region_snapshot,safe_metadata_json)
VALUES($1,$2,$3,$4,$5,$6,$7,'inbound','user',$8,$9,$10,'received',$11,$12,$13,$14,$15,'{}'::JSONB)
ON CONFLICT (tenant_key,channel,external_message_id) WHERE external_message_id!=''
DO UPDATE SET updated_at=messages.updated_at
RETURNING id`, turn.RequestMessageID, turn.TenantKey, turn.Channel, turn.ConversationID,
turn.ActorID, turn.ExternalMessageID, turn.ID, turn.MessageType, turn.Question, mediaJSON,
turn.SenderName, turn.DepartmentSnapshot, turn.RegionSnapshot).Scan(&turn.RequestMessageID); err != nil {
turn.SenderName, turn.TriggerPersonSnapshot, turn.ActorUnionIDSnapshot, turn.DepartmentSnapshot, turn.RegionSnapshot).Scan(&turn.RequestMessageID); err != nil {
return core.Turn{}, false, err
}
@@ -207,6 +207,21 @@ func (s *Store) FinishTurn(ctx context.Context, turn core.Turn) error {
return err
}
answerMessageID = turn.AnswerMessageID
if shouldEnqueueQuestionTableExport(turn) {
exportID, err := newUUID()
if err != nil {
return err
}
_, err = tx.Exec(ctx, `INSERT INTO question_table_exports
(id,tenant_key,channel,turn_id,status)
VALUES($1,$2,$3,$4,'pending')
ON CONFLICT (tenant_key,channel,turn_id) DO NOTHING`,
exportID, turn.TenantKey, turn.Channel, turn.ID)
if err != nil {
return err
}
}
}
_, err = tx.Exec(ctx, `UPDATE turns SET weknora_session_id=$2,weknora_request_id=$3,answer=$4,references_json=$5,media_json=$6,status=$7,error_message=$8,answer_message_id=COALESCE($9::TEXT,answer_message_id),updated_at=NOW() WHERE id=$1`,
turn.ID, turn.WeKnoraSessionID, turn.WeKnoraRequestID, turn.Answer, references, mediaJSON,
@@ -264,14 +279,14 @@ func loadTurnWith(ctx context.Context, query rowQuerier, tenantKey, channel, mes
var references []byte
var mediaJSON []byte
var agentID, requestMessageID, answerMessageID *string
var actorID, conversationID, messageType, actorName *string
var actorID, conversationID, messageType, actorName, actorUnionID *string
var conversationType, externalConversationID, externalActorID *string
var answerDeliveryStatus, answerDeliveryMethod *string
err := query.QueryRow(ctx, `SELECT
t.id,t.tenant_key,t.channel,t.external_message_id,t.session_key,t.weknora_session_id,
t.weknora_request_id,t.question,t.answer,t.references_json,t.media_json,t.status,t.error_message,
t.agent_id,t.request_message_id,t.answer_message_id,
m.actor_id,m.conversation_id,m.message_type,m.actor_name_snapshot,
m.actor_id,m.conversation_id,m.message_type,m.actor_name_snapshot,m.actor_union_id_snapshot,
c.conversation_type,c.external_conversation_id,a.external_actor_id,
am.status,am.delivery_method
FROM turns t
@@ -283,7 +298,7 @@ func loadTurnWith(ctx context.Context, query rowQuerier, tenantKey, channel, mes
&turn.ID, &turn.TenantKey, &turn.Channel, &turn.ExternalMessageID, &turn.SessionKey,
&turn.WeKnoraSessionID, &turn.WeKnoraRequestID, &turn.Question, &turn.Answer, &references,
&mediaJSON, &turn.Status, &turn.ErrorMessage, &agentID, &requestMessageID, &answerMessageID,
&actorID, &conversationID, &messageType, &actorName, &conversationType,
&actorID, &conversationID, &messageType, &actorName, &actorUnionID, &conversationType,
&externalConversationID, &externalActorID, &answerDeliveryStatus, &answerDeliveryMethod)
if err != nil {
return core.Turn{}, err
@@ -315,6 +330,9 @@ func loadTurnWith(ctx context.Context, query rowQuerier, tenantKey, channel, mes
if actorName != nil {
turn.SenderName = *actorName
}
if actorUnionID != nil {
turn.ActorUnionIDSnapshot = *actorUnionID
}
if externalActorID != nil {
turn.ExternalUserID = *externalActorID
}
@@ -343,6 +361,10 @@ func shouldCreateAnswerMessage(turn core.Turn) bool {
strings.TrimSpace(turn.AnswerMessageID) != ""
}
func shouldEnqueueQuestionTableExport(turn core.Turn) bool {
return shouldCreateAnswerMessage(turn) && strings.EqualFold(strings.TrimSpace(turn.Channel), "dingtalk")
}
func validateDeliveryUpdate(update core.DeliveryUpdate) error {
if strings.TrimSpace(update.TenantKey) == "" || strings.TrimSpace(update.Channel) == "" ||
strings.TrimSpace(update.AnswerMessageID) == "" || strings.TrimSpace(update.CorrelationID) == "" {