feat(knowledge): enhance activity logging for FAQ imports

- Added new actions for FAQ import lifecycle: `faq.import_started`, `faq.import_completed`, and `faq.import_failed`.
- Updated activity details to include success, failure, and skipped counts for FAQ imports.
- Enhanced UI to display additional activity information, including filtering options and clearer summaries.
- Implemented tests to validate the new FAQ import outcomes and activity details.

This commit improves the tracking and visibility of FAQ import activities within the knowledge base, ensuring better audit trails and user feedback.
This commit is contained in:
wizardchen
2026-07-22 20:08:31 +08:00
committed by lyingbug
parent a3a0308b62
commit 5af8eae81d
14 changed files with 650 additions and 100 deletions
+43 -1
View File
@@ -3,12 +3,16 @@ package service
import (
"context"
"encoding/json"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
const auditScopeKnowledgeBase = "knowledge_base"
const (
auditScopeKnowledgeBase = "knowledge_base"
kbActivitySampleTitleLimit = 5
)
type kbActivityTaskMetadata struct {
TaskID string
@@ -39,6 +43,44 @@ func kbActivityTrigger(ctx context.Context) string {
return "system"
}
// kbActivityAppendSampleTitles adds a bounded, human-readable preview of batch
// mutations into activity details. The first sample is also mirrored as title so
// list views can show what was affected without opening the drawer.
func kbActivityAppendSampleTitles(details map[string]any, titles ...string) {
if details == nil {
return
}
samples := make([]string, 0, kbActivitySampleTitleLimit)
seen := make(map[string]struct{}, kbActivitySampleTitleLimit)
appendSample := func(title string) {
title = strings.TrimSpace(title)
if title == "" {
return
}
if _, ok := seen[title]; ok {
return
}
if len(samples) >= kbActivitySampleTitleLimit {
return
}
seen[title] = struct{}{}
samples = append(samples, title)
}
if existing, ok := details["title"].(string); ok {
appendSample(existing)
}
for _, title := range titles {
appendSample(title)
}
if len(samples) == 0 {
return
}
details["title"] = samples[0]
if len(samples) > 1 {
details["titles"] = samples
}
}
// withKBActivitySuppressed is used for high-volume child mutations inside a
// composite task. The task's bounded summary event remains visible, while one
// sync run cannot flood the audit table with thousands of per-item rows.
@@ -52,6 +52,60 @@ func TestRecordKBActivityCarriesInitiatorAndTaskMetadata(t *testing.T) {
}
}
func TestFAQImportCompletedOutcome(t *testing.T) {
cases := []struct {
success, failed, skipped int
outcome types.AuditOutcome
}{
{10, 0, 0, types.AuditOutcomeSuccess},
{8, 2, 0, types.AuditOutcomePartial},
{5, 1, 2, types.AuditOutcomePartial},
{0, 1, 1, types.AuditOutcomePartial},
{0, 2, 0, types.AuditOutcomeFailed},
{0, 0, 2, types.AuditOutcomeFailed},
}
for _, tc := range cases {
outcome := faqImportCompletedOutcome(tc.success, tc.failed, tc.skipped)
if outcome != tc.outcome {
t.Fatalf("faqImportCompletedOutcome(%d,%d,%d) = %s, want %s",
tc.success, tc.failed, tc.skipped, outcome, tc.outcome)
}
}
}
func TestFAQImportActivityDetails(t *testing.T) {
payload := &types.FAQImportPayload{Mode: types.FAQBatchModeAppend}
progress := &types.FAQImportProgress{SuccessCount: 0, FailedCount: 1, Total: 2}
details := faqImportActivityDetails(payload, progress, 2)
if details["count"] != 0 {
t.Fatalf("count = %#v, want 0", details["count"])
}
if details["total"] != 2 || details["failed"] != 1 || details["skipped"] != 1 {
t.Fatalf("details = %#v", details)
}
}
func TestKBActivityAppendSampleTitles(t *testing.T) {
details := map[string]any{"count": 3}
kbActivityAppendSampleTitles(details, " Alpha ", "Beta", "Alpha", "Gamma")
if details["title"] != "Alpha" {
t.Fatalf("title = %#v", details["title"])
}
titles, ok := details["titles"].([]string)
if !ok || len(titles) != 3 {
t.Fatalf("titles = %#v", details["titles"])
}
single := map[string]any{"count": 1}
kbActivityAppendSampleTitles(single, "Only one")
if single["title"] != "Only one" {
t.Fatalf("single title = %#v", single["title"])
}
if _, exists := single["titles"]; exists {
t.Fatalf("single titles should be omitted: %#v", single)
}
}
func TestRecordKBActivityCanSuppressCompositeTaskChildren(t *testing.T) {
audit := &captureKBActivityAudit{}
ctx := withKBActivitySuppressed(context.Background())
@@ -61,3 +115,29 @@ func TestRecordKBActivityCanSuppressCompositeTaskChildren(t *testing.T) {
t.Fatalf("suppressed child activity was recorded: %#v", audit.entry)
}
}
// TestKBActivityTriggerReflectsInitiatorIdentity locks in the worker
// attribution used by ProcessKBClone / ProcessKnowledgeMove /
// ProcessKnowledgeListDelete / ProcessKnowledgeListReparse: the task
// trigger must be derived from the restored initiator, not hard-coded to
// "user". A synthetic (API-key) or empty initiator is service-owned work
// and must therefore report "system", matching the empty actor attribution.
func TestKBActivityTriggerReflectsInitiatorIdentity(t *testing.T) {
// Real human initiator → "user".
userCtx := types.TaskInitiator{UserID: "user-1", Role: types.TenantRoleAdmin}.Apply(context.Background())
if got := kbActivityTrigger(userCtx); got != "user" {
t.Fatalf("real initiator trigger = %q, want user", got)
}
// Empty / legacy initiator (e.g. scheduler or API-key origin) → "system".
systemCtx := types.TaskInitiator{}.Apply(context.Background())
if got := kbActivityTrigger(systemCtx); got != "system" {
t.Fatalf("empty initiator trigger = %q, want system", got)
}
// Synthetic API-key user is service identity → "system".
synthCtx := context.WithValue(context.Background(), types.UserIDContextKey, "system-7")
if got := kbActivityTrigger(synthCtx); got != "system" {
t.Fatalf("synthetic user trigger = %q, want system", got)
}
}
@@ -460,7 +460,7 @@ func (s *knowledgeService) ProcessKBClone(ctx context.Context, t *asynq.Task) er
return fmt.Errorf("failed to unmarshal KB clone payload: %w", err)
}
ctx = payload.Initiator.Apply(ctx)
ctx = withKBActivityTask(ctx, payload.TaskID, "user")
ctx = withKBActivityTask(ctx, payload.TaskID, kbActivityTrigger(ctx))
// Add tenant ID to context
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
@@ -995,7 +995,7 @@ func (s *knowledgeService) ProcessKnowledgeMove(ctx context.Context, t *asynq.Ta
return fmt.Errorf("failed to unmarshal knowledge move payload: %w", err)
}
ctx = payload.Initiator.Apply(ctx)
ctx = withKBActivityTask(ctx, payload.TaskID, "user")
ctx = withKBActivityTask(ctx, payload.TaskID, kbActivityTrigger(ctx))
// Add tenant ID to context
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
@@ -629,15 +629,23 @@ func (s *knowledgeService) DeleteKnowledgeList(ctx context.Context, ids []string
if err := s.tenantRepo.AdjustStorageUsed(ctx, tenantInfo.ID, storageAdjust); err != nil {
logger.GetLogger(ctx).WithField("error", err).Errorf("DeleteKnowledge update tenant storage used failed")
}
byKB := make(map[string][]string)
for _, knowledge := range knowledgeList {
byKB[knowledge.KnowledgeBaseID] = append(byKB[knowledge.KnowledgeBaseID], knowledge.ID)
byKB := make(map[string][]*types.Knowledge)
for i := range knowledgeList {
knowledge := knowledgeList[i]
byKB[knowledge.KnowledgeBaseID] = append(byKB[knowledge.KnowledgeBaseID], knowledge)
}
for kbID, knowledgeIDs := range byKB {
for kbID, knowledges := range byKB {
knowledgeIDs := make([]string, 0, len(knowledges))
titles := make([]string, 0, len(knowledges))
for _, knowledge := range knowledges {
knowledgeIDs = append(knowledgeIDs, knowledge.ID)
titles = append(titles, knowledge.Title)
}
details := map[string]any{"count": len(knowledgeIDs)}
if len(knowledgeIDs) <= 20 {
details["knowledge_ids"] = knowledgeIDs
}
kbActivityAppendSampleTitles(details, titles...)
recordKBActivity(ctx, s.audit, tenantInfo.ID, kbID, types.AuditActionKnowledgeBatchDeleted,
"knowledge", "", types.AuditOutcomeSuccess, details)
}
@@ -740,7 +748,7 @@ func (s *knowledgeService) ProcessKnowledgeListDelete(ctx context.Context, t *as
}
ctx = payload.Initiator.Apply(ctx)
taskID, _ := asynq.GetTaskID(ctx)
ctx = withKBActivityTask(ctx, taskID, "user")
ctx = withKBActivityTask(ctx, taskID, kbActivityTrigger(ctx))
logger.Infof(ctx, "Processing knowledge list delete task for %d knowledge items", len(payload.KnowledgeIDs))
+19 -2
View File
@@ -1398,9 +1398,14 @@ func (s *knowledgeService) DeleteFAQEntries(ctx context.Context,
return err
}
}
details := map[string]any{"count": len(chunksToRemove), "source_type": "faq"}
titles := make([]string, 0, len(chunksToRemove))
for _, chunk := range chunksToRemove {
titles = append(titles, faqChunkQuestion(chunk))
}
kbActivityAppendSampleTitles(details, titles...)
recordKBActivity(ctx, s.audit, tenantID, kb.ID, types.AuditActionKnowledgeBatchDeleted,
"faq_entry", "", types.AuditOutcomeSuccess,
map[string]any{"count": len(chunksToRemove), "source_type": "faq"})
"faq_entry", "", types.AuditOutcomeSuccess, details)
return nil
}
@@ -1607,6 +1612,18 @@ func buildFAQKnowledgeTitle(kbName string) string {
return name
}
func faqChunkQuestion(chunk *types.Chunk) string {
if chunk == nil {
return ""
}
if meta, err := chunk.FAQMetadata(); err == nil && meta != nil {
if question := strings.TrimSpace(meta.StandardQuestion); question != "" {
return question
}
}
return strings.TrimSpace(chunk.Content)
}
func (s *knowledgeService) chunkToFAQEntry(chunk *types.Chunk, kb *types.KnowledgeBase, tagSeqIDMap map[string]int64) (*types.FAQEntry, error) {
meta, err := chunk.FAQMetadata()
if err != nil {
@@ -120,6 +120,7 @@ func (s *knowledgeService) UpsertFAQEntries(ctx context.Context,
Mode: payload.Mode,
DryRun: payload.DryRun,
EnqueuedAt: enqueuedAt,
Initiator: types.TaskInitiatorFromContext(ctx),
}
// 阈值:超过 200 条或序列化后超过 50KB 时使用对象存储
@@ -207,6 +208,15 @@ func (s *knowledgeService) UpsertFAQEntries(ctx context.Context,
}
logger.Infof(ctx, "Enqueued FAQ import task: id=%s queue=%s task_id=%s dry_run=%v", info.ID, info.Queue, taskID, payload.DryRun)
if !payload.DryRun {
recordKBActivity(ctx, s.audit, tenantID, kbID, types.AuditActionFAQImportStarted,
"faq_entry", knowledgeID, types.AuditOutcomeAccepted,
map[string]any{
"task_id": taskID, "mode": payload.Mode, "total": len(payload.Entries),
"trigger": kbActivityTrigger(ctx), "processing_status": "pending",
})
}
return taskID, nil
}
@@ -1515,6 +1525,66 @@ func (s *knowledgeService) deleteFAQChunkVectors(ctx context.Context,
return s.repo.UpdateKnowledge(ctx, knowledge)
}
func faqImportCompletedOutcome(successCount, failedCount, skippedCount int) types.AuditOutcome {
if successCount > 0 && (failedCount > 0 || skippedCount > 0) {
return types.AuditOutcomePartial
}
if successCount > 0 {
return types.AuditOutcomeSuccess
}
if failedCount > 0 && skippedCount > 0 {
return types.AuditOutcomePartial
}
if failedCount > 0 || skippedCount > 0 {
return types.AuditOutcomeFailed
}
return types.AuditOutcomeSuccess
}
func faqImportActivityDetails(payload *types.FAQImportPayload, progress *types.FAQImportProgress, totalEntries int) map[string]any {
details := map[string]any{"mode": payload.Mode}
if progress == nil {
return details
}
total := totalEntries
if total <= 0 {
total = progress.Total
}
if total > 0 {
details["total"] = total
}
details["count"] = progress.SuccessCount
if progress.FailedCount > 0 {
details["failed"] = progress.FailedCount
}
skipped := progress.SkippedCount
if skipped <= 0 && total > 0 {
skipped = total - progress.SuccessCount - progress.FailedCount
if skipped < 0 {
skipped = 0
}
}
if skipped > 0 {
details["skipped"] = skipped
}
return details
}
func (s *knowledgeService) recordFAQImportKBActivity(
ctx context.Context,
payload *types.FAQImportPayload,
progress *types.FAQImportProgress,
totalEntries int,
action types.AuditAction,
outcome types.AuditOutcome,
) {
if s == nil || payload == nil || payload.DryRun || payload.KBID == "" {
return
}
recordKBActivity(ctx, s.audit, payload.TenantID, payload.KBID, action,
"faq_entry", payload.KnowledgeID, outcome, faqImportActivityDetails(payload, progress, totalEntries))
}
// ProcessFAQImport handles Asynq FAQ import tasks (including dry run mode)
func (s *knowledgeService) ProcessFAQImport(ctx context.Context, t *asynq.Task) error {
var payload types.FAQImportPayload
@@ -1522,6 +1592,8 @@ func (s *knowledgeService) ProcessFAQImport(ctx context.Context, t *asynq.Task)
logger.Errorf(ctx, "failed to unmarshal FAQ import task payload: %v", err)
return fmt.Errorf("failed to unmarshal task payload: %w", err)
}
ctx = payload.Initiator.Apply(ctx)
ctx = withKBActivityTask(ctx, payload.TaskID, kbActivityTrigger(ctx))
ctx = logger.WithRequestID(ctx, uuid.New().String())
ctx = logger.WithField(ctx, "faq_import", payload.TaskID)
@@ -1660,6 +1732,7 @@ func (s *knowledgeService) ProcessFAQImport(ctx context.Context, t *asynq.Task)
if updateErr := s.updateFAQImportProgressStatus(ctx, payload.TaskID, types.FAQImportStatusFailed, 0, originalTotalEntries, 0, "获取知识库失败", err.Error()); updateErr != nil {
logger.Errorf(ctx, "Failed to update task status to failed: %v", updateErr)
}
s.recordFAQImportKBActivity(ctx, &payload, progress, originalTotalEntries, types.AuditActionFAQImportFailed, types.AuditOutcomeFailed)
}
s.cleanupFAQEntriesFileOnFinalFailure(ctx, payload.EntriesURL, retryCount, maxRetry)
return fmt.Errorf("failed to get knowledge base: %w", err)
@@ -1689,6 +1762,7 @@ func (s *knowledgeService) ProcessFAQImport(ctx context.Context, t *asynq.Task)
if updateErr := s.updateFAQImportProgressStatus(ctx, payload.TaskID, types.FAQImportStatusFailed, 0, originalTotalEntries, 0, "清理未索引数据失败", err.Error()); updateErr != nil {
logger.Errorf(ctx, "Failed to update task status to failed: %v", updateErr)
}
s.recordFAQImportKBActivity(ctx, &payload, progress, originalTotalEntries, types.AuditActionFAQImportFailed, types.AuditOutcomeFailed)
}
s.cleanupFAQEntriesFileOnFinalFailure(ctx, payload.EntriesURL, retryCount, maxRetry)
return fmt.Errorf("failed to delete unindexed chunks: %w", err)
@@ -1745,6 +1819,7 @@ func (s *knowledgeService) ProcessFAQImport(ctx context.Context, t *asynq.Task)
if updateErr := s.updateFAQImportProgressStatus(ctx, payload.TaskID, types.FAQImportStatusFailed, 0, originalTotalEntries, len(validEntries), "导入失败", err.Error()); updateErr != nil {
logger.Errorf(ctx, "Failed to update task status to failed: %v", updateErr)
}
s.recordFAQImportKBActivity(ctx, &payload, progress, originalTotalEntries, types.AuditActionFAQImportFailed, types.AuditOutcomeFailed)
}
s.cleanupFAQEntriesFileOnFinalFailure(ctx, payload.EntriesURL, retryCount, maxRetry)
return fmt.Errorf("FAQ import failed: %w", err)
@@ -1817,6 +1892,17 @@ func (s *knowledgeService) finalizeFAQValidation(ctx context.Context, payload *t
logger.Infof(ctx, "FAQ task completed: %s, dry_run=%v, success: %d, failed: %d",
payload.TaskID, payload.DryRun, progress.SuccessCount, progress.FailedCount)
if !payload.DryRun {
skippedCount := originalTotalEntries - progress.SuccessCount - progress.FailedCount
if skippedCount < 0 {
skippedCount = 0
}
progress.SkippedCount = skippedCount
outcome := faqImportCompletedOutcome(progress.SuccessCount, progress.FailedCount, skippedCount)
s.recordFAQImportKBActivity(ctx, payload, progress, originalTotalEntries,
types.AuditActionFAQImportCompleted, outcome)
}
return nil
}
@@ -3419,7 +3419,7 @@ func (s *knowledgeService) ProcessKnowledgeListReparse(ctx context.Context, t *a
}
ctx = payload.Initiator.Apply(ctx)
taskID, _ := asynq.GetTaskID(ctx)
ctx = withKBActivityTask(ctx, taskID, "user")
ctx = withKBActivityTask(ctx, taskID, kbActivityTrigger(ctx))
logger.Infof(ctx, "Processing knowledge list reparse task for %d knowledge items", len(payload.KnowledgeIDs))