diff --git a/internal/application/repository/chunk.go b/internal/application/repository/chunk.go index 08723f3b..4f0aecbf 100644 --- a/internal/application/repository/chunk.go +++ b/internal/application/repository/chunk.go @@ -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": diff --git a/internal/application/service/knowledge_faq.go b/internal/application/service/knowledge_faq.go index ed82eabb..b0afb1e8 100644 --- a/internal/application/service/knowledge_faq.go +++ b/internal/application/service/knowledge_faq.go @@ -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状态为已索引 diff --git a/internal/application/service/knowledge_faq_create_guard.go b/internal/application/service/knowledge_faq_create_guard.go new file mode 100644 index 00000000..04bb7f56 --- /dev/null +++ b/internal/application/service/knowledge_faq_create_guard.go @@ -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 条目正在创建中,请勿重复提交") +} diff --git a/internal/application/service/knowledge_faq_create_guard_test.go b/internal/application/service/knowledge_faq_create_guard_test.go new file mode 100644 index 00000000..c1b77579 --- /dev/null +++ b/internal/application/service/knowledge_faq_create_guard_test.go @@ -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() +}