fix(faq): prevent duplicate entries when a create is retried
A caller that resends CreateFAQEntry before the first call answers could create several rows for the same standard question. Indexing runs inline and the embedding call retries with exponential backoff, so one create can take far longer than an impatient caller waits; meanwhile the duplicate-question check only looked at ChunkStatusIndexed, so a sibling create still mid-flight was invisible and every retry passed the check. - Serialize concurrent creates of the same question behind a Redis SetNX guard, keyed by tenant + knowledge base + question hash, with an in-process fallback when Redis is unavailable so an outage cannot block FAQ authoring. - Widen the duplicate check to every non-deleted status. This also fixes ChunkStatusDefault entries, which are listed to users but never blocked duplicates. - Bound the indexing step of an interactive create so a degraded embedding service cannot stretch the request out; bulk and background indexing keep the full retry budget. - Report a failed rollback instead of discarding the error, since a leftover stored chunk is hidden from the list yet now matches the duplicate check.main
parent
1985a59b69
commit
03d6f90c5a
|
|
@ -735,10 +735,20 @@ func (r *chunkRepository) FindFAQChunkWithDuplicateQuestion(
|
|||
return nil, nil
|
||||
}
|
||||
|
||||
// Every non-deleted status counts, including ChunkStatusStored: a chunk that
|
||||
// is written but not yet indexed is a sibling create still in flight, and
|
||||
// skipping it lets a retried request insert a second row for the same
|
||||
// question. Soft-deleted rows are excluded by GORM.
|
||||
db := r.db.WithContext(ctx).
|
||||
Select("id, metadata").
|
||||
Where("tenant_id = ? AND knowledge_base_id = ? AND chunk_type = ? AND status = ? AND id != ?",
|
||||
tenantID, kbID, types.ChunkTypeFAQ, types.ChunkStatusIndexed, excludeChunkID)
|
||||
Where("tenant_id = ? AND knowledge_base_id = ? AND chunk_type = ? AND status IN (?) AND id != ?",
|
||||
tenantID, kbID, types.ChunkTypeFAQ,
|
||||
[]int{
|
||||
int(types.ChunkStatusDefault),
|
||||
int(types.ChunkStatusStored),
|
||||
int(types.ChunkStatusIndexed),
|
||||
},
|
||||
excludeChunkID)
|
||||
|
||||
switch r.db.Name() {
|
||||
case "mysql":
|
||||
|
|
|
|||
|
|
@ -124,6 +124,15 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
|
|||
return types.NewPageResult(total, page, entries), nil
|
||||
}
|
||||
|
||||
// faqCreateIndexBudget caps the indexing step of a single interactive FAQ
|
||||
// create. Indexing embeds inline and the embedding call retries with
|
||||
// exponential backoff, so a degraded embedding service can stretch one create
|
||||
// past ten seconds — long enough for an impatient caller to resend and pile up
|
||||
// concurrent creates. Failing fast is the better trade here: the caller can
|
||||
// retry a clear error, whereas a request left hanging invites duplicates.
|
||||
// Background and bulk indexing keep the full retry budget.
|
||||
const faqCreateIndexBudget = 5 * time.Second
|
||||
|
||||
// CreateFAQEntry creates a single FAQ entry synchronously.
|
||||
func (s *knowledgeService) CreateFAQEntry(ctx context.Context,
|
||||
kbID string, payload *types.FAQEntryPayload,
|
||||
|
|
@ -152,6 +161,14 @@ func (s *knowledgeService) CreateFAQEntry(ctx context.Context,
|
|||
return nil, err
|
||||
}
|
||||
|
||||
// 同一标准问的并发创建必须串行:下面的重复校验只看得到已落库的条目,
|
||||
// 拦不住还在索引中的兄弟请求(上游超时重试就会造出这种并发)。
|
||||
releaseGuard, err := s.acquireFAQCreateGuard(ctx, tenantID, kb.ID, meta.StandardQuestion)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer releaseGuard()
|
||||
|
||||
// 检查标准问和相似问是否与其他条目重复
|
||||
if err := s.checkFAQQuestionDuplicate(ctx, tenantID, kb.ID, "", meta); err != nil {
|
||||
return nil, err
|
||||
|
|
@ -212,11 +229,18 @@ func (s *knowledgeService) CreateFAQEntry(ctx context.Context,
|
|||
return nil, fmt.Errorf("failed to create chunk: %w", err)
|
||||
}
|
||||
|
||||
// 索引chunk
|
||||
if err := s.indexFAQChunks(ctx, kb, faqKnowledge, []*types.Chunk{chunk}, embeddingModel, true, false); err != nil {
|
||||
// 如果索引失败,删除已创建的chunk
|
||||
_ = s.chunkService.DeleteChunk(ctx, chunk.ID)
|
||||
return nil, fmt.Errorf("failed to index chunk: %w", err)
|
||||
// 索引chunk:交互式创建给索引步骤设硬上限,避免 embedding 抖动把请求拖长
|
||||
indexCtx, cancelIndex := context.WithTimeout(ctx, faqCreateIndexBudget)
|
||||
indexErr := s.indexFAQChunks(indexCtx, kb, faqKnowledge, []*types.Chunk{chunk}, embeddingModel, true, false)
|
||||
cancelIndex()
|
||||
if indexErr != nil {
|
||||
// 如果索引失败,删除已创建的chunk。回滚失败会留下一条 stored 状态的
|
||||
// 残留:它不出现在列表里,却会被重复校验命中,因此必须告警而非静默。
|
||||
if delErr := s.chunkService.DeleteChunk(ctx, chunk.ID); delErr != nil {
|
||||
logger.Errorf(ctx,
|
||||
"CreateFAQEntry: rollback failed, chunk %s left in stored state: %v", chunk.ID, delErr)
|
||||
}
|
||||
return nil, fmt.Errorf("failed to index chunk: %w", indexErr)
|
||||
}
|
||||
|
||||
// 更新chunk状态为已索引
|
||||
|
|
|
|||
|
|
@ -0,0 +1,89 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
werrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// faqCreateGuardTTL bounds how long one CreateFAQEntry may hold the
|
||||
// per-question guard. A single create runs the embedding call inline and that
|
||||
// call retries with exponential backoff, so the worst case is well past ten
|
||||
// seconds; the TTL only has to outlive that while still releasing the question
|
||||
// reasonably soon after an instance dies mid-create.
|
||||
const faqCreateGuardTTL = 60 * time.Second
|
||||
|
||||
// faqCreateGuardReleaseTimeout caps the Redis DEL issued on release so a slow
|
||||
// Redis cannot extend the request past the work it already finished.
|
||||
const faqCreateGuardReleaseTimeout = 2 * time.Second
|
||||
|
||||
// faqCreateInflight is the single-instance fallback used when Redis is absent
|
||||
// (Lite mode) or momentarily unreachable.
|
||||
var faqCreateInflight sync.Map // guard key -> struct{}
|
||||
|
||||
// faqCreateGuardKey derives the guard key from the standard question. The
|
||||
// question is hashed rather than embedded verbatim so arbitrary user text
|
||||
// cannot inject separators into the Redis key namespace.
|
||||
func faqCreateGuardKey(tenantID uint64, kbID string, standardQuestion string) string {
|
||||
sum := sha256.Sum256([]byte(standardQuestion))
|
||||
return fmt.Sprintf("faq:create:%d:%s:%s", tenantID, kbID, hex.EncodeToString(sum[:16]))
|
||||
}
|
||||
|
||||
// acquireFAQCreateGuard serializes concurrent creates of the same standard
|
||||
// question within a knowledge base and returns a release function.
|
||||
//
|
||||
// The duplicate-question check can only see entries that are already committed,
|
||||
// but a create stays in flight for seconds while its embedding is computed. An
|
||||
// upstream that retries before the first call answers therefore lands several
|
||||
// identical creates on different instances, each passing the check and each
|
||||
// inserting its own row. This guard closes that window: the first caller wins
|
||||
// and the retries get a conflict instead of a second row.
|
||||
//
|
||||
// When Redis is unavailable the guard degrades to a process-local map rather
|
||||
// than rejecting the write, so a Redis outage cannot block FAQ authoring; the
|
||||
// cross-instance protection is simply lost for the duration.
|
||||
func (s *knowledgeService) acquireFAQCreateGuard(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
kbID string,
|
||||
standardQuestion string,
|
||||
) (func(), error) {
|
||||
key := faqCreateGuardKey(tenantID, kbID, standardQuestion)
|
||||
|
||||
if s.redisClient != nil {
|
||||
acquired, err := s.redisClient.SetNX(ctx, key, "1", faqCreateGuardTTL).Result()
|
||||
switch {
|
||||
case err != nil:
|
||||
logger.Warnf(ctx,
|
||||
"CreateFAQEntry: Redis guard unavailable, falling back to in-process guard: %v", err)
|
||||
case !acquired:
|
||||
return nil, faqCreateConflictError()
|
||||
default:
|
||||
return func() {
|
||||
releaseCtx, cancel := context.WithTimeout(
|
||||
context.WithoutCancel(ctx), faqCreateGuardReleaseTimeout)
|
||||
defer cancel()
|
||||
if err := s.redisClient.Del(releaseCtx, key).Err(); err != nil {
|
||||
logger.Warnf(releaseCtx,
|
||||
"CreateFAQEntry: failed to release guard %s (expires in %s): %v",
|
||||
key, faqCreateGuardTTL, err)
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
if _, loaded := faqCreateInflight.LoadOrStore(key, struct{}{}); loaded {
|
||||
return nil, faqCreateConflictError()
|
||||
}
|
||||
return func() { faqCreateInflight.Delete(key) }, nil
|
||||
}
|
||||
|
||||
func faqCreateConflictError() error {
|
||||
return werrors.NewConflictError("相同标准问的 FAQ 条目正在创建中,请勿重复提交")
|
||||
}
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func newGuardService(t *testing.T) *knowledgeService {
|
||||
t.Helper()
|
||||
mr, err := miniredis.Run()
|
||||
if err != nil {
|
||||
t.Fatalf("start miniredis: %v", err)
|
||||
}
|
||||
t.Cleanup(mr.Close)
|
||||
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
return &knowledgeService{redisClient: rdb}
|
||||
}
|
||||
|
||||
func TestAcquireFAQCreateGuardRejectsConcurrentSameQuestion(t *testing.T) {
|
||||
svc := newGuardService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
release, err := svc.acquireFAQCreateGuard(ctx, 1, "kb-1", "哈哈哈")
|
||||
if err != nil {
|
||||
t.Fatalf("first acquire failed: %v", err)
|
||||
}
|
||||
|
||||
if _, err := svc.acquireFAQCreateGuard(ctx, 1, "kb-1", "哈哈哈"); err == nil {
|
||||
t.Fatal("expected the retry to be rejected while the first create is in flight")
|
||||
}
|
||||
|
||||
// Once the first create finishes the question is writable again, so a real
|
||||
// retry after a genuine failure is not permanently blocked.
|
||||
release()
|
||||
release2, err := svc.acquireFAQCreateGuard(ctx, 1, "kb-1", "哈哈哈")
|
||||
if err != nil {
|
||||
t.Fatalf("acquire after release failed: %v", err)
|
||||
}
|
||||
release2()
|
||||
}
|
||||
|
||||
func TestAcquireFAQCreateGuardIsolatesUnrelatedCreates(t *testing.T) {
|
||||
svc := newGuardService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
release, err := svc.acquireFAQCreateGuard(ctx, 1, "kb-1", "哈哈哈")
|
||||
if err != nil {
|
||||
t.Fatalf("acquire failed: %v", err)
|
||||
}
|
||||
defer release()
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
tenantID uint64
|
||||
kbID string
|
||||
question string
|
||||
}{
|
||||
{"different question", 1, "kb-1", "呵呵呵"},
|
||||
{"different knowledge base", 1, "kb-2", "哈哈哈"},
|
||||
{"different tenant", 2, "kb-1", "哈哈哈"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
release, err := svc.acquireFAQCreateGuard(ctx, tc.tenantID, tc.kbID, tc.question)
|
||||
if err != nil {
|
||||
t.Fatalf("acquire failed: %v", err)
|
||||
}
|
||||
release()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcquireFAQCreateGuardFallsBackWithoutRedis(t *testing.T) {
|
||||
svc := &knowledgeService{}
|
||||
ctx := context.Background()
|
||||
|
||||
release, err := svc.acquireFAQCreateGuard(ctx, 1, "kb-lite", "哈哈哈")
|
||||
if err != nil {
|
||||
t.Fatalf("first acquire failed: %v", err)
|
||||
}
|
||||
|
||||
if _, err := svc.acquireFAQCreateGuard(ctx, 1, "kb-lite", "哈哈哈"); err == nil {
|
||||
t.Fatal("expected in-process guard to reject the concurrent create")
|
||||
}
|
||||
|
||||
release()
|
||||
release2, err := svc.acquireFAQCreateGuard(ctx, 1, "kb-lite", "哈哈哈")
|
||||
if err != nil {
|
||||
t.Fatalf("acquire after release failed: %v", err)
|
||||
}
|
||||
release2()
|
||||
}
|
||||
Loading…
Reference in New Issue