feat(dingtalk): add reasoning mode and support evidence
This commit is contained in:
@@ -82,6 +82,11 @@ func (s *Store) RecordFeedback(ctx context.Context, record feedback.Record) (fee
|
||||
if command.RowsAffected() != 1 {
|
||||
return feedback.Result{}, errors.New("insert feedback state affected unexpected rows")
|
||||
}
|
||||
if record.Value == feedback.ValueDown {
|
||||
if err = s.ensureFeedbackSupportCase(ctx, tx, record, record.ID, turnID); err != nil {
|
||||
return feedback.Result{}, err
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return feedback.Result{}, fmt.Errorf("commit feedback create: %w", err)
|
||||
}
|
||||
@@ -92,6 +97,11 @@ func (s *Store) RecordFeedback(ctx context.Context, record feedback.Record) (fee
|
||||
}
|
||||
|
||||
if sameFeedbackState(existingValue, existingReason, record.Value, record.ReasonCode) {
|
||||
if record.Value == feedback.ValueDown {
|
||||
if err = s.ensureFeedbackSupportCase(ctx, tx, record, existingID, turnID); err != nil {
|
||||
return feedback.Result{}, err
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return feedback.Result{}, fmt.Errorf("commit feedback replay: %w", err)
|
||||
}
|
||||
@@ -108,12 +118,42 @@ func (s *Store) RecordFeedback(ctx context.Context, record feedback.Record) (fee
|
||||
if command.RowsAffected() != 1 {
|
||||
return feedback.Result{}, errors.New("update feedback state affected unexpected rows")
|
||||
}
|
||||
if record.Value == feedback.ValueDown {
|
||||
if err = s.ensureFeedbackSupportCase(ctx, tx, record, existingID, turnID); err != nil {
|
||||
return feedback.Result{}, err
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return feedback.Result{}, fmt.Errorf("commit feedback change: %w", err)
|
||||
}
|
||||
return feedback.Result{Changed: true, Value: record.Value, ReasonCode: record.ReasonCode}, nil
|
||||
}
|
||||
|
||||
func (s *Store) ensureFeedbackSupportCase(ctx context.Context, tx pgx.Tx, record feedback.Record, feedbackID, turnID string) error {
|
||||
var decisionID *string
|
||||
if err := tx.QueryRow(ctx, `SELECT (SELECT id FROM coverage_decisions
|
||||
WHERE tenant_key=$1 AND channel=$2 AND turn_id=$3)`,
|
||||
record.TenantKey, record.Channel, turnID,
|
||||
).Scan(&decisionID); err != nil {
|
||||
return fmt.Errorf("find feedback coverage decision: %w", err)
|
||||
}
|
||||
caseID, err := newUUID()
|
||||
if err != nil {
|
||||
return fmt.Errorf("generate feedback support case ID: %w", err)
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO support_cases
|
||||
(id,tenant_key,channel,turn_id,coverage_decision_id,status,faq_export_status,trigger_type,trigger_feedback_id)
|
||||
VALUES($1,$2,$3,$4,$5,'pending',$6,'feedback_down',$7)
|
||||
ON CONFLICT (tenant_key,channel,turn_id) DO NOTHING`,
|
||||
caseID, record.TenantKey, record.Channel, turnID, decisionID,
|
||||
faqExportStatus(s.faqExportEnabled), feedbackID,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert feedback support case: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateFeedbackRecord(record feedback.Record) error {
|
||||
if record.ID == "" || record.ActorID == "" || record.TenantKey == "" || record.Channel == "" ||
|
||||
record.ExternalActorID == "" || record.OutTrackID == "" || record.Source != feedback.SourceDingTalkCard {
|
||||
|
||||
@@ -75,3 +75,29 @@ func TestSameFeedbackState(t *testing.T) {
|
||||
t.Fatal("value change must be a state change")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedbackDownvoteEnsuresIdempotentSupportCaseInsideTransaction(t *testing.T) {
|
||||
data, err := os.ReadFile("feedback.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := strings.ToUpper(string(data))
|
||||
for _, required := range []string{
|
||||
"ENSUREFEEDBACKSUPPORTCASE",
|
||||
"SELECT ID FROM COVERAGE_DECISIONS",
|
||||
"TENANT_KEY=$1 AND CHANNEL=$2 AND TURN_ID=$3",
|
||||
"INSERT INTO SUPPORT_CASES",
|
||||
"TRIGGER_TYPE",
|
||||
"TRIGGER_FEEDBACK_ID",
|
||||
"'FEEDBACK_DOWN'",
|
||||
"ON CONFLICT (TENANT_KEY,CHANNEL,TURN_ID) DO NOTHING",
|
||||
"FAQEXPORTSTATUS(S.FAQEXPORTENABLED)",
|
||||
} {
|
||||
if !strings.Contains(source, required) {
|
||||
t.Errorf("feedback support wiring missing %q", required)
|
||||
}
|
||||
}
|
||||
if strings.Count(source, "ENSUREFEEDBACKSUPPORTCASE") < 4 {
|
||||
t.Fatal("create, replay, and changed-down paths must all ensure the same idempotent support case")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/feedback"
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/reasoningmode"
|
||||
)
|
||||
|
||||
func openIntegrationStore(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
url := os.Getenv("DOBOTAI_POSTGRES_INTEGRATION_URL")
|
||||
if url == "" {
|
||||
t.Skip("DOBOTAI_POSTGRES_INTEGRATION_URL is not set")
|
||||
}
|
||||
store, err := Open(context.Background(), url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(store.Close)
|
||||
return store
|
||||
}
|
||||
|
||||
func seedSucceededTurn(t *testing.T, store *Store, suffix string, deliveredCard bool) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
tenant, channel := "tenant-"+suffix, "dingtalk"
|
||||
actorID, conversationID := "actor-"+suffix, "conversation-"+suffix
|
||||
requestID, turnID, answerID := "request-"+suffix, "turn-"+suffix, "answer-"+suffix
|
||||
if _, err := store.pool.Exec(ctx, `INSERT INTO channel_actors(id,tenant_key,channel,external_actor_id,actor_type) VALUES($1,$2,$3,$4,'user')`, actorID, tenant, channel, "staff-"+suffix); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.pool.Exec(ctx, `INSERT INTO channel_conversations(id,tenant_key,channel,external_conversation_id,conversation_type) VALUES($1,$2,$3,$4,'direct')`, conversationID, tenant, channel, "chat-"+suffix); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.pool.Exec(ctx, `INSERT INTO messages(id,tenant_key,channel,conversation_id,actor_id,external_message_id,correlation_id,direction,role,message_type,text_content,status) VALUES($1,$2,$3,$4,$5,$6,$7,'inbound','user','text','question','received')`, requestID, tenant, channel, conversationID, actorID, "external-"+suffix, turnID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.pool.Exec(ctx, `INSERT INTO turns(id,tenant_key,channel,external_message_id,session_key,question,answer,status,request_message_id,agent_id) VALUES($1,$2,$3,$4,$5,'question','answer','succeeded',$6,'agent')`, turnID, tenant, channel, "external-"+suffix, "session-"+suffix, requestID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
messageStatus, method, providerID := "generated", "", ""
|
||||
if deliveredCard {
|
||||
messageStatus, method, providerID = "sent", "card", "track-"+suffix
|
||||
}
|
||||
if _, err := store.pool.Exec(ctx, `INSERT INTO messages(id,tenant_key,channel,conversation_id,external_message_id,correlation_id,direction,role,message_type,text_content,reply_to_message_id,status,delivery_method,provider_message_id) VALUES($1,$2,$3,$4,'',$5,'outbound','assistant','text','answer',$6,$7,$8,$9)`, answerID, tenant, channel, conversationID, turnID, requestID, messageStatus, method, providerID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.pool.Exec(ctx, `UPDATE turns SET answer_message_id=$2 WHERE id=$1`, turnID, answerID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.pool.Exec(ctx, `INSERT INTO coverage_decisions(id,tenant_key,channel,turn_id,evaluator_version,verdict,reason_code,reference_count,top_score) VALUES($1,$2,$3,$4,'v3','covered','covered_has_references',1,0)`, "decision-"+suffix, tenant, channel, turnID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationReasoningCompletionIsIdempotent(t *testing.T) {
|
||||
store := openIntegrationStore(t)
|
||||
seedSucceededTurn(t, store, "reasoning", false)
|
||||
ctx := context.Background()
|
||||
scope := reasoningmode.Scope{TenantKey: "tenant-reasoning", Channel: "dingtalk", ExternalActorID: "staff-reasoning"}
|
||||
now := time.Date(2026, 9, 9, 12, 0, 0, 0, time.UTC)
|
||||
if _, err := store.Enable(ctx, scope, now, 10*time.Minute); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.pool.Exec(ctx, `UPDATE reasoning_mode_states SET rounds_used=7 WHERE tenant_key=$1 AND channel=$2 AND external_actor_id=$3`, scope.TenantKey, scope.Channel, scope.ExternalActorID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := reasoningmode.TurnCompletion{Scope: scope, TurnID: "turn-reasoning", Execution: reasoningmode.ExecutionReasoning, At: now.Add(time.Minute), Idle: 10 * time.Minute}
|
||||
first, err := store.CompleteTurn(ctx, input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := store.CompleteTurn(ctx, input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.RoundNumber != 8 || !first.ShowHint || second.RoundNumber != 8 || !second.ShowHint {
|
||||
t.Fatalf("first=%+v second=%+v", first, second)
|
||||
}
|
||||
var rounds, ledger int
|
||||
if err := store.pool.QueryRow(ctx, `SELECT rounds_used FROM reasoning_mode_states WHERE tenant_key=$1 AND channel=$2 AND external_actor_id=$3`, scope.TenantKey, scope.Channel, scope.ExternalActorID).Scan(&rounds); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.pool.QueryRow(ctx, `SELECT count(*) FROM reasoning_mode_turns WHERE tenant_key=$1 AND channel=$2 AND turn_id=$3`, scope.TenantKey, scope.Channel, input.TurnID).Scan(&ledger); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rounds != 8 || ledger != 1 {
|
||||
t.Fatalf("rounds=%d ledger=%d", rounds, ledger)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationDownvoteCreatesOneFeedbackSupportCase(t *testing.T) {
|
||||
store := openIntegrationStore(t)
|
||||
seedSucceededTurn(t, store, "feedback", true)
|
||||
store.SetExternalTableExports(false, true)
|
||||
ctx := context.Background()
|
||||
command := feedback.Record{
|
||||
ID: "feedback-state-1", TenantKey: "tenant-feedback", Channel: "dingtalk", ActorID: "feedback-actor-1",
|
||||
ExternalActorID: "staff-feedback", OutTrackID: "track-feedback", Value: feedback.ValueDown,
|
||||
ReasonCode: feedback.ReasonEmpty, Source: feedback.SourceDingTalkCard,
|
||||
}
|
||||
if _, err := store.RecordFeedback(ctx, command); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
command.ID, command.ActorID = "feedback-state-replay", "feedback-actor-replay"
|
||||
result, err := store.RecordFeedback(ctx, command)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !result.Replayed {
|
||||
t.Fatalf("result=%+v", result)
|
||||
}
|
||||
var count int
|
||||
var triggerType, faqStatus string
|
||||
if err := store.pool.QueryRow(ctx, `SELECT count(*),max(trigger_type),max(faq_export_status) FROM support_cases WHERE tenant_key=$1 AND channel=$2 AND turn_id=$3`, "tenant-feedback", "dingtalk", "turn-feedback").Scan(&count, &triggerType, &faqStatus); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 1 || triggerType != "feedback_down" || faqStatus != "pending" {
|
||||
t.Fatalf("count=%d trigger=%q faq=%q", count, triggerType, faqStatus)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationDownvoteCreatesCaseWithoutCoverageDecision(t *testing.T) {
|
||||
store := openIntegrationStore(t)
|
||||
seedSucceededTurn(t, store, "feedback-no-decision", true)
|
||||
store.SetExternalTableExports(false, true)
|
||||
ctx := context.Background()
|
||||
if _, err := store.pool.Exec(ctx, `DELETE FROM coverage_decisions
|
||||
WHERE tenant_key=$1 AND channel=$2 AND turn_id=$3`,
|
||||
"tenant-feedback-no-decision", "dingtalk", "turn-feedback-no-decision"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
command := feedback.Record{
|
||||
ID: "feedback-state-no-decision", TenantKey: "tenant-feedback-no-decision", Channel: "dingtalk", ActorID: "feedback-actor-no-decision",
|
||||
ExternalActorID: "staff-feedback-no-decision", OutTrackID: "track-feedback-no-decision", Value: feedback.ValueDown,
|
||||
ReasonCode: feedback.ReasonEmpty, Source: feedback.SourceDingTalkCard,
|
||||
}
|
||||
if _, err := store.RecordFeedback(ctx, command); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var count int
|
||||
if err := store.pool.QueryRow(ctx, `SELECT count(*) FROM support_cases
|
||||
WHERE tenant_key=$1 AND channel=$2 AND turn_id=$3 AND coverage_decision_id IS NULL
|
||||
AND trigger_type='feedback_down'`,
|
||||
"tenant-feedback-no-decision", "dingtalk", "turn-feedback-no-decision").Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("count=%d", count)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/reasoningmode"
|
||||
)
|
||||
|
||||
func (s *Store) ResolveState(ctx context.Context, scope reasoningmode.Scope, now time.Time) (reasoningmode.State, bool, error) {
|
||||
if err := validateReasoningScope(scope); err != nil {
|
||||
return reasoningmode.State{}, false, err
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return reasoningmode.State{}, false, fmt.Errorf("begin reasoning state resolve: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if err = ensureReasoningState(ctx, tx, scope); err != nil {
|
||||
return reasoningmode.State{}, false, err
|
||||
}
|
||||
state, err := selectReasoningStateForUpdate(ctx, tx, scope)
|
||||
if err != nil {
|
||||
return reasoningmode.State{}, false, err
|
||||
}
|
||||
effective, expired := reasoningmode.EffectiveState(state, now)
|
||||
if expired {
|
||||
if err = updateReasoningState(ctx, tx, scope, effective, now); err != nil {
|
||||
return reasoningmode.State{}, false, err
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return reasoningmode.State{}, false, fmt.Errorf("commit reasoning state resolve: %w", err)
|
||||
}
|
||||
return effective, expired, nil
|
||||
}
|
||||
|
||||
func (s *Store) Enable(ctx context.Context, scope reasoningmode.Scope, now time.Time, idle time.Duration) (reasoningmode.State, error) {
|
||||
if err := validateReasoningScope(scope); err != nil || idle <= 0 {
|
||||
if err != nil {
|
||||
return reasoningmode.State{}, err
|
||||
}
|
||||
return reasoningmode.State{}, reasoningmode.ErrInvalidState
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return reasoningmode.State{}, fmt.Errorf("begin reasoning enable: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if err = ensureReasoningState(ctx, tx, scope); err != nil {
|
||||
return reasoningmode.State{}, err
|
||||
}
|
||||
state, err := selectReasoningStateForUpdate(ctx, tx, scope)
|
||||
if err != nil {
|
||||
return reasoningmode.State{}, err
|
||||
}
|
||||
state.Mode = reasoningmode.ModeReasoning
|
||||
state.RoundsUsed = 0
|
||||
state.LastActivityAt = now
|
||||
state.ExpiresAt = now.Add(idle)
|
||||
if err = updateReasoningState(ctx, tx, scope, state, now); err != nil {
|
||||
return reasoningmode.State{}, err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return reasoningmode.State{}, fmt.Errorf("commit reasoning enable: %w", err)
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func (s *Store) Disable(ctx context.Context, scope reasoningmode.Scope, now time.Time) (reasoningmode.State, bool, error) {
|
||||
if err := validateReasoningScope(scope); err != nil {
|
||||
return reasoningmode.State{}, false, err
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return reasoningmode.State{}, false, fmt.Errorf("begin reasoning disable: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if err = ensureReasoningState(ctx, tx, scope); err != nil {
|
||||
return reasoningmode.State{}, false, err
|
||||
}
|
||||
state, err := selectReasoningStateForUpdate(ctx, tx, scope)
|
||||
if err != nil {
|
||||
return reasoningmode.State{}, false, err
|
||||
}
|
||||
state, _ = reasoningmode.EffectiveState(state, now)
|
||||
wasReasoning := state.Mode == reasoningmode.ModeReasoning
|
||||
state.Mode = reasoningmode.ModeQuick
|
||||
state.RoundsUsed = 0
|
||||
state.ExpiresAt = time.Time{}
|
||||
if err = updateReasoningState(ctx, tx, scope, state, now); err != nil {
|
||||
return reasoningmode.State{}, false, err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return reasoningmode.State{}, false, fmt.Errorf("commit reasoning disable: %w", err)
|
||||
}
|
||||
return state, wasReasoning, nil
|
||||
}
|
||||
|
||||
func (s *Store) SetMaxRounds(ctx context.Context, scope reasoningmode.Scope, maxRounds int, now time.Time) (reasoningmode.State, error) {
|
||||
if err := validateReasoningScope(scope); err != nil {
|
||||
return reasoningmode.State{}, err
|
||||
}
|
||||
if maxRounds < 1 || maxRounds > 50 {
|
||||
return reasoningmode.State{}, reasoningmode.ErrInvalidState
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return reasoningmode.State{}, fmt.Errorf("begin reasoning rounds update: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if err = ensureReasoningState(ctx, tx, scope); err != nil {
|
||||
return reasoningmode.State{}, err
|
||||
}
|
||||
state, err := selectReasoningStateForUpdate(ctx, tx, scope)
|
||||
if err != nil {
|
||||
return reasoningmode.State{}, err
|
||||
}
|
||||
state.MaxRounds = maxRounds
|
||||
if state.RoundsUsed >= maxRounds {
|
||||
state.Mode = reasoningmode.ModeQuick
|
||||
state.RoundsUsed = 0
|
||||
state.ExpiresAt = time.Time{}
|
||||
}
|
||||
if err = updateReasoningState(ctx, tx, scope, state, now); err != nil {
|
||||
return reasoningmode.State{}, err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return reasoningmode.State{}, fmt.Errorf("commit reasoning rounds update: %w", err)
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func (s *Store) SetHintEnabled(ctx context.Context, scope reasoningmode.Scope, enabled bool, now time.Time) (reasoningmode.State, error) {
|
||||
if err := validateReasoningScope(scope); err != nil {
|
||||
return reasoningmode.State{}, err
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return reasoningmode.State{}, fmt.Errorf("begin reasoning hint update: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if err = ensureReasoningState(ctx, tx, scope); err != nil {
|
||||
return reasoningmode.State{}, err
|
||||
}
|
||||
state, err := selectReasoningStateForUpdate(ctx, tx, scope)
|
||||
if err != nil {
|
||||
return reasoningmode.State{}, err
|
||||
}
|
||||
state.HintEnabled = enabled
|
||||
if err = updateReasoningState(ctx, tx, scope, state, now); err != nil {
|
||||
return reasoningmode.State{}, err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return reasoningmode.State{}, fmt.Errorf("commit reasoning hint update: %w", err)
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func (s *Store) CompleteTurn(ctx context.Context, input reasoningmode.TurnCompletion) (reasoningmode.Completion, error) {
|
||||
if err := validateReasoningScope(input.Scope); err != nil {
|
||||
return reasoningmode.Completion{}, err
|
||||
}
|
||||
if strings.TrimSpace(input.TurnID) == "" || input.At.IsZero() || input.Idle <= 0 {
|
||||
return reasoningmode.Completion{}, reasoningmode.ErrInvalidState
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return reasoningmode.Completion{}, fmt.Errorf("begin reasoning turn completion: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
var existing reasoningmode.Completion
|
||||
err = tx.QueryRow(ctx, `SELECT round_number,showed_hint,auto_closed,showed_onboarding
|
||||
FROM reasoning_mode_turns
|
||||
WHERE tenant_key=$1 AND channel=$2 AND turn_id=$3 AND external_actor_id=$4
|
||||
FOR UPDATE`, input.Scope.TenantKey, input.Scope.Channel, input.TurnID, input.Scope.ExternalActorID).Scan(
|
||||
&existing.RoundNumber, &existing.ShowHint, &existing.AutoClosed, &existing.ShowOnboarding,
|
||||
)
|
||||
if err == nil {
|
||||
if existing.Next, err = selectReasoningState(ctx, tx, input.Scope); err != nil {
|
||||
return reasoningmode.Completion{}, err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return reasoningmode.Completion{}, fmt.Errorf("commit replayed reasoning completion: %w", err)
|
||||
}
|
||||
return existing, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return reasoningmode.Completion{}, fmt.Errorf("find reasoning turn completion: %w", err)
|
||||
}
|
||||
var status string
|
||||
if err = tx.QueryRow(ctx, `SELECT t.status FROM turns t
|
||||
JOIN messages m ON m.id=t.request_message_id
|
||||
JOIN channel_actors a ON a.id=m.actor_id
|
||||
WHERE t.id=$1 AND t.tenant_key=$2 AND t.channel=$3
|
||||
AND a.external_actor_id=$4
|
||||
FOR UPDATE OF t`, input.TurnID, input.Scope.TenantKey, input.Scope.Channel, input.Scope.ExternalActorID).Scan(&status); err != nil {
|
||||
return reasoningmode.Completion{}, fmt.Errorf("lock reasoning completion turn: %w", err)
|
||||
}
|
||||
if status != "succeeded" {
|
||||
return reasoningmode.Completion{}, errors.New("reasoning completion requires a succeeded turn")
|
||||
}
|
||||
|
||||
if err = ensureReasoningState(ctx, tx, input.Scope); err != nil {
|
||||
return reasoningmode.Completion{}, err
|
||||
}
|
||||
state, err := selectReasoningStateForUpdate(ctx, tx, input.Scope)
|
||||
if err != nil {
|
||||
return reasoningmode.Completion{}, err
|
||||
}
|
||||
completion, err := reasoningmode.ApplySuccessfulTurn(state, input.Execution, input.At, input.Idle)
|
||||
if err != nil {
|
||||
return reasoningmode.Completion{}, err
|
||||
}
|
||||
if err = updateReasoningState(ctx, tx, input.Scope, completion.Next, input.At); err != nil {
|
||||
return reasoningmode.Completion{}, err
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `INSERT INTO reasoning_mode_turns
|
||||
(id,tenant_key,channel,turn_id,external_actor_id,execution_mode,round_number,showed_hint,auto_closed,showed_onboarding)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
|
||||
ON CONFLICT (tenant_key,channel,turn_id) DO NOTHING`,
|
||||
newSettingsID(), input.Scope.TenantKey, input.Scope.Channel, input.TurnID,
|
||||
input.Scope.ExternalActorID, string(input.Execution), completion.RoundNumber,
|
||||
completion.ShowHint, completion.AutoClosed, completion.ShowOnboarding,
|
||||
)
|
||||
if err != nil {
|
||||
return reasoningmode.Completion{}, fmt.Errorf("insert reasoning turn completion: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return reasoningmode.Completion{}, errors.New("insert reasoning turn completion affected unexpected rows")
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return reasoningmode.Completion{}, fmt.Errorf("commit reasoning turn completion: %w", err)
|
||||
}
|
||||
return completion, nil
|
||||
}
|
||||
|
||||
func ensureReasoningState(ctx context.Context, tx pgx.Tx, scope reasoningmode.Scope) error {
|
||||
_, err := tx.Exec(ctx, `INSERT INTO reasoning_mode_states
|
||||
(tenant_key,channel,external_actor_id,mode,max_rounds,rounds_used,hint_enabled)
|
||||
VALUES($1,$2,$3,'quick',10,0,TRUE)
|
||||
ON CONFLICT (tenant_key,channel,external_actor_id) DO NOTHING`,
|
||||
scope.TenantKey, scope.Channel, scope.ExternalActorID,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ensure reasoning state: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func selectReasoningStateForUpdate(ctx context.Context, tx pgx.Tx, scope reasoningmode.Scope) (reasoningmode.State, error) {
|
||||
return scanReasoningState(tx.QueryRow(ctx, `SELECT mode,max_rounds,rounds_used,hint_enabled,last_activity_at,expires_at,onboarding_shown_at
|
||||
FROM reasoning_mode_states
|
||||
WHERE tenant_key=$1 AND channel=$2 AND external_actor_id=$3
|
||||
FOR UPDATE`, scope.TenantKey, scope.Channel, scope.ExternalActorID))
|
||||
}
|
||||
|
||||
func selectReasoningState(ctx context.Context, tx pgx.Tx, scope reasoningmode.Scope) (reasoningmode.State, error) {
|
||||
return scanReasoningState(tx.QueryRow(ctx, `SELECT mode,max_rounds,rounds_used,hint_enabled,last_activity_at,expires_at,onboarding_shown_at
|
||||
FROM reasoning_mode_states
|
||||
WHERE tenant_key=$1 AND channel=$2 AND external_actor_id=$3`, scope.TenantKey, scope.Channel, scope.ExternalActorID))
|
||||
}
|
||||
|
||||
func scanReasoningState(row pgx.Row) (reasoningmode.State, error) {
|
||||
var (
|
||||
state reasoningmode.State
|
||||
mode string
|
||||
last pgtype.Timestamptz
|
||||
expires pgtype.Timestamptz
|
||||
onboarding pgtype.Timestamptz
|
||||
)
|
||||
if err := row.Scan(&mode, &state.MaxRounds, &state.RoundsUsed, &state.HintEnabled, &last, &expires, &onboarding); err != nil {
|
||||
return reasoningmode.State{}, fmt.Errorf("scan reasoning state: %w", err)
|
||||
}
|
||||
state.Mode = reasoningmode.Mode(mode)
|
||||
if last.Valid {
|
||||
state.LastActivityAt = last.Time
|
||||
}
|
||||
if expires.Valid {
|
||||
state.ExpiresAt = expires.Time
|
||||
}
|
||||
if onboarding.Valid {
|
||||
state.OnboardingShown = true
|
||||
state.OnboardingShownAt = onboarding.Time
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
func updateReasoningState(ctx context.Context, tx pgx.Tx, scope reasoningmode.Scope, state reasoningmode.State, now time.Time) error {
|
||||
_, err := tx.Exec(ctx, `UPDATE reasoning_mode_states SET
|
||||
mode=$4,max_rounds=$5,rounds_used=$6,hint_enabled=$7,
|
||||
last_activity_at=$8,expires_at=$9,onboarding_shown_at=$10,updated_at=$11
|
||||
WHERE tenant_key=$1 AND channel=$2 AND external_actor_id=$3`,
|
||||
scope.TenantKey, scope.Channel, scope.ExternalActorID,
|
||||
string(state.Mode), state.MaxRounds, state.RoundsUsed, state.HintEnabled,
|
||||
nullableTime(state.LastActivityAt), nullableTime(state.ExpiresAt), nullableTime(state.OnboardingShownAt), now,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("update reasoning state: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func nullableTime(value time.Time) any {
|
||||
if value.IsZero() {
|
||||
return nil
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func validateReasoningScope(scope reasoningmode.Scope) error {
|
||||
if strings.TrimSpace(scope.TenantKey) == "" || strings.TrimSpace(scope.Channel) == "" || strings.TrimSpace(scope.ExternalActorID) == "" {
|
||||
return errors.New("reasoning mode scope is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ reasoningmode.Repository = (*Store)(nil)
|
||||
@@ -0,0 +1,59 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReasoningModeRepositoryUsesScopedAtomicStateTransitions(t *testing.T) {
|
||||
data, err := os.ReadFile("reasoning_mode.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := strings.ToUpper(string(data))
|
||||
for _, required := range []string{
|
||||
"REASONING_MODE_STATES",
|
||||
"TENANT_KEY=$1",
|
||||
"CHANNEL=$2",
|
||||
"EXTERNAL_ACTOR_ID=$3",
|
||||
"FOR UPDATE",
|
||||
"REASONINGMODE.MODEQUICK",
|
||||
"REASONINGMODE.MODEREASONING",
|
||||
"STRING(STATE.MODE)",
|
||||
"EXPIRES_AT",
|
||||
"MAX_ROUNDS",
|
||||
"HINT_ENABLED",
|
||||
} {
|
||||
if !strings.Contains(source, required) {
|
||||
t.Errorf("reasoning repository missing %q", required)
|
||||
}
|
||||
}
|
||||
if strings.Count(source, "BEGINTX") < 4 || strings.Count(source, "TX.COMMIT") < 4 {
|
||||
t.Fatal("state transitions must use explicit transactions")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReasoningModeRepositoryMakesTurnCompletionIdempotent(t *testing.T) {
|
||||
data, err := os.ReadFile("reasoning_mode.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := strings.ToUpper(string(data))
|
||||
for _, required := range []string{
|
||||
"REASONING_MODE_TURNS",
|
||||
"ON CONFLICT (TENANT_KEY,CHANNEL,TURN_ID) DO NOTHING",
|
||||
"ROWSAFFECTED",
|
||||
"APPLYSUCCESSFULTURN",
|
||||
"SELECT ROUND_NUMBER,SHOWED_HINT,AUTO_CLOSED,SHOWED_ONBOARDING",
|
||||
"JOIN MESSAGES M ON M.ID=T.REQUEST_MESSAGE_ID",
|
||||
"JOIN CHANNEL_ACTORS A ON A.ID=M.ACTOR_ID",
|
||||
"T.ID=$1 AND T.TENANT_KEY=$2 AND T.CHANNEL=$3",
|
||||
"A.EXTERNAL_ACTOR_ID=$4",
|
||||
"STATUS != \"SUCCEEDED\"",
|
||||
} {
|
||||
if !strings.Contains(source, required) {
|
||||
t.Errorf("turn completion repository missing %q", required)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/reasoningmode"
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
@@ -37,6 +38,14 @@ func (r *SettingsRepository) SetPreference(ctx context.Context, tenant, channel,
|
||||
_, err := r.store.pool.Exec(ctx, `INSERT INTO user_preferences(tenant_key,channel,external_actor_id,language_mode,locale) VALUES($1,$2,$3,$4,$5) ON CONFLICT(tenant_key,channel,external_actor_id) DO UPDATE SET language_mode=EXCLUDED.language_mode,locale=EXCLUDED.locale,updated_at=NOW()`, tenant, channel, staff, mode, locale)
|
||||
return err
|
||||
}
|
||||
func (r *SettingsRepository) SetReasoningMaxRounds(ctx context.Context, tenant, channel, staff string, rounds int, now time.Time) error {
|
||||
_, err := r.store.SetMaxRounds(ctx, reasoningmode.Scope{TenantKey: tenant, Channel: channel, ExternalActorID: staff}, rounds, now)
|
||||
return err
|
||||
}
|
||||
func (r *SettingsRepository) SetReasoningHintEnabled(ctx context.Context, tenant, channel, staff string, enabled bool, now time.Time) error {
|
||||
_, err := r.store.SetHintEnabled(ctx, reasoningmode.Scope{TenantKey: tenant, Channel: channel, ExternalActorID: staff}, enabled, now)
|
||||
return err
|
||||
}
|
||||
func (r *SettingsRepository) GetPreference(ctx context.Context, tenant, channel, staff string) (string, error) {
|
||||
var locale string
|
||||
err := r.store.pool.QueryRow(ctx, `SELECT locale FROM user_preferences WHERE tenant_key=$1 AND channel=$2 AND external_actor_id=$3`, tenant, channel, staff).Scan(&locale)
|
||||
|
||||
@@ -49,7 +49,7 @@ func (s *Store) Claim(ctx context.Context, limit int, maxAttempts int, staleBefo
|
||||
FROM candidates c
|
||||
WHERE sc.id = c.id
|
||||
RETURNING sc.id, sc.tenant_key, sc.channel, sc.turn_id,
|
||||
sc.notification_attempts, sc.created_at, sc.faq_record_id
|
||||
sc.notification_attempts, sc.created_at, sc.faq_record_id, sc.trigger_type
|
||||
)
|
||||
SELECT
|
||||
cl.id,
|
||||
@@ -62,7 +62,8 @@ func (s *Store) Claim(ctx context.Context, limit int, maxAttempts int, staleBefo
|
||||
COALESCE(c.conversation_type, 'direct') AS conversation_type,
|
||||
m.created_at AS asked_at,
|
||||
COALESCE(history.previous_questions, ARRAY[]::TEXT[]) AS previous_questions,
|
||||
cl.faq_record_id
|
||||
cl.faq_record_id,
|
||||
cl.trigger_type
|
||||
FROM claimed cl
|
||||
JOIN turns t ON t.id = cl.turn_id
|
||||
AND t.tenant_key = cl.tenant_key
|
||||
@@ -110,16 +111,18 @@ func (s *Store) Claim(ctx context.Context, limit int, maxAttempts int, staleBefo
|
||||
askedAt time.Time
|
||||
previousQuestions []string
|
||||
faqRecordID string
|
||||
triggerType string
|
||||
)
|
||||
if err := rows.Scan(&id, &tenantKey, &channel, &turnID, &attempts,
|
||||
&question, &senderName, &conversationType, &askedAt,
|
||||
&previousQuestions, &faqRecordID); err != nil {
|
||||
&previousQuestions, &faqRecordID, &triggerType); err != nil {
|
||||
rows.Close()
|
||||
return nil, fmt.Errorf("claim scan: %w", err)
|
||||
}
|
||||
cases = append(cases, coverage.PendingSupportCase{
|
||||
SupportNotification: coverage.SupportNotification{
|
||||
CaseID: id,
|
||||
TriggerType: triggerType,
|
||||
Question: question,
|
||||
SenderName: senderName,
|
||||
Channel: channel,
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSupportNotificationClaimReadsTriggerType(t *testing.T) {
|
||||
data, err := os.ReadFile("support_notifications.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := strings.ToUpper(string(data))
|
||||
for _, required := range []string{"SC.TRIGGER_TYPE", "CL.TRIGGER_TYPE", "TRIGGERTYPE"} {
|
||||
if !strings.Contains(source, required) {
|
||||
t.Errorf("support claim missing %q", required)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user