feat: add coverage decision persistence
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/coverage"
|
||||
)
|
||||
|
||||
// SaveCoverageDecision implements coverage.Repository. It writes the decision
|
||||
// and, for uncovered verdicts, atomically creates a pending support case in a
|
||||
// single transaction. Both writes are idempotent via ON CONFLICT DO NOTHING.
|
||||
func (s *Store) SaveCoverageDecision(ctx context.Context, d coverage.Decision) error {
|
||||
if s == nil || s.pool == nil {
|
||||
return coverage.ErrRepository
|
||||
}
|
||||
|
||||
decisionID, err := newUUID()
|
||||
if err != nil {
|
||||
return fmt.Errorf("coverage decision id: %w", err)
|
||||
}
|
||||
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("coverage tx begin: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
var persistedDecisionID string
|
||||
err = tx.QueryRow(ctx, `INSERT INTO coverage_decisions
|
||||
(id, tenant_key, channel, turn_id, evaluator_version, verdict, reason_code, top_score)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8)
|
||||
ON CONFLICT (tenant_key, channel, turn_id)
|
||||
DO UPDATE SET id=coverage_decisions.id
|
||||
RETURNING id`,
|
||||
decisionID, d.TenantKey, d.Channel, d.TurnID,
|
||||
d.EvaluatorVersion, d.Verdict, d.ReasonCode, d.TopScore).Scan(&persistedDecisionID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("coverage insert decision: %w", err)
|
||||
}
|
||||
|
||||
// Only create support case for uncovered verdicts.
|
||||
if d.Verdict == coverage.VerdictUncovered {
|
||||
caseID, err := newUUID()
|
||||
if err != nil {
|
||||
return fmt.Errorf("coverage case id: %w", err)
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO support_cases
|
||||
(id, tenant_key, channel, turn_id, coverage_decision_id, status)
|
||||
VALUES($1,$2,$3,$4,$5,$6)
|
||||
ON CONFLICT (tenant_key, channel, turn_id) DO NOTHING`,
|
||||
caseID, d.TenantKey, d.Channel, d.TurnID, persistedDecisionID, "pending")
|
||||
if err != nil {
|
||||
return fmt.Errorf("coverage insert support case: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("coverage tx commit: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// newUUID produces a 32-char hex id.
|
||||
func newUUID() (string, error) {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("%08x%04x%04x%04x%012x",
|
||||
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
// Source-level contract tests for the coverage repository SQL.
|
||||
// No real database connection is used.
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func readCoverageSource(t *testing.T) string {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile("coverage.go")
|
||||
if err != nil {
|
||||
t.Fatalf("read coverage.go: %v", err)
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func extractSQLFromCoverage(t *testing.T) []string {
|
||||
t.Helper()
|
||||
src := readCoverageSource(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") {
|
||||
sqls = append(sqls, m[1])
|
||||
}
|
||||
}
|
||||
return sqls
|
||||
}
|
||||
|
||||
func TestCoverageRepoInsertsIntoCoverageDecisions(t *testing.T) {
|
||||
// Find the INSERT INTO coverage_decisions SQL in coverage.go
|
||||
sqls := extractSQLFromCoverage(t)
|
||||
var found string
|
||||
for _, sql := range sqls {
|
||||
upper := strings.ToUpper(sql)
|
||||
if strings.Contains(upper, "INSERT INTO COVERAGE_DECISIONS") {
|
||||
found = sql
|
||||
break
|
||||
}
|
||||
}
|
||||
if found == "" {
|
||||
t.Fatal("INSERT INTO coverage_decisions SQL not found in coverage.go")
|
||||
}
|
||||
|
||||
requiredCols := []string{
|
||||
"id", "tenant_key", "channel", "turn_id",
|
||||
"evaluator_version", "verdict", "reason_code", "top_score",
|
||||
}
|
||||
upper := strings.ToUpper(found)
|
||||
for _, col := range requiredCols {
|
||||
if !strings.Contains(upper, strings.ToUpper(col)) {
|
||||
t.Errorf("INSERT INTO coverage_decisions missing column %q", col)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoverageRepoReplayReturnsPersistedDecisionIDForSupportCase(t *testing.T) {
|
||||
sqls := extractSQLFromCoverage(t)
|
||||
var decisionInsert string
|
||||
for _, sql := range sqls {
|
||||
if strings.Contains(strings.ToUpper(sql), "INSERT INTO COVERAGE_DECISIONS") {
|
||||
decisionInsert = strings.ToUpper(sql)
|
||||
break
|
||||
}
|
||||
}
|
||||
if decisionInsert == "" {
|
||||
t.Fatal("INSERT INTO coverage_decisions SQL not found")
|
||||
}
|
||||
if !strings.Contains(decisionInsert, "ON CONFLICT (TENANT_KEY, CHANNEL, TURN_ID)") {
|
||||
t.Fatal("decision upsert must use the scoped idempotency key")
|
||||
}
|
||||
if !strings.Contains(decisionInsert, "DO UPDATE") || !strings.Contains(decisionInsert, "RETURNING ID") {
|
||||
t.Fatal("decision upsert must return the persisted ID on both insert and replay")
|
||||
}
|
||||
|
||||
src := readCoverageSource(t)
|
||||
if !strings.Contains(src, "persistedDecisionID") {
|
||||
t.Fatal("support case must use the persisted decision ID")
|
||||
}
|
||||
if !strings.Contains(src, "d.TurnID, persistedDecisionID") {
|
||||
t.Fatal("support case INSERT must reference persistedDecisionID, not a new conflicting ID")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoverageRepoInsertsSupportCaseOnlyForUncovered(t *testing.T) {
|
||||
sqls := extractSQLFromCoverage(t)
|
||||
var insertSQL string
|
||||
for _, sql := range sqls {
|
||||
upper := strings.ToUpper(sql)
|
||||
if strings.Contains(upper, "INSERT INTO SUPPORT_CASES") {
|
||||
insertSQL = sql
|
||||
break
|
||||
}
|
||||
}
|
||||
if insertSQL == "" {
|
||||
t.Fatal("INSERT INTO support_cases SQL not found in coverage.go")
|
||||
}
|
||||
|
||||
upper := strings.ToUpper(insertSQL)
|
||||
requiredCols := []string{
|
||||
"id", "tenant_key", "channel", "turn_id",
|
||||
"coverage_decision_id", "status",
|
||||
}
|
||||
for _, col := range requiredCols {
|
||||
if !strings.Contains(upper, strings.ToUpper(col)) {
|
||||
t.Errorf("INSERT INTO support_cases missing column %q", col)
|
||||
}
|
||||
}
|
||||
// Must have ON CONFLICT for idempotency
|
||||
if !strings.Contains(upper, "ON CONFLICT") {
|
||||
t.Error("support_cases INSERT must use ON CONFLICT for idempotency")
|
||||
}
|
||||
if !strings.Contains(upper, "DO NOTHING") {
|
||||
t.Error("support_cases ON CONFLICT must use DO NOTHING")
|
||||
}
|
||||
|
||||
// Check that the support_cases INSERT is guarded by a verdict check
|
||||
src := readCoverageSource(t)
|
||||
if !strings.Contains(src, "VerdictUncovered") {
|
||||
t.Error("support_cases INSERT must be guarded by uncovered verdict check")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoverageRepoUsesSingleTransaction(t *testing.T) {
|
||||
src := readCoverageSource(t)
|
||||
// Must use BeginTx
|
||||
if !strings.Contains(src, "BeginTx") {
|
||||
t.Error("SaveCoverageDecision must use a transaction (BeginTx)")
|
||||
}
|
||||
// Must commit
|
||||
if !strings.Contains(src, "Commit(ctx)") {
|
||||
t.Error("SaveCoverageDecision must commit the transaction")
|
||||
}
|
||||
// Must rollback on error
|
||||
if !strings.Contains(src, "Rollback(ctx)") {
|
||||
t.Error("SaveCoverageDecision must rollback on error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoverageRepoNoReservedWords(t *testing.T) {
|
||||
sqls := extractSQLFromCoverage(t)
|
||||
for _, sql := range sqls {
|
||||
upper := strings.ToUpper(sql)
|
||||
// Check for bare "references" as column name (not references_json)
|
||||
// Remove references_json first
|
||||
scrubbed := regexp.MustCompile("(?i)\\breferences_json\\b").ReplaceAllString(upper, "")
|
||||
// Also remove REFERENCES as foreign key keyword
|
||||
scrubbed = regexp.MustCompile("(?i)\\bREFERENCES\\s+(COVERAGE_DECISIONS|TURNS)\\b").ReplaceAllString(scrubbed, "")
|
||||
if regexp.MustCompile("(?i)\\bREFERENCES\\b").MatchString(scrubbed) {
|
||||
t.Errorf("SQL uses reserved word 'references' as identifier: %s", sql)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoverageRepoNoQuestionAnswerBodies(t *testing.T) {
|
||||
sqls := extractSQLFromCoverage(t)
|
||||
joined := strings.ToUpper(strings.Join(sqls, " "))
|
||||
for _, forbidden := range []string{"QUESTION", "ANSWER_TEXT", "REFERENCE_CONTENT", "ANSWER_CONTENT"} {
|
||||
if strings.Contains(joined, forbidden) {
|
||||
t.Errorf("coverage repository SQL must not dupe question/answer/reference bodies: found %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoverageRepoSavesTenantChannelTurnScope(t *testing.T) {
|
||||
src := readCoverageSource(t)
|
||||
// Must pass tenant, channel, turn values to the INSERT
|
||||
if !strings.Contains(src, "d.TenantKey") || !strings.Contains(src, "d.Channel") || !strings.Contains(src, "d.TurnID") {
|
||||
t.Error("SaveCoverageDecision must use d.TenantKey, d.Channel, d.TurnID for tenant/channel/turn scope")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoverageRepoNilSafe(t *testing.T) {
|
||||
src := readCoverageSource(t)
|
||||
// Must check for nil store/pool
|
||||
if !strings.Contains(src, "s == nil") || !strings.Contains(src, "s.pool == nil") {
|
||||
t.Error("SaveCoverageDecision must guard against nil store/pool")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user